UNPKG

67.5 kBJavaScriptView Raw
1import { __assign, __extends } from 'tslib';
2
3/**
4 * @license
5 * Copyright 2017 Google LLC
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19/**
20 * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.
21 */
22var CONSTANTS = {
23 /**
24 * @define {boolean} Whether this is the client Node.js SDK.
25 */
26 NODE_CLIENT: false,
27 /**
28 * @define {boolean} Whether this is the Admin Node.js SDK.
29 */
30 NODE_ADMIN: false,
31 /**
32 * Firebase SDK Version
33 */
34 SDK_VERSION: '${JSCORE_VERSION}'
35};
36
37/**
38 * @license
39 * Copyright 2017 Google LLC
40 *
41 * Licensed under the Apache License, Version 2.0 (the "License");
42 * you may not use this file except in compliance with the License.
43 * You may obtain a copy of the License at
44 *
45 * http://www.apache.org/licenses/LICENSE-2.0
46 *
47 * Unless required by applicable law or agreed to in writing, software
48 * distributed under the License is distributed on an "AS IS" BASIS,
49 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
50 * See the License for the specific language governing permissions and
51 * limitations under the License.
52 */
53/**
54 * Throws an error if the provided assertion is falsy
55 */
56var assert = function (assertion, message) {
57 if (!assertion) {
58 throw assertionError(message);
59 }
60};
61/**
62 * Returns an Error object suitable for throwing.
63 */
64var assertionError = function (message) {
65 return new Error('Firebase Database (' +
66 CONSTANTS.SDK_VERSION +
67 ') INTERNAL ASSERT FAILED: ' +
68 message);
69};
70
71/**
72 * @license
73 * Copyright 2017 Google LLC
74 *
75 * Licensed under the Apache License, Version 2.0 (the "License");
76 * you may not use this file except in compliance with the License.
77 * You may obtain a copy of the License at
78 *
79 * http://www.apache.org/licenses/LICENSE-2.0
80 *
81 * Unless required by applicable law or agreed to in writing, software
82 * distributed under the License is distributed on an "AS IS" BASIS,
83 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
84 * See the License for the specific language governing permissions and
85 * limitations under the License.
86 */
87var stringToByteArray$1 = function (str) {
88 // TODO(user): Use native implementations if/when available
89 var out = [];
90 var p = 0;
91 for (var i = 0; i < str.length; i++) {
92 var c = str.charCodeAt(i);
93 if (c < 128) {
94 out[p++] = c;
95 }
96 else if (c < 2048) {
97 out[p++] = (c >> 6) | 192;
98 out[p++] = (c & 63) | 128;
99 }
100 else if ((c & 0xfc00) === 0xd800 &&
101 i + 1 < str.length &&
102 (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
103 // Surrogate Pair
104 c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
105 out[p++] = (c >> 18) | 240;
106 out[p++] = ((c >> 12) & 63) | 128;
107 out[p++] = ((c >> 6) & 63) | 128;
108 out[p++] = (c & 63) | 128;
109 }
110 else {
111 out[p++] = (c >> 12) | 224;
112 out[p++] = ((c >> 6) & 63) | 128;
113 out[p++] = (c & 63) | 128;
114 }
115 }
116 return out;
117};
118/**
119 * Turns an array of numbers into the string given by the concatenation of the
120 * characters to which the numbers correspond.
121 * @param bytes Array of numbers representing characters.
122 * @return Stringification of the array.
123 */
124var byteArrayToString = function (bytes) {
125 // TODO(user): Use native implementations if/when available
126 var out = [];
127 var pos = 0, c = 0;
128 while (pos < bytes.length) {
129 var c1 = bytes[pos++];
130 if (c1 < 128) {
131 out[c++] = String.fromCharCode(c1);
132 }
133 else if (c1 > 191 && c1 < 224) {
134 var c2 = bytes[pos++];
135 out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
136 }
137 else if (c1 > 239 && c1 < 365) {
138 // Surrogate Pair
139 var c2 = bytes[pos++];
140 var c3 = bytes[pos++];
141 var c4 = bytes[pos++];
142 var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
143 0x10000;
144 out[c++] = String.fromCharCode(0xd800 + (u >> 10));
145 out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
146 }
147 else {
148 var c2 = bytes[pos++];
149 var c3 = bytes[pos++];
150 out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
151 }
152 }
153 return out.join('');
154};
155// We define it as an object literal instead of a class because a class compiled down to es5 can't
156// be treeshaked. https://github.com/rollup/rollup/issues/1691
157// Static lookup maps, lazily populated by init_()
158var base64 = {
159 /**
160 * Maps bytes to characters.
161 */
162 byteToCharMap_: null,
163 /**
164 * Maps characters to bytes.
165 */
166 charToByteMap_: null,
167 /**
168 * Maps bytes to websafe characters.
169 * @private
170 */
171 byteToCharMapWebSafe_: null,
172 /**
173 * Maps websafe characters to bytes.
174 * @private
175 */
176 charToByteMapWebSafe_: null,
177 /**
178 * Our default alphabet, shared between
179 * ENCODED_VALS and ENCODED_VALS_WEBSAFE
180 */
181 ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
182 /**
183 * Our default alphabet. Value 64 (=) is special; it means "nothing."
184 */
185 get ENCODED_VALS() {
186 return this.ENCODED_VALS_BASE + '+/=';
187 },
188 /**
189 * Our websafe alphabet.
190 */
191 get ENCODED_VALS_WEBSAFE() {
192 return this.ENCODED_VALS_BASE + '-_.';
193 },
194 /**
195 * Whether this browser supports the atob and btoa functions. This extension
196 * started at Mozilla but is now implemented by many browsers. We use the
197 * ASSUME_* variables to avoid pulling in the full useragent detection library
198 * but still allowing the standard per-browser compilations.
199 *
200 */
201 HAS_NATIVE_SUPPORT: typeof atob === 'function',
202 /**
203 * Base64-encode an array of bytes.
204 *
205 * @param input An array of bytes (numbers with
206 * value in [0, 255]) to encode.
207 * @param webSafe Boolean indicating we should use the
208 * alternative alphabet.
209 * @return The base64 encoded string.
210 */
211 encodeByteArray: function (input, webSafe) {
212 if (!Array.isArray(input)) {
213 throw Error('encodeByteArray takes an array as a parameter');
214 }
215 this.init_();
216 var byteToCharMap = webSafe
217 ? this.byteToCharMapWebSafe_
218 : this.byteToCharMap_;
219 var output = [];
220 for (var i = 0; i < input.length; i += 3) {
221 var byte1 = input[i];
222 var haveByte2 = i + 1 < input.length;
223 var byte2 = haveByte2 ? input[i + 1] : 0;
224 var haveByte3 = i + 2 < input.length;
225 var byte3 = haveByte3 ? input[i + 2] : 0;
226 var outByte1 = byte1 >> 2;
227 var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
228 var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
229 var outByte4 = byte3 & 0x3f;
230 if (!haveByte3) {
231 outByte4 = 64;
232 if (!haveByte2) {
233 outByte3 = 64;
234 }
235 }
236 output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
237 }
238 return output.join('');
239 },
240 /**
241 * Base64-encode a string.
242 *
243 * @param input A string to encode.
244 * @param webSafe If true, we should use the
245 * alternative alphabet.
246 * @return The base64 encoded string.
247 */
248 encodeString: function (input, webSafe) {
249 // Shortcut for Mozilla browsers that implement
250 // a native base64 encoder in the form of "btoa/atob"
251 if (this.HAS_NATIVE_SUPPORT && !webSafe) {
252 return btoa(input);
253 }
254 return this.encodeByteArray(stringToByteArray$1(input), webSafe);
255 },
256 /**
257 * Base64-decode a string.
258 *
259 * @param input to decode.
260 * @param webSafe True if we should use the
261 * alternative alphabet.
262 * @return string representing the decoded value.
263 */
264 decodeString: function (input, webSafe) {
265 // Shortcut for Mozilla browsers that implement
266 // a native base64 encoder in the form of "btoa/atob"
267 if (this.HAS_NATIVE_SUPPORT && !webSafe) {
268 return atob(input);
269 }
270 return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
271 },
272 /**
273 * Base64-decode a string.
274 *
275 * In base-64 decoding, groups of four characters are converted into three
276 * bytes. If the encoder did not apply padding, the input length may not
277 * be a multiple of 4.
278 *
279 * In this case, the last group will have fewer than 4 characters, and
280 * padding will be inferred. If the group has one or two characters, it decodes
281 * to one byte. If the group has three characters, it decodes to two bytes.
282 *
283 * @param input Input to decode.
284 * @param webSafe True if we should use the web-safe alphabet.
285 * @return bytes representing the decoded value.
286 */
287 decodeStringToByteArray: function (input, webSafe) {
288 this.init_();
289 var charToByteMap = webSafe
290 ? this.charToByteMapWebSafe_
291 : this.charToByteMap_;
292 var output = [];
293 for (var i = 0; i < input.length;) {
294 var byte1 = charToByteMap[input.charAt(i++)];
295 var haveByte2 = i < input.length;
296 var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
297 ++i;
298 var haveByte3 = i < input.length;
299 var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
300 ++i;
301 var haveByte4 = i < input.length;
302 var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
303 ++i;
304 if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
305 throw Error();
306 }
307 var outByte1 = (byte1 << 2) | (byte2 >> 4);
308 output.push(outByte1);
309 if (byte3 !== 64) {
310 var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
311 output.push(outByte2);
312 if (byte4 !== 64) {
313 var outByte3 = ((byte3 << 6) & 0xc0) | byte4;
314 output.push(outByte3);
315 }
316 }
317 }
318 return output;
319 },
320 /**
321 * Lazy static initialization function. Called before
322 * accessing any of the static map variables.
323 * @private
324 */
325 init_: function () {
326 if (!this.byteToCharMap_) {
327 this.byteToCharMap_ = {};
328 this.charToByteMap_ = {};
329 this.byteToCharMapWebSafe_ = {};
330 this.charToByteMapWebSafe_ = {};
331 // We want quick mappings back and forth, so we precompute two maps.
332 for (var i = 0; i < this.ENCODED_VALS.length; i++) {
333 this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
334 this.charToByteMap_[this.byteToCharMap_[i]] = i;
335 this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
336 this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
337 // Be forgiving when decoding and correctly decode both encodings.
338 if (i >= this.ENCODED_VALS_BASE.length) {
339 this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
340 this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
341 }
342 }
343 }
344 }
345};
346/**
347 * URL-safe base64 encoding
348 */
349var base64Encode = function (str) {
350 var utf8Bytes = stringToByteArray$1(str);
351 return base64.encodeByteArray(utf8Bytes, true);
352};
353/**
354 * URL-safe base64 encoding (without "." padding in the end).
355 * e.g. Used in JSON Web Token (JWT) parts.
356 */
357var base64urlEncodeWithoutPadding = function (str) {
358 // Use base64url encoding and remove padding in the end (dot characters).
359 return base64Encode(str).replace(/\./g, '');
360};
361/**
362 * URL-safe base64 decoding
363 *
364 * NOTE: DO NOT use the global atob() function - it does NOT support the
365 * base64Url variant encoding.
366 *
367 * @param str To be decoded
368 * @return Decoded result, if possible
369 */
370var base64Decode = function (str) {
371 try {
372 return base64.decodeString(str, true);
373 }
374 catch (e) {
375 console.error('base64Decode failed: ', e);
376 }
377 return null;
378};
379
380/**
381 * @license
382 * Copyright 2017 Google LLC
383 *
384 * Licensed under the Apache License, Version 2.0 (the "License");
385 * you may not use this file except in compliance with the License.
386 * You may obtain a copy of the License at
387 *
388 * http://www.apache.org/licenses/LICENSE-2.0
389 *
390 * Unless required by applicable law or agreed to in writing, software
391 * distributed under the License is distributed on an "AS IS" BASIS,
392 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
393 * See the License for the specific language governing permissions and
394 * limitations under the License.
395 */
396/**
397 * Do a deep-copy of basic JavaScript Objects or Arrays.
398 */
399function deepCopy(value) {
400 return deepExtend(undefined, value);
401}
402/**
403 * Copy properties from source to target (recursively allows extension
404 * of Objects and Arrays). Scalar values in the target are over-written.
405 * If target is undefined, an object of the appropriate type will be created
406 * (and returned).
407 *
408 * We recursively copy all child properties of plain Objects in the source- so
409 * that namespace- like dictionaries are merged.
410 *
411 * Note that the target can be a function, in which case the properties in
412 * the source Object are copied onto it as static properties of the Function.
413 *
414 * Note: we don't merge __proto__ to prevent prototype pollution
415 */
416function deepExtend(target, source) {
417 if (!(source instanceof Object)) {
418 return source;
419 }
420 switch (source.constructor) {
421 case Date:
422 // Treat Dates like scalars; if the target date object had any child
423 // properties - they will be lost!
424 var dateValue = source;
425 return new Date(dateValue.getTime());
426 case Object:
427 if (target === undefined) {
428 target = {};
429 }
430 break;
431 case Array:
432 // Always copy the array source and overwrite the target.
433 target = [];
434 break;
435 default:
436 // Not a plain Object - treat it as a scalar.
437 return source;
438 }
439 for (var prop in source) {
440 // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202
441 if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {
442 continue;
443 }
444 target[prop] = deepExtend(target[prop], source[prop]);
445 }
446 return target;
447}
448function isValidKey(key) {
449 return key !== '__proto__';
450}
451
452/**
453 * @license
454 * Copyright 2017 Google LLC
455 *
456 * Licensed under the Apache License, Version 2.0 (the "License");
457 * you may not use this file except in compliance with the License.
458 * You may obtain a copy of the License at
459 *
460 * http://www.apache.org/licenses/LICENSE-2.0
461 *
462 * Unless required by applicable law or agreed to in writing, software
463 * distributed under the License is distributed on an "AS IS" BASIS,
464 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
465 * See the License for the specific language governing permissions and
466 * limitations under the License.
467 */
468var Deferred = /** @class */ (function () {
469 function Deferred() {
470 var _this = this;
471 this.reject = function () { };
472 this.resolve = function () { };
473 this.promise = new Promise(function (resolve, reject) {
474 _this.resolve = resolve;
475 _this.reject = reject;
476 });
477 }
478 /**
479 * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around
480 * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
481 * and returns a node-style callback which will resolve or reject the Deferred's promise.
482 */
483 Deferred.prototype.wrapCallback = function (callback) {
484 var _this = this;
485 return function (error, value) {
486 if (error) {
487 _this.reject(error);
488 }
489 else {
490 _this.resolve(value);
491 }
492 if (typeof callback === 'function') {
493 // Attaching noop handler just in case developer wasn't expecting
494 // promises
495 _this.promise.catch(function () { });
496 // Some of our callbacks don't expect a value and our own tests
497 // assert that the parameter length is 1
498 if (callback.length === 1) {
499 callback(error);
500 }
501 else {
502 callback(error, value);
503 }
504 }
505 };
506 };
507 return Deferred;
508}());
509
510/**
511 * @license
512 * Copyright 2021 Google LLC
513 *
514 * Licensed under the Apache License, Version 2.0 (the "License");
515 * you may not use this file except in compliance with the License.
516 * You may obtain a copy of the License at
517 *
518 * http://www.apache.org/licenses/LICENSE-2.0
519 *
520 * Unless required by applicable law or agreed to in writing, software
521 * distributed under the License is distributed on an "AS IS" BASIS,
522 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
523 * See the License for the specific language governing permissions and
524 * limitations under the License.
525 */
526function createMockUserToken(token, projectId) {
527 if (token.uid) {
528 throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');
529 }
530 // Unsecured JWTs use "none" as the algorithm.
531 var header = {
532 alg: 'none',
533 type: 'JWT'
534 };
535 var project = projectId || 'demo-project';
536 var iat = token.iat || 0;
537 var sub = token.sub || token.user_id;
538 if (!sub) {
539 throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");
540 }
541 var payload = __assign({
542 // Set all required fields to decent defaults
543 iss: "https://securetoken.google.com/" + project, aud: project, iat: iat, exp: iat + 3600, auth_time: iat, sub: sub, user_id: sub, firebase: {
544 sign_in_provider: 'custom',
545 identities: {}
546 } }, token);
547 // Unsecured JWTs use the empty string as a signature.
548 var signature = '';
549 return [
550 base64urlEncodeWithoutPadding(JSON.stringify(header)),
551 base64urlEncodeWithoutPadding(JSON.stringify(payload)),
552 signature
553 ].join('.');
554}
555
556/**
557 * @license
558 * Copyright 2017 Google LLC
559 *
560 * Licensed under the Apache License, Version 2.0 (the "License");
561 * you may not use this file except in compliance with the License.
562 * You may obtain a copy of the License at
563 *
564 * http://www.apache.org/licenses/LICENSE-2.0
565 *
566 * Unless required by applicable law or agreed to in writing, software
567 * distributed under the License is distributed on an "AS IS" BASIS,
568 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
569 * See the License for the specific language governing permissions and
570 * limitations under the License.
571 */
572/**
573 * Returns navigator.userAgent string or '' if it's not defined.
574 * @return user agent string
575 */
576function getUA() {
577 if (typeof navigator !== 'undefined' &&
578 typeof navigator['userAgent'] === 'string') {
579 return navigator['userAgent'];
580 }
581 else {
582 return '';
583 }
584}
585/**
586 * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
587 *
588 * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
589 * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
590 * wait for a callback.
591 */
592function isMobileCordova() {
593 return (typeof window !== 'undefined' &&
594 // @ts-ignore Setting up an broadly applicable index signature for Window
595 // just to deal with this case would probably be a bad idea.
596 !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&
597 /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));
598}
599/**
600 * Detect Node.js.
601 *
602 * @return true if Node.js environment is detected.
603 */
604// Node detection logic from: https://github.com/iliakan/detect-node/
605function isNode() {
606 try {
607 return (Object.prototype.toString.call(global.process) === '[object process]');
608 }
609 catch (e) {
610 return false;
611 }
612}
613/**
614 * Detect Browser Environment
615 */
616function isBrowser() {
617 return typeof self === 'object' && self.self === self;
618}
619function isBrowserExtension() {
620 var runtime = typeof chrome === 'object'
621 ? chrome.runtime
622 : typeof browser === 'object'
623 ? browser.runtime
624 : undefined;
625 return typeof runtime === 'object' && runtime.id !== undefined;
626}
627/**
628 * Detect React Native.
629 *
630 * @return true if ReactNative environment is detected.
631 */
632function isReactNative() {
633 return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');
634}
635/** Detects Electron apps. */
636function isElectron() {
637 return getUA().indexOf('Electron/') >= 0;
638}
639/** Detects Internet Explorer. */
640function isIE() {
641 var ua = getUA();
642 return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;
643}
644/** Detects Universal Windows Platform apps. */
645function isUWP() {
646 return getUA().indexOf('MSAppHost/') >= 0;
647}
648/**
649 * Detect whether the current SDK build is the Node version.
650 *
651 * @return true if it's the Node SDK build.
652 */
653function isNodeSdk() {
654 return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;
655}
656/** Returns true if we are running in Safari. */
657function isSafari() {
658 return (!isNode() &&
659 navigator.userAgent.includes('Safari') &&
660 !navigator.userAgent.includes('Chrome'));
661}
662/**
663 * This method checks if indexedDB is supported by current browser/service worker context
664 * @return true if indexedDB is supported by current browser/service worker context
665 */
666function isIndexedDBAvailable() {
667 return typeof indexedDB === 'object';
668}
669/**
670 * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
671 * if errors occur during the database open operation.
672 *
673 * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
674 * private browsing)
675 */
676function validateIndexedDBOpenable() {
677 return new Promise(function (resolve, reject) {
678 try {
679 var preExist_1 = true;
680 var DB_CHECK_NAME_1 = 'validate-browser-context-for-indexeddb-analytics-module';
681 var request_1 = self.indexedDB.open(DB_CHECK_NAME_1);
682 request_1.onsuccess = function () {
683 request_1.result.close();
684 // delete database only when it doesn't pre-exist
685 if (!preExist_1) {
686 self.indexedDB.deleteDatabase(DB_CHECK_NAME_1);
687 }
688 resolve(true);
689 };
690 request_1.onupgradeneeded = function () {
691 preExist_1 = false;
692 };
693 request_1.onerror = function () {
694 var _a;
695 reject(((_a = request_1.error) === null || _a === void 0 ? void 0 : _a.message) || '');
696 };
697 }
698 catch (error) {
699 reject(error);
700 }
701 });
702}
703/**
704 *
705 * This method checks whether cookie is enabled within current browser
706 * @return true if cookie is enabled within current browser
707 */
708function areCookiesEnabled() {
709 if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
710 return false;
711 }
712 return true;
713}
714/**
715 * Polyfill for `globalThis` object.
716 * @returns the `globalThis` object for the given environment.
717 */
718function getGlobal() {
719 if (typeof self !== 'undefined') {
720 return self;
721 }
722 if (typeof window !== 'undefined') {
723 return window;
724 }
725 if (typeof global !== 'undefined') {
726 return global;
727 }
728 throw new Error('Unable to locate global object.');
729}
730
731/**
732 * @license
733 * Copyright 2017 Google LLC
734 *
735 * Licensed under the Apache License, Version 2.0 (the "License");
736 * you may not use this file except in compliance with the License.
737 * You may obtain a copy of the License at
738 *
739 * http://www.apache.org/licenses/LICENSE-2.0
740 *
741 * Unless required by applicable law or agreed to in writing, software
742 * distributed under the License is distributed on an "AS IS" BASIS,
743 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
744 * See the License for the specific language governing permissions and
745 * limitations under the License.
746 */
747var ERROR_NAME = 'FirebaseError';
748// Based on code from:
749// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
750var FirebaseError = /** @class */ (function (_super) {
751 __extends(FirebaseError, _super);
752 function FirebaseError(
753 /** The error code for this error. */
754 code, message,
755 /** Custom data for this error. */
756 customData) {
757 var _this = _super.call(this, message) || this;
758 _this.code = code;
759 _this.customData = customData;
760 /** The custom name for all FirebaseErrors. */
761 _this.name = ERROR_NAME;
762 // Fix For ES5
763 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
764 Object.setPrototypeOf(_this, FirebaseError.prototype);
765 // Maintains proper stack trace for where our error was thrown.
766 // Only available on V8.
767 if (Error.captureStackTrace) {
768 Error.captureStackTrace(_this, ErrorFactory.prototype.create);
769 }
770 return _this;
771 }
772 return FirebaseError;
773}(Error));
774var ErrorFactory = /** @class */ (function () {
775 function ErrorFactory(service, serviceName, errors) {
776 this.service = service;
777 this.serviceName = serviceName;
778 this.errors = errors;
779 }
780 ErrorFactory.prototype.create = function (code) {
781 var data = [];
782 for (var _i = 1; _i < arguments.length; _i++) {
783 data[_i - 1] = arguments[_i];
784 }
785 var customData = data[0] || {};
786 var fullCode = this.service + "/" + code;
787 var template = this.errors[code];
788 var message = template ? replaceTemplate(template, customData) : 'Error';
789 // Service Name: Error message (service/code).
790 var fullMessage = this.serviceName + ": " + message + " (" + fullCode + ").";
791 var error = new FirebaseError(fullCode, fullMessage, customData);
792 return error;
793 };
794 return ErrorFactory;
795}());
796function replaceTemplate(template, data) {
797 return template.replace(PATTERN, function (_, key) {
798 var value = data[key];
799 return value != null ? String(value) : "<" + key + "?>";
800 });
801}
802var PATTERN = /\{\$([^}]+)}/g;
803
804/**
805 * @license
806 * Copyright 2017 Google LLC
807 *
808 * Licensed under the Apache License, Version 2.0 (the "License");
809 * you may not use this file except in compliance with the License.
810 * You may obtain a copy of the License at
811 *
812 * http://www.apache.org/licenses/LICENSE-2.0
813 *
814 * Unless required by applicable law or agreed to in writing, software
815 * distributed under the License is distributed on an "AS IS" BASIS,
816 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
817 * See the License for the specific language governing permissions and
818 * limitations under the License.
819 */
820/**
821 * Evaluates a JSON string into a javascript object.
822 *
823 * @param {string} str A string containing JSON.
824 * @return {*} The javascript object representing the specified JSON.
825 */
826function jsonEval(str) {
827 return JSON.parse(str);
828}
829/**
830 * Returns JSON representing a javascript object.
831 * @param {*} data Javascript object to be stringified.
832 * @return {string} The JSON contents of the object.
833 */
834function stringify(data) {
835 return JSON.stringify(data);
836}
837
838/**
839 * @license
840 * Copyright 2017 Google LLC
841 *
842 * Licensed under the Apache License, Version 2.0 (the "License");
843 * you may not use this file except in compliance with the License.
844 * You may obtain a copy of the License at
845 *
846 * http://www.apache.org/licenses/LICENSE-2.0
847 *
848 * Unless required by applicable law or agreed to in writing, software
849 * distributed under the License is distributed on an "AS IS" BASIS,
850 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
851 * See the License for the specific language governing permissions and
852 * limitations under the License.
853 */
854/**
855 * Decodes a Firebase auth. token into constituent parts.
856 *
857 * Notes:
858 * - May return with invalid / incomplete claims if there's no native base64 decoding support.
859 * - Doesn't check if the token is actually valid.
860 */
861var decode = function (token) {
862 var header = {}, claims = {}, data = {}, signature = '';
863 try {
864 var parts = token.split('.');
865 header = jsonEval(base64Decode(parts[0]) || '');
866 claims = jsonEval(base64Decode(parts[1]) || '');
867 signature = parts[2];
868 data = claims['d'] || {};
869 delete claims['d'];
870 }
871 catch (e) { }
872 return {
873 header: header,
874 claims: claims,
875 data: data,
876 signature: signature
877 };
878};
879/**
880 * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the
881 * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.
882 *
883 * Notes:
884 * - May return a false negative if there's no native base64 decoding support.
885 * - Doesn't check if the token is actually valid.
886 */
887var isValidTimestamp = function (token) {
888 var claims = decode(token).claims;
889 var now = Math.floor(new Date().getTime() / 1000);
890 var validSince = 0, validUntil = 0;
891 if (typeof claims === 'object') {
892 if (claims.hasOwnProperty('nbf')) {
893 validSince = claims['nbf'];
894 }
895 else if (claims.hasOwnProperty('iat')) {
896 validSince = claims['iat'];
897 }
898 if (claims.hasOwnProperty('exp')) {
899 validUntil = claims['exp'];
900 }
901 else {
902 // token will expire after 24h by default
903 validUntil = validSince + 86400;
904 }
905 }
906 return (!!now &&
907 !!validSince &&
908 !!validUntil &&
909 now >= validSince &&
910 now <= validUntil);
911};
912/**
913 * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.
914 *
915 * Notes:
916 * - May return null if there's no native base64 decoding support.
917 * - Doesn't check if the token is actually valid.
918 */
919var issuedAtTime = function (token) {
920 var claims = decode(token).claims;
921 if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {
922 return claims['iat'];
923 }
924 return null;
925};
926/**
927 * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.
928 *
929 * Notes:
930 * - May return a false negative if there's no native base64 decoding support.
931 * - Doesn't check if the token is actually valid.
932 */
933var isValidFormat = function (token) {
934 var decoded = decode(token), claims = decoded.claims;
935 return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');
936};
937/**
938 * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.
939 *
940 * Notes:
941 * - May return a false negative if there's no native base64 decoding support.
942 * - Doesn't check if the token is actually valid.
943 */
944var isAdmin = function (token) {
945 var claims = decode(token).claims;
946 return typeof claims === 'object' && claims['admin'] === true;
947};
948
949/**
950 * @license
951 * Copyright 2017 Google LLC
952 *
953 * Licensed under the Apache License, Version 2.0 (the "License");
954 * you may not use this file except in compliance with the License.
955 * You may obtain a copy of the License at
956 *
957 * http://www.apache.org/licenses/LICENSE-2.0
958 *
959 * Unless required by applicable law or agreed to in writing, software
960 * distributed under the License is distributed on an "AS IS" BASIS,
961 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
962 * See the License for the specific language governing permissions and
963 * limitations under the License.
964 */
965function contains(obj, key) {
966 return Object.prototype.hasOwnProperty.call(obj, key);
967}
968function safeGet(obj, key) {
969 if (Object.prototype.hasOwnProperty.call(obj, key)) {
970 return obj[key];
971 }
972 else {
973 return undefined;
974 }
975}
976function isEmpty(obj) {
977 for (var key in obj) {
978 if (Object.prototype.hasOwnProperty.call(obj, key)) {
979 return false;
980 }
981 }
982 return true;
983}
984function map(obj, fn, contextObj) {
985 var res = {};
986 for (var key in obj) {
987 if (Object.prototype.hasOwnProperty.call(obj, key)) {
988 res[key] = fn.call(contextObj, obj[key], key, obj);
989 }
990 }
991 return res;
992}
993/**
994 * Deep equal two objects. Support Arrays and Objects.
995 */
996function deepEqual(a, b) {
997 if (a === b) {
998 return true;
999 }
1000 var aKeys = Object.keys(a);
1001 var bKeys = Object.keys(b);
1002 for (var _i = 0, aKeys_1 = aKeys; _i < aKeys_1.length; _i++) {
1003 var k = aKeys_1[_i];
1004 if (!bKeys.includes(k)) {
1005 return false;
1006 }
1007 var aProp = a[k];
1008 var bProp = b[k];
1009 if (isObject(aProp) && isObject(bProp)) {
1010 if (!deepEqual(aProp, bProp)) {
1011 return false;
1012 }
1013 }
1014 else if (aProp !== bProp) {
1015 return false;
1016 }
1017 }
1018 for (var _a = 0, bKeys_1 = bKeys; _a < bKeys_1.length; _a++) {
1019 var k = bKeys_1[_a];
1020 if (!aKeys.includes(k)) {
1021 return false;
1022 }
1023 }
1024 return true;
1025}
1026function isObject(thing) {
1027 return thing !== null && typeof thing === 'object';
1028}
1029
1030/**
1031 * @license
1032 * Copyright 2017 Google LLC
1033 *
1034 * Licensed under the Apache License, Version 2.0 (the "License");
1035 * you may not use this file except in compliance with the License.
1036 * You may obtain a copy of the License at
1037 *
1038 * http://www.apache.org/licenses/LICENSE-2.0
1039 *
1040 * Unless required by applicable law or agreed to in writing, software
1041 * distributed under the License is distributed on an "AS IS" BASIS,
1042 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1043 * See the License for the specific language governing permissions and
1044 * limitations under the License.
1045 */
1046/**
1047 * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a
1048 * params object (e.g. {arg: 'val', arg2: 'val2'})
1049 * Note: You must prepend it with ? when adding it to a URL.
1050 */
1051function querystring(querystringParams) {
1052 var params = [];
1053 var _loop_1 = function (key, value) {
1054 if (Array.isArray(value)) {
1055 value.forEach(function (arrayVal) {
1056 params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));
1057 });
1058 }
1059 else {
1060 params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
1061 }
1062 };
1063 for (var _i = 0, _a = Object.entries(querystringParams); _i < _a.length; _i++) {
1064 var _b = _a[_i], key = _b[0], value = _b[1];
1065 _loop_1(key, value);
1066 }
1067 return params.length ? '&' + params.join('&') : '';
1068}
1069/**
1070 * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object
1071 * (e.g. {arg: 'val', arg2: 'val2'})
1072 */
1073function querystringDecode(querystring) {
1074 var obj = {};
1075 var tokens = querystring.replace(/^\?/, '').split('&');
1076 tokens.forEach(function (token) {
1077 if (token) {
1078 var _a = token.split('='), key = _a[0], value = _a[1];
1079 obj[decodeURIComponent(key)] = decodeURIComponent(value);
1080 }
1081 });
1082 return obj;
1083}
1084/**
1085 * Extract the query string part of a URL, including the leading question mark (if present).
1086 */
1087function extractQuerystring(url) {
1088 var queryStart = url.indexOf('?');
1089 if (!queryStart) {
1090 return '';
1091 }
1092 var fragmentStart = url.indexOf('#', queryStart);
1093 return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);
1094}
1095
1096/**
1097 * @license
1098 * Copyright 2017 Google LLC
1099 *
1100 * Licensed under the Apache License, Version 2.0 (the "License");
1101 * you may not use this file except in compliance with the License.
1102 * You may obtain a copy of the License at
1103 *
1104 * http://www.apache.org/licenses/LICENSE-2.0
1105 *
1106 * Unless required by applicable law or agreed to in writing, software
1107 * distributed under the License is distributed on an "AS IS" BASIS,
1108 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1109 * See the License for the specific language governing permissions and
1110 * limitations under the License.
1111 */
1112/**
1113 * @fileoverview SHA-1 cryptographic hash.
1114 * Variable names follow the notation in FIPS PUB 180-3:
1115 * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.
1116 *
1117 * Usage:
1118 * var sha1 = new sha1();
1119 * sha1.update(bytes);
1120 * var hash = sha1.digest();
1121 *
1122 * Performance:
1123 * Chrome 23: ~400 Mbit/s
1124 * Firefox 16: ~250 Mbit/s
1125 *
1126 */
1127/**
1128 * SHA-1 cryptographic hash constructor.
1129 *
1130 * The properties declared here are discussed in the above algorithm document.
1131 * @constructor
1132 * @final
1133 * @struct
1134 */
1135var Sha1 = /** @class */ (function () {
1136 function Sha1() {
1137 /**
1138 * Holds the previous values of accumulated variables a-e in the compress_
1139 * function.
1140 * @private
1141 */
1142 this.chain_ = [];
1143 /**
1144 * A buffer holding the partially computed hash result.
1145 * @private
1146 */
1147 this.buf_ = [];
1148 /**
1149 * An array of 80 bytes, each a part of the message to be hashed. Referred to
1150 * as the message schedule in the docs.
1151 * @private
1152 */
1153 this.W_ = [];
1154 /**
1155 * Contains data needed to pad messages less than 64 bytes.
1156 * @private
1157 */
1158 this.pad_ = [];
1159 /**
1160 * @private {number}
1161 */
1162 this.inbuf_ = 0;
1163 /**
1164 * @private {number}
1165 */
1166 this.total_ = 0;
1167 this.blockSize = 512 / 8;
1168 this.pad_[0] = 128;
1169 for (var i = 1; i < this.blockSize; ++i) {
1170 this.pad_[i] = 0;
1171 }
1172 this.reset();
1173 }
1174 Sha1.prototype.reset = function () {
1175 this.chain_[0] = 0x67452301;
1176 this.chain_[1] = 0xefcdab89;
1177 this.chain_[2] = 0x98badcfe;
1178 this.chain_[3] = 0x10325476;
1179 this.chain_[4] = 0xc3d2e1f0;
1180 this.inbuf_ = 0;
1181 this.total_ = 0;
1182 };
1183 /**
1184 * Internal compress helper function.
1185 * @param buf Block to compress.
1186 * @param offset Offset of the block in the buffer.
1187 * @private
1188 */
1189 Sha1.prototype.compress_ = function (buf, offset) {
1190 if (!offset) {
1191 offset = 0;
1192 }
1193 var W = this.W_;
1194 // get 16 big endian words
1195 if (typeof buf === 'string') {
1196 for (var i = 0; i < 16; i++) {
1197 // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS
1198 // have a bug that turns the post-increment ++ operator into pre-increment
1199 // during JIT compilation. We have code that depends heavily on SHA-1 for
1200 // correctness and which is affected by this bug, so I've removed all uses
1201 // of post-increment ++ in which the result value is used. We can revert
1202 // this change once the Safari bug
1203 // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and
1204 // most clients have been updated.
1205 W[i] =
1206 (buf.charCodeAt(offset) << 24) |
1207 (buf.charCodeAt(offset + 1) << 16) |
1208 (buf.charCodeAt(offset + 2) << 8) |
1209 buf.charCodeAt(offset + 3);
1210 offset += 4;
1211 }
1212 }
1213 else {
1214 for (var i = 0; i < 16; i++) {
1215 W[i] =
1216 (buf[offset] << 24) |
1217 (buf[offset + 1] << 16) |
1218 (buf[offset + 2] << 8) |
1219 buf[offset + 3];
1220 offset += 4;
1221 }
1222 }
1223 // expand to 80 words
1224 for (var i = 16; i < 80; i++) {
1225 var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
1226 W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;
1227 }
1228 var a = this.chain_[0];
1229 var b = this.chain_[1];
1230 var c = this.chain_[2];
1231 var d = this.chain_[3];
1232 var e = this.chain_[4];
1233 var f, k;
1234 // TODO(user): Try to unroll this loop to speed up the computation.
1235 for (var i = 0; i < 80; i++) {
1236 if (i < 40) {
1237 if (i < 20) {
1238 f = d ^ (b & (c ^ d));
1239 k = 0x5a827999;
1240 }
1241 else {
1242 f = b ^ c ^ d;
1243 k = 0x6ed9eba1;
1244 }
1245 }
1246 else {
1247 if (i < 60) {
1248 f = (b & c) | (d & (b | c));
1249 k = 0x8f1bbcdc;
1250 }
1251 else {
1252 f = b ^ c ^ d;
1253 k = 0xca62c1d6;
1254 }
1255 }
1256 var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;
1257 e = d;
1258 d = c;
1259 c = ((b << 30) | (b >>> 2)) & 0xffffffff;
1260 b = a;
1261 a = t;
1262 }
1263 this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;
1264 this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;
1265 this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;
1266 this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;
1267 this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;
1268 };
1269 Sha1.prototype.update = function (bytes, length) {
1270 // TODO(johnlenz): tighten the function signature and remove this check
1271 if (bytes == null) {
1272 return;
1273 }
1274 if (length === undefined) {
1275 length = bytes.length;
1276 }
1277 var lengthMinusBlock = length - this.blockSize;
1278 var n = 0;
1279 // Using local instead of member variables gives ~5% speedup on Firefox 16.
1280 var buf = this.buf_;
1281 var inbuf = this.inbuf_;
1282 // The outer while loop should execute at most twice.
1283 while (n < length) {
1284 // When we have no data in the block to top up, we can directly process the
1285 // input buffer (assuming it contains sufficient data). This gives ~25%
1286 // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that
1287 // the data is provided in large chunks (or in multiples of 64 bytes).
1288 if (inbuf === 0) {
1289 while (n <= lengthMinusBlock) {
1290 this.compress_(bytes, n);
1291 n += this.blockSize;
1292 }
1293 }
1294 if (typeof bytes === 'string') {
1295 while (n < length) {
1296 buf[inbuf] = bytes.charCodeAt(n);
1297 ++inbuf;
1298 ++n;
1299 if (inbuf === this.blockSize) {
1300 this.compress_(buf);
1301 inbuf = 0;
1302 // Jump to the outer loop so we use the full-block optimization.
1303 break;
1304 }
1305 }
1306 }
1307 else {
1308 while (n < length) {
1309 buf[inbuf] = bytes[n];
1310 ++inbuf;
1311 ++n;
1312 if (inbuf === this.blockSize) {
1313 this.compress_(buf);
1314 inbuf = 0;
1315 // Jump to the outer loop so we use the full-block optimization.
1316 break;
1317 }
1318 }
1319 }
1320 }
1321 this.inbuf_ = inbuf;
1322 this.total_ += length;
1323 };
1324 /** @override */
1325 Sha1.prototype.digest = function () {
1326 var digest = [];
1327 var totalBits = this.total_ * 8;
1328 // Add pad 0x80 0x00*.
1329 if (this.inbuf_ < 56) {
1330 this.update(this.pad_, 56 - this.inbuf_);
1331 }
1332 else {
1333 this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
1334 }
1335 // Add # bits.
1336 for (var i = this.blockSize - 1; i >= 56; i--) {
1337 this.buf_[i] = totalBits & 255;
1338 totalBits /= 256; // Don't use bit-shifting here!
1339 }
1340 this.compress_(this.buf_);
1341 var n = 0;
1342 for (var i = 0; i < 5; i++) {
1343 for (var j = 24; j >= 0; j -= 8) {
1344 digest[n] = (this.chain_[i] >> j) & 255;
1345 ++n;
1346 }
1347 }
1348 return digest;
1349 };
1350 return Sha1;
1351}());
1352
1353/**
1354 * Helper to make a Subscribe function (just like Promise helps make a
1355 * Thenable).
1356 *
1357 * @param executor Function which can make calls to a single Observer
1358 * as a proxy.
1359 * @param onNoObservers Callback when count of Observers goes to zero.
1360 */
1361function createSubscribe(executor, onNoObservers) {
1362 var proxy = new ObserverProxy(executor, onNoObservers);
1363 return proxy.subscribe.bind(proxy);
1364}
1365/**
1366 * Implement fan-out for any number of Observers attached via a subscribe
1367 * function.
1368 */
1369var ObserverProxy = /** @class */ (function () {
1370 /**
1371 * @param executor Function which can make calls to a single Observer
1372 * as a proxy.
1373 * @param onNoObservers Callback when count of Observers goes to zero.
1374 */
1375 function ObserverProxy(executor, onNoObservers) {
1376 var _this = this;
1377 this.observers = [];
1378 this.unsubscribes = [];
1379 this.observerCount = 0;
1380 // Micro-task scheduling by calling task.then().
1381 this.task = Promise.resolve();
1382 this.finalized = false;
1383 this.onNoObservers = onNoObservers;
1384 // Call the executor asynchronously so subscribers that are called
1385 // synchronously after the creation of the subscribe function
1386 // can still receive the very first value generated in the executor.
1387 this.task
1388 .then(function () {
1389 executor(_this);
1390 })
1391 .catch(function (e) {
1392 _this.error(e);
1393 });
1394 }
1395 ObserverProxy.prototype.next = function (value) {
1396 this.forEachObserver(function (observer) {
1397 observer.next(value);
1398 });
1399 };
1400 ObserverProxy.prototype.error = function (error) {
1401 this.forEachObserver(function (observer) {
1402 observer.error(error);
1403 });
1404 this.close(error);
1405 };
1406 ObserverProxy.prototype.complete = function () {
1407 this.forEachObserver(function (observer) {
1408 observer.complete();
1409 });
1410 this.close();
1411 };
1412 /**
1413 * Subscribe function that can be used to add an Observer to the fan-out list.
1414 *
1415 * - We require that no event is sent to a subscriber sychronously to their
1416 * call to subscribe().
1417 */
1418 ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) {
1419 var _this = this;
1420 var observer;
1421 if (nextOrObserver === undefined &&
1422 error === undefined &&
1423 complete === undefined) {
1424 throw new Error('Missing Observer.');
1425 }
1426 // Assemble an Observer object when passed as callback functions.
1427 if (implementsAnyMethods(nextOrObserver, [
1428 'next',
1429 'error',
1430 'complete'
1431 ])) {
1432 observer = nextOrObserver;
1433 }
1434 else {
1435 observer = {
1436 next: nextOrObserver,
1437 error: error,
1438 complete: complete
1439 };
1440 }
1441 if (observer.next === undefined) {
1442 observer.next = noop;
1443 }
1444 if (observer.error === undefined) {
1445 observer.error = noop;
1446 }
1447 if (observer.complete === undefined) {
1448 observer.complete = noop;
1449 }
1450 var unsub = this.unsubscribeOne.bind(this, this.observers.length);
1451 // Attempt to subscribe to a terminated Observable - we
1452 // just respond to the Observer with the final error or complete
1453 // event.
1454 if (this.finalized) {
1455 // eslint-disable-next-line @typescript-eslint/no-floating-promises
1456 this.task.then(function () {
1457 try {
1458 if (_this.finalError) {
1459 observer.error(_this.finalError);
1460 }
1461 else {
1462 observer.complete();
1463 }
1464 }
1465 catch (e) {
1466 // nothing
1467 }
1468 return;
1469 });
1470 }
1471 this.observers.push(observer);
1472 return unsub;
1473 };
1474 // Unsubscribe is synchronous - we guarantee that no events are sent to
1475 // any unsubscribed Observer.
1476 ObserverProxy.prototype.unsubscribeOne = function (i) {
1477 if (this.observers === undefined || this.observers[i] === undefined) {
1478 return;
1479 }
1480 delete this.observers[i];
1481 this.observerCount -= 1;
1482 if (this.observerCount === 0 && this.onNoObservers !== undefined) {
1483 this.onNoObservers(this);
1484 }
1485 };
1486 ObserverProxy.prototype.forEachObserver = function (fn) {
1487 if (this.finalized) {
1488 // Already closed by previous event....just eat the additional values.
1489 return;
1490 }
1491 // Since sendOne calls asynchronously - there is no chance that
1492 // this.observers will become undefined.
1493 for (var i = 0; i < this.observers.length; i++) {
1494 this.sendOne(i, fn);
1495 }
1496 };
1497 // Call the Observer via one of it's callback function. We are careful to
1498 // confirm that the observe has not been unsubscribed since this asynchronous
1499 // function had been queued.
1500 ObserverProxy.prototype.sendOne = function (i, fn) {
1501 var _this = this;
1502 // Execute the callback asynchronously
1503 // eslint-disable-next-line @typescript-eslint/no-floating-promises
1504 this.task.then(function () {
1505 if (_this.observers !== undefined && _this.observers[i] !== undefined) {
1506 try {
1507 fn(_this.observers[i]);
1508 }
1509 catch (e) {
1510 // Ignore exceptions raised in Observers or missing methods of an
1511 // Observer.
1512 // Log error to console. b/31404806
1513 if (typeof console !== 'undefined' && console.error) {
1514 console.error(e);
1515 }
1516 }
1517 }
1518 });
1519 };
1520 ObserverProxy.prototype.close = function (err) {
1521 var _this = this;
1522 if (this.finalized) {
1523 return;
1524 }
1525 this.finalized = true;
1526 if (err !== undefined) {
1527 this.finalError = err;
1528 }
1529 // Proxy is no longer needed - garbage collect references
1530 // eslint-disable-next-line @typescript-eslint/no-floating-promises
1531 this.task.then(function () {
1532 _this.observers = undefined;
1533 _this.onNoObservers = undefined;
1534 });
1535 };
1536 return ObserverProxy;
1537}());
1538/** Turn synchronous function into one called asynchronously. */
1539// eslint-disable-next-line @typescript-eslint/ban-types
1540function async(fn, onError) {
1541 return function () {
1542 var args = [];
1543 for (var _i = 0; _i < arguments.length; _i++) {
1544 args[_i] = arguments[_i];
1545 }
1546 Promise.resolve(true)
1547 .then(function () {
1548 fn.apply(void 0, args);
1549 })
1550 .catch(function (error) {
1551 if (onError) {
1552 onError(error);
1553 }
1554 });
1555 };
1556}
1557/**
1558 * Return true if the object passed in implements any of the named methods.
1559 */
1560function implementsAnyMethods(obj, methods) {
1561 if (typeof obj !== 'object' || obj === null) {
1562 return false;
1563 }
1564 for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {
1565 var method = methods_1[_i];
1566 if (method in obj && typeof obj[method] === 'function') {
1567 return true;
1568 }
1569 }
1570 return false;
1571}
1572function noop() {
1573 // do nothing
1574}
1575
1576/**
1577 * @license
1578 * Copyright 2017 Google LLC
1579 *
1580 * Licensed under the Apache License, Version 2.0 (the "License");
1581 * you may not use this file except in compliance with the License.
1582 * You may obtain a copy of the License at
1583 *
1584 * http://www.apache.org/licenses/LICENSE-2.0
1585 *
1586 * Unless required by applicable law or agreed to in writing, software
1587 * distributed under the License is distributed on an "AS IS" BASIS,
1588 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1589 * See the License for the specific language governing permissions and
1590 * limitations under the License.
1591 */
1592/**
1593 * Check to make sure the appropriate number of arguments are provided for a public function.
1594 * Throws an error if it fails.
1595 *
1596 * @param fnName The function name
1597 * @param minCount The minimum number of arguments to allow for the function call
1598 * @param maxCount The maximum number of argument to allow for the function call
1599 * @param argCount The actual number of arguments provided.
1600 */
1601var validateArgCount = function (fnName, minCount, maxCount, argCount) {
1602 var argError;
1603 if (argCount < minCount) {
1604 argError = 'at least ' + minCount;
1605 }
1606 else if (argCount > maxCount) {
1607 argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;
1608 }
1609 if (argError) {
1610 var error = fnName +
1611 ' failed: Was called with ' +
1612 argCount +
1613 (argCount === 1 ? ' argument.' : ' arguments.') +
1614 ' Expects ' +
1615 argError +
1616 '.';
1617 throw new Error(error);
1618 }
1619};
1620/**
1621 * Generates a string to prefix an error message about failed argument validation
1622 *
1623 * @param fnName The function name
1624 * @param argName The name of the argument
1625 * @return The prefix to add to the error thrown for validation.
1626 */
1627function errorPrefix(fnName, argName) {
1628 return fnName + " failed: " + argName + " argument ";
1629}
1630/**
1631 * @param fnName
1632 * @param argumentNumber
1633 * @param namespace
1634 * @param optional
1635 */
1636function validateNamespace(fnName, namespace, optional) {
1637 if (optional && !namespace) {
1638 return;
1639 }
1640 if (typeof namespace !== 'string') {
1641 //TODO: I should do more validation here. We only allow certain chars in namespaces.
1642 throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');
1643 }
1644}
1645function validateCallback(fnName, argumentName,
1646// eslint-disable-next-line @typescript-eslint/ban-types
1647callback, optional) {
1648 if (optional && !callback) {
1649 return;
1650 }
1651 if (typeof callback !== 'function') {
1652 throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');
1653 }
1654}
1655function validateContextObject(fnName, argumentName, context, optional) {
1656 if (optional && !context) {
1657 return;
1658 }
1659 if (typeof context !== 'object' || context === null) {
1660 throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');
1661 }
1662}
1663
1664/**
1665 * @license
1666 * Copyright 2017 Google LLC
1667 *
1668 * Licensed under the Apache License, Version 2.0 (the "License");
1669 * you may not use this file except in compliance with the License.
1670 * You may obtain a copy of the License at
1671 *
1672 * http://www.apache.org/licenses/LICENSE-2.0
1673 *
1674 * Unless required by applicable law or agreed to in writing, software
1675 * distributed under the License is distributed on an "AS IS" BASIS,
1676 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1677 * See the License for the specific language governing permissions and
1678 * limitations under the License.
1679 */
1680// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they
1681// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs,
1682// so it's been modified.
1683// Note that not all Unicode characters appear as single characters in JavaScript strings.
1684// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters
1685// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first
1686// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate
1687// pair).
1688// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3
1689/**
1690 * @param {string} str
1691 * @return {Array}
1692 */
1693var stringToByteArray = function (str) {
1694 var out = [];
1695 var p = 0;
1696 for (var i = 0; i < str.length; i++) {
1697 var c = str.charCodeAt(i);
1698 // Is this the lead surrogate in a surrogate pair?
1699 if (c >= 0xd800 && c <= 0xdbff) {
1700 var high = c - 0xd800; // the high 10 bits.
1701 i++;
1702 assert(i < str.length, 'Surrogate pair missing trail surrogate.');
1703 var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.
1704 c = 0x10000 + (high << 10) + low;
1705 }
1706 if (c < 128) {
1707 out[p++] = c;
1708 }
1709 else if (c < 2048) {
1710 out[p++] = (c >> 6) | 192;
1711 out[p++] = (c & 63) | 128;
1712 }
1713 else if (c < 65536) {
1714 out[p++] = (c >> 12) | 224;
1715 out[p++] = ((c >> 6) & 63) | 128;
1716 out[p++] = (c & 63) | 128;
1717 }
1718 else {
1719 out[p++] = (c >> 18) | 240;
1720 out[p++] = ((c >> 12) & 63) | 128;
1721 out[p++] = ((c >> 6) & 63) | 128;
1722 out[p++] = (c & 63) | 128;
1723 }
1724 }
1725 return out;
1726};
1727/**
1728 * Calculate length without actually converting; useful for doing cheaper validation.
1729 * @param {string} str
1730 * @return {number}
1731 */
1732var stringLength = function (str) {
1733 var p = 0;
1734 for (var i = 0; i < str.length; i++) {
1735 var c = str.charCodeAt(i);
1736 if (c < 128) {
1737 p++;
1738 }
1739 else if (c < 2048) {
1740 p += 2;
1741 }
1742 else if (c >= 0xd800 && c <= 0xdbff) {
1743 // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.
1744 p += 4;
1745 i++; // skip trail surrogate.
1746 }
1747 else {
1748 p += 3;
1749 }
1750 }
1751 return p;
1752};
1753
1754/**
1755 * @license
1756 * Copyright 2022 Google LLC
1757 *
1758 * Licensed under the Apache License, Version 2.0 (the "License");
1759 * you may not use this file except in compliance with the License.
1760 * You may obtain a copy of the License at
1761 *
1762 * http://www.apache.org/licenses/LICENSE-2.0
1763 *
1764 * Unless required by applicable law or agreed to in writing, software
1765 * distributed under the License is distributed on an "AS IS" BASIS,
1766 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1767 * See the License for the specific language governing permissions and
1768 * limitations under the License.
1769 */
1770/**
1771 * Copied from https://stackoverflow.com/a/2117523
1772 * Generates a new uuid.
1773 * @public
1774 */
1775var uuidv4 = function () {
1776 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
1777 var r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;
1778 return v.toString(16);
1779 });
1780};
1781
1782/**
1783 * @license
1784 * Copyright 2019 Google LLC
1785 *
1786 * Licensed under the Apache License, Version 2.0 (the "License");
1787 * you may not use this file except in compliance with the License.
1788 * You may obtain a copy of the License at
1789 *
1790 * http://www.apache.org/licenses/LICENSE-2.0
1791 *
1792 * Unless required by applicable law or agreed to in writing, software
1793 * distributed under the License is distributed on an "AS IS" BASIS,
1794 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1795 * See the License for the specific language governing permissions and
1796 * limitations under the License.
1797 */
1798/**
1799 * The amount of milliseconds to exponentially increase.
1800 */
1801var DEFAULT_INTERVAL_MILLIS = 1000;
1802/**
1803 * The factor to backoff by.
1804 * Should be a number greater than 1.
1805 */
1806var DEFAULT_BACKOFF_FACTOR = 2;
1807/**
1808 * The maximum milliseconds to increase to.
1809 *
1810 * <p>Visible for testing
1811 */
1812var MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.
1813/**
1814 * The percentage of backoff time to randomize by.
1815 * See
1816 * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic
1817 * for context.
1818 *
1819 * <p>Visible for testing
1820 */
1821var RANDOM_FACTOR = 0.5;
1822/**
1823 * Based on the backoff method from
1824 * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.
1825 * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.
1826 */
1827function calculateBackoffMillis(backoffCount, intervalMillis, backoffFactor) {
1828 if (intervalMillis === void 0) { intervalMillis = DEFAULT_INTERVAL_MILLIS; }
1829 if (backoffFactor === void 0) { backoffFactor = DEFAULT_BACKOFF_FACTOR; }
1830 // Calculates an exponentially increasing value.
1831 // Deviation: calculates value from count and a constant interval, so we only need to save value
1832 // and count to restore state.
1833 var currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);
1834 // A random "fuzz" to avoid waves of retries.
1835 // Deviation: randomFactor is required.
1836 var randomWait = Math.round(
1837 // A fraction of the backoff value to add/subtract.
1838 // Deviation: changes multiplication order to improve readability.
1839 RANDOM_FACTOR *
1840 currBaseValue *
1841 // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
1842 // if we add or subtract.
1843 (Math.random() - 0.5) *
1844 2);
1845 // Limits backoff to max to avoid effectively permanent backoff.
1846 return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
1847}
1848
1849/**
1850 * @license
1851 * Copyright 2020 Google LLC
1852 *
1853 * Licensed under the Apache License, Version 2.0 (the "License");
1854 * you may not use this file except in compliance with the License.
1855 * You may obtain a copy of the License at
1856 *
1857 * http://www.apache.org/licenses/LICENSE-2.0
1858 *
1859 * Unless required by applicable law or agreed to in writing, software
1860 * distributed under the License is distributed on an "AS IS" BASIS,
1861 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1862 * See the License for the specific language governing permissions and
1863 * limitations under the License.
1864 */
1865/**
1866 * Provide English ordinal letters after a number
1867 */
1868function ordinal(i) {
1869 if (!Number.isFinite(i)) {
1870 return "" + i;
1871 }
1872 return i + indicator(i);
1873}
1874function indicator(i) {
1875 i = Math.abs(i);
1876 var cent = i % 100;
1877 if (cent >= 10 && cent <= 20) {
1878 return 'th';
1879 }
1880 var dec = i % 10;
1881 if (dec === 1) {
1882 return 'st';
1883 }
1884 if (dec === 2) {
1885 return 'nd';
1886 }
1887 if (dec === 3) {
1888 return 'rd';
1889 }
1890 return 'th';
1891}
1892
1893/**
1894 * @license
1895 * Copyright 2021 Google LLC
1896 *
1897 * Licensed under the Apache License, Version 2.0 (the "License");
1898 * you may not use this file except in compliance with the License.
1899 * You may obtain a copy of the License at
1900 *
1901 * http://www.apache.org/licenses/LICENSE-2.0
1902 *
1903 * Unless required by applicable law or agreed to in writing, software
1904 * distributed under the License is distributed on an "AS IS" BASIS,
1905 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1906 * See the License for the specific language governing permissions and
1907 * limitations under the License.
1908 */
1909function getModularInstance(service) {
1910 if (service && service._delegate) {
1911 return service._delegate;
1912 }
1913 else {
1914 return service;
1915 }
1916}
1917
1918export { CONSTANTS, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };
1919//# sourceMappingURL=index.esm5.js.map