UNPKG

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