GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2098 lines
71 KiB

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