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.

3746 lines
160 KiB

2 months ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var phone = require('./phone-ec5655af.js');
  4. var tslib = require('tslib');
  5. var util = require('@firebase/util');
  6. var app = require('@firebase/app');
  7. require('@firebase/component');
  8. require('@firebase/logger');
  9. /**
  10. * @license
  11. * Copyright 2019 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. // There are two different browser persistence types: local and session.
  26. // Both have the same implementation but use a different underlying storage
  27. // object.
  28. var BrowserPersistenceClass = /** @class */ (function () {
  29. function BrowserPersistenceClass(storageRetriever, type) {
  30. this.storageRetriever = storageRetriever;
  31. this.type = type;
  32. }
  33. BrowserPersistenceClass.prototype._isAvailable = function () {
  34. try {
  35. if (!this.storage) {
  36. return Promise.resolve(false);
  37. }
  38. this.storage.setItem(phone.STORAGE_AVAILABLE_KEY, '1');
  39. this.storage.removeItem(phone.STORAGE_AVAILABLE_KEY);
  40. return Promise.resolve(true);
  41. }
  42. catch (_a) {
  43. return Promise.resolve(false);
  44. }
  45. };
  46. BrowserPersistenceClass.prototype._set = function (key, value) {
  47. this.storage.setItem(key, JSON.stringify(value));
  48. return Promise.resolve();
  49. };
  50. BrowserPersistenceClass.prototype._get = function (key) {
  51. var json = this.storage.getItem(key);
  52. return Promise.resolve(json ? JSON.parse(json) : null);
  53. };
  54. BrowserPersistenceClass.prototype._remove = function (key) {
  55. this.storage.removeItem(key);
  56. return Promise.resolve();
  57. };
  58. Object.defineProperty(BrowserPersistenceClass.prototype, "storage", {
  59. get: function () {
  60. return this.storageRetriever();
  61. },
  62. enumerable: false,
  63. configurable: true
  64. });
  65. return BrowserPersistenceClass;
  66. }());
  67. /**
  68. * @license
  69. * Copyright 2020 Google LLC
  70. *
  71. * Licensed under the Apache License, Version 2.0 (the "License");
  72. * you may not use this file except in compliance with the License.
  73. * You may obtain a copy of the License at
  74. *
  75. * http://www.apache.org/licenses/LICENSE-2.0
  76. *
  77. * Unless required by applicable law or agreed to in writing, software
  78. * distributed under the License is distributed on an "AS IS" BASIS,
  79. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  80. * See the License for the specific language governing permissions and
  81. * limitations under the License.
  82. */
  83. function _iframeCannotSyncWebStorage() {
  84. var ua = util.getUA();
  85. return phone._isSafari(ua) || phone._isIOS(ua);
  86. }
  87. // The polling period in case events are not supported
  88. var _POLLING_INTERVAL_MS$1 = 1000;
  89. // The IE 10 localStorage cross tab synchronization delay in milliseconds
  90. var IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
  91. var BrowserLocalPersistence = /** @class */ (function (_super) {
  92. tslib.__extends(BrowserLocalPersistence, _super);
  93. function BrowserLocalPersistence() {
  94. var _this = _super.call(this, function () { return window.localStorage; }, "LOCAL" /* PersistenceType.LOCAL */) || this;
  95. _this.boundEventHandler = function (event, poll) { return _this.onStorageEvent(event, poll); };
  96. _this.listeners = {};
  97. _this.localCache = {};
  98. // setTimeout return value is platform specific
  99. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  100. _this.pollTimer = null;
  101. // Safari or iOS browser and embedded in an iframe.
  102. _this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && phone._isIframe();
  103. // Whether to use polling instead of depending on window events
  104. _this.fallbackToPolling = phone._isMobileBrowser();
  105. _this._shouldAllowMigration = true;
  106. return _this;
  107. }
  108. BrowserLocalPersistence.prototype.forAllChangedKeys = function (cb) {
  109. // Check all keys with listeners on them.
  110. for (var _i = 0, _a = Object.keys(this.listeners); _i < _a.length; _i++) {
  111. var key = _a[_i];
  112. // Get value from localStorage.
  113. var newValue = this.storage.getItem(key);
  114. var oldValue = this.localCache[key];
  115. // If local map value does not match, trigger listener with storage event.
  116. // Differentiate this simulated event from the real storage event.
  117. if (newValue !== oldValue) {
  118. cb(key, oldValue, newValue);
  119. }
  120. }
  121. };
  122. BrowserLocalPersistence.prototype.onStorageEvent = function (event, poll) {
  123. var _this = this;
  124. if (poll === void 0) { poll = false; }
  125. // Key would be null in some situations, like when localStorage is cleared
  126. if (!event.key) {
  127. this.forAllChangedKeys(function (key, _oldValue, newValue) {
  128. _this.notifyListeners(key, newValue);
  129. });
  130. return;
  131. }
  132. var key = event.key;
  133. // Check the mechanism how this event was detected.
  134. // The first event will dictate the mechanism to be used.
  135. if (poll) {
  136. // Environment detects storage changes via polling.
  137. // Remove storage event listener to prevent possible event duplication.
  138. this.detachListener();
  139. }
  140. else {
  141. // Environment detects storage changes via storage event listener.
  142. // Remove polling listener to prevent possible event duplication.
  143. this.stopPolling();
  144. }
  145. // Safari embedded iframe. Storage event will trigger with the delta
  146. // changes but no changes will be applied to the iframe localStorage.
  147. if (this.safariLocalStorageNotSynced) {
  148. // Get current iframe page value.
  149. var storedValue_1 = this.storage.getItem(key);
  150. // Value not synchronized, synchronize manually.
  151. if (event.newValue !== storedValue_1) {
  152. if (event.newValue !== null) {
  153. // Value changed from current value.
  154. this.storage.setItem(key, event.newValue);
  155. }
  156. else {
  157. // Current value deleted.
  158. this.storage.removeItem(key);
  159. }
  160. }
  161. else if (this.localCache[key] === event.newValue && !poll) {
  162. // Already detected and processed, do not trigger listeners again.
  163. return;
  164. }
  165. }
  166. var triggerListeners = function () {
  167. // Keep local map up to date in case storage event is triggered before
  168. // poll.
  169. var storedValue = _this.storage.getItem(key);
  170. if (!poll && _this.localCache[key] === storedValue) {
  171. // Real storage event which has already been detected, do nothing.
  172. // This seems to trigger in some IE browsers for some reason.
  173. return;
  174. }
  175. _this.notifyListeners(key, storedValue);
  176. };
  177. var storedValue = this.storage.getItem(key);
  178. if (phone._isIE10() &&
  179. storedValue !== event.newValue &&
  180. event.newValue !== event.oldValue) {
  181. // IE 10 has this weird bug where a storage event would trigger with the
  182. // correct key, oldValue and newValue but localStorage.getItem(key) does
  183. // not yield the updated value until a few milliseconds. This ensures
  184. // this recovers from that situation.
  185. setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
  186. }
  187. else {
  188. triggerListeners();
  189. }
  190. };
  191. BrowserLocalPersistence.prototype.notifyListeners = function (key, value) {
  192. this.localCache[key] = value;
  193. var listeners = this.listeners[key];
  194. if (listeners) {
  195. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  196. var listener = _a[_i];
  197. listener(value ? JSON.parse(value) : value);
  198. }
  199. }
  200. };
  201. BrowserLocalPersistence.prototype.startPolling = function () {
  202. var _this = this;
  203. this.stopPolling();
  204. this.pollTimer = setInterval(function () {
  205. _this.forAllChangedKeys(function (key, oldValue, newValue) {
  206. _this.onStorageEvent(new StorageEvent('storage', {
  207. key: key,
  208. oldValue: oldValue,
  209. newValue: newValue
  210. }),
  211. /* poll */ true);
  212. });
  213. }, _POLLING_INTERVAL_MS$1);
  214. };
  215. BrowserLocalPersistence.prototype.stopPolling = function () {
  216. if (this.pollTimer) {
  217. clearInterval(this.pollTimer);
  218. this.pollTimer = null;
  219. }
  220. };
  221. BrowserLocalPersistence.prototype.attachListener = function () {
  222. window.addEventListener('storage', this.boundEventHandler);
  223. };
  224. BrowserLocalPersistence.prototype.detachListener = function () {
  225. window.removeEventListener('storage', this.boundEventHandler);
  226. };
  227. BrowserLocalPersistence.prototype._addListener = function (key, listener) {
  228. if (Object.keys(this.listeners).length === 0) {
  229. // Whether browser can detect storage event when it had already been pushed to the background.
  230. // This may happen in some mobile browsers. A localStorage change in the foreground window
  231. // will not be detected in the background window via the storage event.
  232. // This was detected in iOS 7.x mobile browsers
  233. if (this.fallbackToPolling) {
  234. this.startPolling();
  235. }
  236. else {
  237. this.attachListener();
  238. }
  239. }
  240. if (!this.listeners[key]) {
  241. this.listeners[key] = new Set();
  242. // Populate the cache to avoid spuriously triggering on first poll.
  243. this.localCache[key] = this.storage.getItem(key);
  244. }
  245. this.listeners[key].add(listener);
  246. };
  247. BrowserLocalPersistence.prototype._removeListener = function (key, listener) {
  248. if (this.listeners[key]) {
  249. this.listeners[key].delete(listener);
  250. if (this.listeners[key].size === 0) {
  251. delete this.listeners[key];
  252. }
  253. }
  254. if (Object.keys(this.listeners).length === 0) {
  255. this.detachListener();
  256. this.stopPolling();
  257. }
  258. };
  259. // Update local cache on base operations:
  260. BrowserLocalPersistence.prototype._set = function (key, value) {
  261. return tslib.__awaiter(this, void 0, void 0, function () {
  262. return tslib.__generator(this, function (_a) {
  263. switch (_a.label) {
  264. case 0: return [4 /*yield*/, _super.prototype._set.call(this, key, value)];
  265. case 1:
  266. _a.sent();
  267. this.localCache[key] = JSON.stringify(value);
  268. return [2 /*return*/];
  269. }
  270. });
  271. });
  272. };
  273. BrowserLocalPersistence.prototype._get = function (key) {
  274. return tslib.__awaiter(this, void 0, void 0, function () {
  275. var value;
  276. return tslib.__generator(this, function (_a) {
  277. switch (_a.label) {
  278. case 0: return [4 /*yield*/, _super.prototype._get.call(this, key)];
  279. case 1:
  280. value = _a.sent();
  281. this.localCache[key] = JSON.stringify(value);
  282. return [2 /*return*/, value];
  283. }
  284. });
  285. });
  286. };
  287. BrowserLocalPersistence.prototype._remove = function (key) {
  288. return tslib.__awaiter(this, void 0, void 0, function () {
  289. return tslib.__generator(this, function (_a) {
  290. switch (_a.label) {
  291. case 0: return [4 /*yield*/, _super.prototype._remove.call(this, key)];
  292. case 1:
  293. _a.sent();
  294. delete this.localCache[key];
  295. return [2 /*return*/];
  296. }
  297. });
  298. });
  299. };
  300. BrowserLocalPersistence.type = 'LOCAL';
  301. return BrowserLocalPersistence;
  302. }(BrowserPersistenceClass));
  303. /**
  304. * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
  305. * for the underlying storage.
  306. *
  307. * @public
  308. */
  309. var browserLocalPersistence = BrowserLocalPersistence;
  310. /**
  311. * @license
  312. * Copyright 2020 Google LLC
  313. *
  314. * Licensed under the Apache License, Version 2.0 (the "License");
  315. * you may not use this file except in compliance with the License.
  316. * You may obtain a copy of the License at
  317. *
  318. * http://www.apache.org/licenses/LICENSE-2.0
  319. *
  320. * Unless required by applicable law or agreed to in writing, software
  321. * distributed under the License is distributed on an "AS IS" BASIS,
  322. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  323. * See the License for the specific language governing permissions and
  324. * limitations under the License.
  325. */
  326. var BrowserSessionPersistence = /** @class */ (function (_super) {
  327. tslib.__extends(BrowserSessionPersistence, _super);
  328. function BrowserSessionPersistence() {
  329. return _super.call(this, function () { return window.sessionStorage; }, "SESSION" /* PersistenceType.SESSION */) || this;
  330. }
  331. BrowserSessionPersistence.prototype._addListener = function (_key, _listener) {
  332. // Listeners are not supported for session storage since it cannot be shared across windows
  333. return;
  334. };
  335. BrowserSessionPersistence.prototype._removeListener = function (_key, _listener) {
  336. // Listeners are not supported for session storage since it cannot be shared across windows
  337. return;
  338. };
  339. BrowserSessionPersistence.type = 'SESSION';
  340. return BrowserSessionPersistence;
  341. }(BrowserPersistenceClass));
  342. /**
  343. * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
  344. * for the underlying storage.
  345. *
  346. * @public
  347. */
  348. var browserSessionPersistence = BrowserSessionPersistence;
  349. /**
  350. * @license
  351. * Copyright 2019 Google LLC
  352. *
  353. * Licensed under the Apache License, Version 2.0 (the "License");
  354. * you may not use this file except in compliance with the License.
  355. * You may obtain a copy of the License at
  356. *
  357. * http://www.apache.org/licenses/LICENSE-2.0
  358. *
  359. * Unless required by applicable law or agreed to in writing, software
  360. * distributed under the License is distributed on an "AS IS" BASIS,
  361. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  362. * See the License for the specific language governing permissions and
  363. * limitations under the License.
  364. */
  365. /**
  366. * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
  367. *
  368. * @param promises - Array of promises to wait on.
  369. */
  370. function _allSettled(promises) {
  371. var _this = this;
  372. return Promise.all(promises.map(function (promise) { return tslib.__awaiter(_this, void 0, void 0, function () {
  373. var value, reason_1;
  374. return tslib.__generator(this, function (_a) {
  375. switch (_a.label) {
  376. case 0:
  377. _a.trys.push([0, 2, , 3]);
  378. return [4 /*yield*/, promise];
  379. case 1:
  380. value = _a.sent();
  381. return [2 /*return*/, {
  382. fulfilled: true,
  383. value: value
  384. }];
  385. case 2:
  386. reason_1 = _a.sent();
  387. return [2 /*return*/, {
  388. fulfilled: false,
  389. reason: reason_1
  390. }];
  391. case 3: return [2 /*return*/];
  392. }
  393. });
  394. }); }));
  395. }
  396. /**
  397. * @license
  398. * Copyright 2019 Google LLC
  399. *
  400. * Licensed under the Apache License, Version 2.0 (the "License");
  401. * you may not use this file except in compliance with the License.
  402. * You may obtain a copy of the License at
  403. *
  404. * http://www.apache.org/licenses/LICENSE-2.0
  405. *
  406. * Unless required by applicable law or agreed to in writing, software
  407. * distributed under the License is distributed on an "AS IS" BASIS,
  408. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  409. * See the License for the specific language governing permissions and
  410. * limitations under the License.
  411. */
  412. /**
  413. * Interface class for receiving messages.
  414. *
  415. */
  416. var Receiver = /** @class */ (function () {
  417. function Receiver(eventTarget) {
  418. this.eventTarget = eventTarget;
  419. this.handlersMap = {};
  420. this.boundEventHandler = this.handleEvent.bind(this);
  421. }
  422. /**
  423. * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
  424. *
  425. * @param eventTarget - An event target (such as window or self) through which the underlying
  426. * messages will be received.
  427. */
  428. Receiver._getInstance = function (eventTarget) {
  429. // The results are stored in an array since objects can't be keys for other
  430. // objects. In addition, setting a unique property on an event target as a
  431. // hash map key may not be allowed due to CORS restrictions.
  432. var existingInstance = this.receivers.find(function (receiver) {
  433. return receiver.isListeningto(eventTarget);
  434. });
  435. if (existingInstance) {
  436. return existingInstance;
  437. }
  438. var newInstance = new Receiver(eventTarget);
  439. this.receivers.push(newInstance);
  440. return newInstance;
  441. };
  442. Receiver.prototype.isListeningto = function (eventTarget) {
  443. return this.eventTarget === eventTarget;
  444. };
  445. /**
  446. * Fans out a MessageEvent to the appropriate listeners.
  447. *
  448. * @remarks
  449. * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
  450. * finished processing.
  451. *
  452. * @param event - The MessageEvent.
  453. *
  454. */
  455. Receiver.prototype.handleEvent = function (event) {
  456. return tslib.__awaiter(this, void 0, void 0, function () {
  457. var messageEvent, _a, eventId, eventType, data, handlers, promises, response;
  458. var _this = this;
  459. return tslib.__generator(this, function (_b) {
  460. switch (_b.label) {
  461. case 0:
  462. messageEvent = event;
  463. _a = messageEvent.data, eventId = _a.eventId, eventType = _a.eventType, data = _a.data;
  464. handlers = this.handlersMap[eventType];
  465. if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
  466. return [2 /*return*/];
  467. }
  468. messageEvent.ports[0].postMessage({
  469. status: "ack" /* _Status.ACK */,
  470. eventId: eventId,
  471. eventType: eventType
  472. });
  473. promises = Array.from(handlers).map(function (handler) { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  474. return [2 /*return*/, handler(messageEvent.origin, data)];
  475. }); }); });
  476. return [4 /*yield*/, _allSettled(promises)];
  477. case 1:
  478. response = _b.sent();
  479. messageEvent.ports[0].postMessage({
  480. status: "done" /* _Status.DONE */,
  481. eventId: eventId,
  482. eventType: eventType,
  483. response: response
  484. });
  485. return [2 /*return*/];
  486. }
  487. });
  488. });
  489. };
  490. /**
  491. * Subscribe an event handler for a particular event.
  492. *
  493. * @param eventType - Event name to subscribe to.
  494. * @param eventHandler - The event handler which should receive the events.
  495. *
  496. */
  497. Receiver.prototype._subscribe = function (eventType, eventHandler) {
  498. if (Object.keys(this.handlersMap).length === 0) {
  499. this.eventTarget.addEventListener('message', this.boundEventHandler);
  500. }
  501. if (!this.handlersMap[eventType]) {
  502. this.handlersMap[eventType] = new Set();
  503. }
  504. this.handlersMap[eventType].add(eventHandler);
  505. };
  506. /**
  507. * Unsubscribe an event handler from a particular event.
  508. *
  509. * @param eventType - Event name to unsubscribe from.
  510. * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
  511. *
  512. */
  513. Receiver.prototype._unsubscribe = function (eventType, eventHandler) {
  514. if (this.handlersMap[eventType] && eventHandler) {
  515. this.handlersMap[eventType].delete(eventHandler);
  516. }
  517. if (!eventHandler || this.handlersMap[eventType].size === 0) {
  518. delete this.handlersMap[eventType];
  519. }
  520. if (Object.keys(this.handlersMap).length === 0) {
  521. this.eventTarget.removeEventListener('message', this.boundEventHandler);
  522. }
  523. };
  524. Receiver.receivers = [];
  525. return Receiver;
  526. }());
  527. /**
  528. * @license
  529. * Copyright 2020 Google LLC
  530. *
  531. * Licensed under the Apache License, Version 2.0 (the "License");
  532. * you may not use this file except in compliance with the License.
  533. * You may obtain a copy of the License at
  534. *
  535. * http://www.apache.org/licenses/LICENSE-2.0
  536. *
  537. * Unless required by applicable law or agreed to in writing, software
  538. * distributed under the License is distributed on an "AS IS" BASIS,
  539. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  540. * See the License for the specific language governing permissions and
  541. * limitations under the License.
  542. */
  543. function _generateEventId(prefix, digits) {
  544. if (prefix === void 0) { prefix = ''; }
  545. if (digits === void 0) { digits = 10; }
  546. var random = '';
  547. for (var i = 0; i < digits; i++) {
  548. random += Math.floor(Math.random() * 10);
  549. }
  550. return prefix + random;
  551. }
  552. /**
  553. * @license
  554. * Copyright 2019 Google LLC
  555. *
  556. * Licensed under the Apache License, Version 2.0 (the "License");
  557. * you may not use this file except in compliance with the License.
  558. * You may obtain a copy of the License at
  559. *
  560. * http://www.apache.org/licenses/LICENSE-2.0
  561. *
  562. * Unless required by applicable law or agreed to in writing, software
  563. * distributed under the License is distributed on an "AS IS" BASIS,
  564. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  565. * See the License for the specific language governing permissions and
  566. * limitations under the License.
  567. */
  568. /**
  569. * Interface for sending messages and waiting for a completion response.
  570. *
  571. */
  572. var Sender = /** @class */ (function () {
  573. function Sender(target) {
  574. this.target = target;
  575. this.handlers = new Set();
  576. }
  577. /**
  578. * Unsubscribe the handler and remove it from our tracking Set.
  579. *
  580. * @param handler - The handler to unsubscribe.
  581. */
  582. Sender.prototype.removeMessageHandler = function (handler) {
  583. if (handler.messageChannel) {
  584. handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
  585. handler.messageChannel.port1.close();
  586. }
  587. this.handlers.delete(handler);
  588. };
  589. /**
  590. * Send a message to the Receiver located at {@link target}.
  591. *
  592. * @remarks
  593. * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
  594. * receiver has had a chance to fully process the event.
  595. *
  596. * @param eventType - Type of event to send.
  597. * @param data - The payload of the event.
  598. * @param timeout - Timeout for waiting on an ACK from the receiver.
  599. *
  600. * @returns An array of settled promises from all the handlers that were listening on the receiver.
  601. */
  602. Sender.prototype._send = function (eventType, data, timeout) {
  603. if (timeout === void 0) { timeout = 50 /* _TimeoutDuration.ACK */; }
  604. return tslib.__awaiter(this, void 0, void 0, function () {
  605. var messageChannel, completionTimer, handler;
  606. var _this = this;
  607. return tslib.__generator(this, function (_a) {
  608. messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
  609. if (!messageChannel) {
  610. throw new Error("connection_unavailable" /* _MessageError.CONNECTION_UNAVAILABLE */);
  611. }
  612. return [2 /*return*/, new Promise(function (resolve, reject) {
  613. var eventId = _generateEventId('', 20);
  614. messageChannel.port1.start();
  615. var ackTimer = setTimeout(function () {
  616. reject(new Error("unsupported_event" /* _MessageError.UNSUPPORTED_EVENT */));
  617. }, timeout);
  618. handler = {
  619. messageChannel: messageChannel,
  620. onMessage: function (event) {
  621. var messageEvent = event;
  622. if (messageEvent.data.eventId !== eventId) {
  623. return;
  624. }
  625. switch (messageEvent.data.status) {
  626. case "ack" /* _Status.ACK */:
  627. // The receiver should ACK first.
  628. clearTimeout(ackTimer);
  629. completionTimer = setTimeout(function () {
  630. reject(new Error("timeout" /* _MessageError.TIMEOUT */));
  631. }, 3000 /* _TimeoutDuration.COMPLETION */);
  632. break;
  633. case "done" /* _Status.DONE */:
  634. // Once the receiver's handlers are finished we will get the results.
  635. clearTimeout(completionTimer);
  636. resolve(messageEvent.data.response);
  637. break;
  638. default:
  639. clearTimeout(ackTimer);
  640. clearTimeout(completionTimer);
  641. reject(new Error("invalid_response" /* _MessageError.INVALID_RESPONSE */));
  642. break;
  643. }
  644. }
  645. };
  646. _this.handlers.add(handler);
  647. messageChannel.port1.addEventListener('message', handler.onMessage);
  648. _this.target.postMessage({
  649. eventType: eventType,
  650. eventId: eventId,
  651. data: data
  652. }, [messageChannel.port2]);
  653. }).finally(function () {
  654. if (handler) {
  655. _this.removeMessageHandler(handler);
  656. }
  657. })];
  658. });
  659. });
  660. };
  661. return Sender;
  662. }());
  663. /**
  664. * @license
  665. * Copyright 2019 Google LLC
  666. *
  667. * Licensed under the Apache License, Version 2.0 (the "License");
  668. * you may not use this file except in compliance with the License.
  669. * You may obtain a copy of the License at
  670. *
  671. * http://www.apache.org/licenses/LICENSE-2.0
  672. *
  673. * Unless required by applicable law or agreed to in writing, software
  674. * distributed under the License is distributed on an "AS IS" BASIS,
  675. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  676. * See the License for the specific language governing permissions and
  677. * limitations under the License.
  678. */
  679. var DB_NAME = 'firebaseLocalStorageDb';
  680. var DB_VERSION = 1;
  681. var DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
  682. var DB_DATA_KEYPATH = 'fbase_key';
  683. /**
  684. * Promise wrapper for IDBRequest
  685. *
  686. * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
  687. *
  688. */
  689. var DBPromise = /** @class */ (function () {
  690. function DBPromise(request) {
  691. this.request = request;
  692. }
  693. DBPromise.prototype.toPromise = function () {
  694. var _this = this;
  695. return new Promise(function (resolve, reject) {
  696. _this.request.addEventListener('success', function () {
  697. resolve(_this.request.result);
  698. });
  699. _this.request.addEventListener('error', function () {
  700. reject(_this.request.error);
  701. });
  702. });
  703. };
  704. return DBPromise;
  705. }());
  706. function getObjectStore(db, isReadWrite) {
  707. return db
  708. .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
  709. .objectStore(DB_OBJECTSTORE_NAME);
  710. }
  711. function _deleteDatabase() {
  712. var request = indexedDB.deleteDatabase(DB_NAME);
  713. return new DBPromise(request).toPromise();
  714. }
  715. function _openDatabase() {
  716. var _this = this;
  717. var request = indexedDB.open(DB_NAME, DB_VERSION);
  718. return new Promise(function (resolve, reject) {
  719. request.addEventListener('error', function () {
  720. reject(request.error);
  721. });
  722. request.addEventListener('upgradeneeded', function () {
  723. var db = request.result;
  724. try {
  725. db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
  726. }
  727. catch (e) {
  728. reject(e);
  729. }
  730. });
  731. request.addEventListener('success', function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  732. var db, _a;
  733. return tslib.__generator(this, function (_b) {
  734. switch (_b.label) {
  735. case 0:
  736. db = request.result;
  737. if (!!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) return [3 /*break*/, 3];
  738. // Need to close the database or else you get a `blocked` event
  739. db.close();
  740. return [4 /*yield*/, _deleteDatabase()];
  741. case 1:
  742. _b.sent();
  743. _a = resolve;
  744. return [4 /*yield*/, _openDatabase()];
  745. case 2:
  746. _a.apply(void 0, [_b.sent()]);
  747. return [3 /*break*/, 4];
  748. case 3:
  749. resolve(db);
  750. _b.label = 4;
  751. case 4: return [2 /*return*/];
  752. }
  753. });
  754. }); });
  755. });
  756. }
  757. function _putObject(db, key, value) {
  758. return tslib.__awaiter(this, void 0, void 0, function () {
  759. var request;
  760. var _a;
  761. return tslib.__generator(this, function (_b) {
  762. request = getObjectStore(db, true).put((_a = {},
  763. _a[DB_DATA_KEYPATH] = key,
  764. _a.value = value,
  765. _a));
  766. return [2 /*return*/, new DBPromise(request).toPromise()];
  767. });
  768. });
  769. }
  770. function getObject(db, key) {
  771. return tslib.__awaiter(this, void 0, void 0, function () {
  772. var request, data;
  773. return tslib.__generator(this, function (_a) {
  774. switch (_a.label) {
  775. case 0:
  776. request = getObjectStore(db, false).get(key);
  777. return [4 /*yield*/, new DBPromise(request).toPromise()];
  778. case 1:
  779. data = _a.sent();
  780. return [2 /*return*/, data === undefined ? null : data.value];
  781. }
  782. });
  783. });
  784. }
  785. function _deleteObject(db, key) {
  786. var request = getObjectStore(db, true).delete(key);
  787. return new DBPromise(request).toPromise();
  788. }
  789. var _POLLING_INTERVAL_MS = 800;
  790. var _TRANSACTION_RETRY_COUNT = 3;
  791. var IndexedDBLocalPersistence = /** @class */ (function () {
  792. function IndexedDBLocalPersistence() {
  793. this.type = "LOCAL" /* PersistenceType.LOCAL */;
  794. this._shouldAllowMigration = true;
  795. this.listeners = {};
  796. this.localCache = {};
  797. // setTimeout return value is platform specific
  798. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  799. this.pollTimer = null;
  800. this.pendingWrites = 0;
  801. this.receiver = null;
  802. this.sender = null;
  803. this.serviceWorkerReceiverAvailable = false;
  804. this.activeServiceWorker = null;
  805. // Fire & forget the service worker registration as it may never resolve
  806. this._workerInitializationPromise =
  807. this.initializeServiceWorkerMessaging().then(function () { }, function () { });
  808. }
  809. IndexedDBLocalPersistence.prototype._openDb = function () {
  810. return tslib.__awaiter(this, void 0, void 0, function () {
  811. var _a;
  812. return tslib.__generator(this, function (_b) {
  813. switch (_b.label) {
  814. case 0:
  815. if (this.db) {
  816. return [2 /*return*/, this.db];
  817. }
  818. _a = this;
  819. return [4 /*yield*/, _openDatabase()];
  820. case 1:
  821. _a.db = _b.sent();
  822. return [2 /*return*/, this.db];
  823. }
  824. });
  825. });
  826. };
  827. IndexedDBLocalPersistence.prototype._withRetries = function (op) {
  828. return tslib.__awaiter(this, void 0, void 0, function () {
  829. var numAttempts, db, e_1;
  830. return tslib.__generator(this, function (_a) {
  831. switch (_a.label) {
  832. case 0:
  833. numAttempts = 0;
  834. _a.label = 1;
  835. case 1:
  836. _a.label = 2;
  837. case 2:
  838. _a.trys.push([2, 5, , 6]);
  839. return [4 /*yield*/, this._openDb()];
  840. case 3:
  841. db = _a.sent();
  842. return [4 /*yield*/, op(db)];
  843. case 4: return [2 /*return*/, _a.sent()];
  844. case 5:
  845. e_1 = _a.sent();
  846. if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
  847. throw e_1;
  848. }
  849. if (this.db) {
  850. this.db.close();
  851. this.db = undefined;
  852. }
  853. return [3 /*break*/, 6];
  854. case 6: return [3 /*break*/, 1];
  855. case 7: return [2 /*return*/];
  856. }
  857. });
  858. });
  859. };
  860. /**
  861. * IndexedDB events do not propagate from the main window to the worker context. We rely on a
  862. * postMessage interface to send these events to the worker ourselves.
  863. */
  864. IndexedDBLocalPersistence.prototype.initializeServiceWorkerMessaging = function () {
  865. return tslib.__awaiter(this, void 0, void 0, function () {
  866. return tslib.__generator(this, function (_a) {
  867. return [2 /*return*/, phone._isWorker() ? this.initializeReceiver() : this.initializeSender()];
  868. });
  869. });
  870. };
  871. /**
  872. * As the worker we should listen to events from the main window.
  873. */
  874. IndexedDBLocalPersistence.prototype.initializeReceiver = function () {
  875. return tslib.__awaiter(this, void 0, void 0, function () {
  876. var _this = this;
  877. return tslib.__generator(this, function (_a) {
  878. this.receiver = Receiver._getInstance(phone._getWorkerGlobalScope());
  879. // Refresh from persistence if we receive a KeyChanged message.
  880. this.receiver._subscribe("keyChanged" /* _EventType.KEY_CHANGED */, function (_origin, data) { return tslib.__awaiter(_this, void 0, void 0, function () {
  881. var keys;
  882. return tslib.__generator(this, function (_a) {
  883. switch (_a.label) {
  884. case 0: return [4 /*yield*/, this._poll()];
  885. case 1:
  886. keys = _a.sent();
  887. return [2 /*return*/, {
  888. keyProcessed: keys.includes(data.key)
  889. }];
  890. }
  891. });
  892. }); });
  893. // Let the sender know that we are listening so they give us more timeout.
  894. this.receiver._subscribe("ping" /* _EventType.PING */, function (_origin, _data) { return tslib.__awaiter(_this, void 0, void 0, function () {
  895. return tslib.__generator(this, function (_a) {
  896. return [2 /*return*/, ["keyChanged" /* _EventType.KEY_CHANGED */]];
  897. });
  898. }); });
  899. return [2 /*return*/];
  900. });
  901. });
  902. };
  903. /**
  904. * As the main window, we should let the worker know when keys change (set and remove).
  905. *
  906. * @remarks
  907. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
  908. * may not resolve.
  909. */
  910. IndexedDBLocalPersistence.prototype.initializeSender = function () {
  911. var _a, _b;
  912. return tslib.__awaiter(this, void 0, void 0, function () {
  913. var _c, results;
  914. return tslib.__generator(this, function (_d) {
  915. switch (_d.label) {
  916. case 0:
  917. // Check to see if there's an active service worker.
  918. _c = this;
  919. return [4 /*yield*/, phone._getActiveServiceWorker()];
  920. case 1:
  921. // Check to see if there's an active service worker.
  922. _c.activeServiceWorker = _d.sent();
  923. if (!this.activeServiceWorker) {
  924. return [2 /*return*/];
  925. }
  926. this.sender = new Sender(this.activeServiceWorker);
  927. return [4 /*yield*/, this.sender._send("ping" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */)];
  928. case 2:
  929. results = _d.sent();
  930. if (!results) {
  931. return [2 /*return*/];
  932. }
  933. if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
  934. ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* _EventType.KEY_CHANGED */))) {
  935. this.serviceWorkerReceiverAvailable = true;
  936. }
  937. return [2 /*return*/];
  938. }
  939. });
  940. });
  941. };
  942. /**
  943. * Let the worker know about a changed key, the exact key doesn't technically matter since the
  944. * worker will just trigger a full sync anyway.
  945. *
  946. * @remarks
  947. * For now, we only support one service worker per page.
  948. *
  949. * @param key - Storage key which changed.
  950. */
  951. IndexedDBLocalPersistence.prototype.notifyServiceWorker = function (key) {
  952. return tslib.__awaiter(this, void 0, void 0, function () {
  953. return tslib.__generator(this, function (_b) {
  954. switch (_b.label) {
  955. case 0:
  956. if (!this.sender ||
  957. !this.activeServiceWorker ||
  958. phone._getServiceWorkerController() !== this.activeServiceWorker) {
  959. return [2 /*return*/];
  960. }
  961. _b.label = 1;
  962. case 1:
  963. _b.trys.push([1, 3, , 4]);
  964. return [4 /*yield*/, this.sender._send("keyChanged" /* _EventType.KEY_CHANGED */, { key: key },
  965. // Use long timeout if receiver has previously responded to a ping from us.
  966. this.serviceWorkerReceiverAvailable
  967. ? 800 /* _TimeoutDuration.LONG_ACK */
  968. : 50 /* _TimeoutDuration.ACK */)];
  969. case 2:
  970. _b.sent();
  971. return [3 /*break*/, 4];
  972. case 3:
  973. _b.sent();
  974. return [3 /*break*/, 4];
  975. case 4: return [2 /*return*/];
  976. }
  977. });
  978. });
  979. };
  980. IndexedDBLocalPersistence.prototype._isAvailable = function () {
  981. return tslib.__awaiter(this, void 0, void 0, function () {
  982. var db;
  983. return tslib.__generator(this, function (_b) {
  984. switch (_b.label) {
  985. case 0:
  986. _b.trys.push([0, 4, , 5]);
  987. if (!indexedDB) {
  988. return [2 /*return*/, false];
  989. }
  990. return [4 /*yield*/, _openDatabase()];
  991. case 1:
  992. db = _b.sent();
  993. return [4 /*yield*/, _putObject(db, phone.STORAGE_AVAILABLE_KEY, '1')];
  994. case 2:
  995. _b.sent();
  996. return [4 /*yield*/, _deleteObject(db, phone.STORAGE_AVAILABLE_KEY)];
  997. case 3:
  998. _b.sent();
  999. return [2 /*return*/, true];
  1000. case 4:
  1001. _b.sent();
  1002. return [3 /*break*/, 5];
  1003. case 5: return [2 /*return*/, false];
  1004. }
  1005. });
  1006. });
  1007. };
  1008. IndexedDBLocalPersistence.prototype._withPendingWrite = function (write) {
  1009. return tslib.__awaiter(this, void 0, void 0, function () {
  1010. return tslib.__generator(this, function (_a) {
  1011. switch (_a.label) {
  1012. case 0:
  1013. this.pendingWrites++;
  1014. _a.label = 1;
  1015. case 1:
  1016. _a.trys.push([1, , 3, 4]);
  1017. return [4 /*yield*/, write()];
  1018. case 2:
  1019. _a.sent();
  1020. return [3 /*break*/, 4];
  1021. case 3:
  1022. this.pendingWrites--;
  1023. return [7 /*endfinally*/];
  1024. case 4: return [2 /*return*/];
  1025. }
  1026. });
  1027. });
  1028. };
  1029. IndexedDBLocalPersistence.prototype._set = function (key, value) {
  1030. return tslib.__awaiter(this, void 0, void 0, function () {
  1031. var _this = this;
  1032. return tslib.__generator(this, function (_a) {
  1033. return [2 /*return*/, this._withPendingWrite(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1034. return tslib.__generator(this, function (_a) {
  1035. switch (_a.label) {
  1036. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _putObject(db, key, value); })];
  1037. case 1:
  1038. _a.sent();
  1039. this.localCache[key] = value;
  1040. return [2 /*return*/, this.notifyServiceWorker(key)];
  1041. }
  1042. });
  1043. }); })];
  1044. });
  1045. });
  1046. };
  1047. IndexedDBLocalPersistence.prototype._get = function (key) {
  1048. return tslib.__awaiter(this, void 0, void 0, function () {
  1049. var obj;
  1050. return tslib.__generator(this, function (_a) {
  1051. switch (_a.label) {
  1052. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  1053. return getObject(db, key);
  1054. })];
  1055. case 1:
  1056. obj = (_a.sent());
  1057. this.localCache[key] = obj;
  1058. return [2 /*return*/, obj];
  1059. }
  1060. });
  1061. });
  1062. };
  1063. IndexedDBLocalPersistence.prototype._remove = function (key) {
  1064. return tslib.__awaiter(this, void 0, void 0, function () {
  1065. var _this = this;
  1066. return tslib.__generator(this, function (_a) {
  1067. return [2 /*return*/, this._withPendingWrite(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1068. return tslib.__generator(this, function (_a) {
  1069. switch (_a.label) {
  1070. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _deleteObject(db, key); })];
  1071. case 1:
  1072. _a.sent();
  1073. delete this.localCache[key];
  1074. return [2 /*return*/, this.notifyServiceWorker(key)];
  1075. }
  1076. });
  1077. }); })];
  1078. });
  1079. });
  1080. };
  1081. IndexedDBLocalPersistence.prototype._poll = function () {
  1082. return tslib.__awaiter(this, void 0, void 0, function () {
  1083. var result, keys, keysInResult, _i, result_1, _a, key, value, _b, _c, localKey;
  1084. return tslib.__generator(this, function (_d) {
  1085. switch (_d.label) {
  1086. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  1087. var getAllRequest = getObjectStore(db, false).getAll();
  1088. return new DBPromise(getAllRequest).toPromise();
  1089. })];
  1090. case 1:
  1091. result = _d.sent();
  1092. if (!result) {
  1093. return [2 /*return*/, []];
  1094. }
  1095. // If we have pending writes in progress abort, we'll get picked up on the next poll
  1096. if (this.pendingWrites !== 0) {
  1097. return [2 /*return*/, []];
  1098. }
  1099. keys = [];
  1100. keysInResult = new Set();
  1101. for (_i = 0, result_1 = result; _i < result_1.length; _i++) {
  1102. _a = result_1[_i], key = _a.fbase_key, value = _a.value;
  1103. keysInResult.add(key);
  1104. if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
  1105. this.notifyListeners(key, value);
  1106. keys.push(key);
  1107. }
  1108. }
  1109. for (_b = 0, _c = Object.keys(this.localCache); _b < _c.length; _b++) {
  1110. localKey = _c[_b];
  1111. if (this.localCache[localKey] && !keysInResult.has(localKey)) {
  1112. // Deleted
  1113. this.notifyListeners(localKey, null);
  1114. keys.push(localKey);
  1115. }
  1116. }
  1117. return [2 /*return*/, keys];
  1118. }
  1119. });
  1120. });
  1121. };
  1122. IndexedDBLocalPersistence.prototype.notifyListeners = function (key, newValue) {
  1123. this.localCache[key] = newValue;
  1124. var listeners = this.listeners[key];
  1125. if (listeners) {
  1126. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  1127. var listener = _a[_i];
  1128. listener(newValue);
  1129. }
  1130. }
  1131. };
  1132. IndexedDBLocalPersistence.prototype.startPolling = function () {
  1133. var _this = this;
  1134. this.stopPolling();
  1135. this.pollTimer = setInterval(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  1136. return [2 /*return*/, this._poll()];
  1137. }); }); }, _POLLING_INTERVAL_MS);
  1138. };
  1139. IndexedDBLocalPersistence.prototype.stopPolling = function () {
  1140. if (this.pollTimer) {
  1141. clearInterval(this.pollTimer);
  1142. this.pollTimer = null;
  1143. }
  1144. };
  1145. IndexedDBLocalPersistence.prototype._addListener = function (key, listener) {
  1146. if (Object.keys(this.listeners).length === 0) {
  1147. this.startPolling();
  1148. }
  1149. if (!this.listeners[key]) {
  1150. this.listeners[key] = new Set();
  1151. // Populate the cache to avoid spuriously triggering on first poll.
  1152. void this._get(key); // This can happen in the background async and we can return immediately.
  1153. }
  1154. this.listeners[key].add(listener);
  1155. };
  1156. IndexedDBLocalPersistence.prototype._removeListener = function (key, listener) {
  1157. if (this.listeners[key]) {
  1158. this.listeners[key].delete(listener);
  1159. if (this.listeners[key].size === 0) {
  1160. delete this.listeners[key];
  1161. }
  1162. }
  1163. if (Object.keys(this.listeners).length === 0) {
  1164. this.stopPolling();
  1165. }
  1166. };
  1167. IndexedDBLocalPersistence.type = 'LOCAL';
  1168. return IndexedDBLocalPersistence;
  1169. }());
  1170. /**
  1171. * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
  1172. * for the underlying storage.
  1173. *
  1174. * @public
  1175. */
  1176. var indexedDBLocalPersistence = IndexedDBLocalPersistence;
  1177. /**
  1178. * @license
  1179. * Copyright 2021 Google LLC
  1180. *
  1181. * Licensed under the Apache License, Version 2.0 (the "License");
  1182. * you may not use this file except in compliance with the License.
  1183. * You may obtain a copy of the License at
  1184. *
  1185. * http://www.apache.org/licenses/LICENSE-2.0
  1186. *
  1187. * Unless required by applicable law or agreed to in writing, software
  1188. * distributed under the License is distributed on an "AS IS" BASIS,
  1189. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1190. * See the License for the specific language governing permissions and
  1191. * limitations under the License.
  1192. */
  1193. /**
  1194. * Chooses a popup/redirect resolver to use. This prefers the override (which
  1195. * is directly passed in), and falls back to the property set on the auth
  1196. * object. If neither are available, this function errors w/ an argument error.
  1197. */
  1198. function _withDefaultResolver(auth, resolverOverride) {
  1199. if (resolverOverride) {
  1200. return phone._getInstance(resolverOverride);
  1201. }
  1202. phone._assert(auth._popupRedirectResolver, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  1203. return auth._popupRedirectResolver;
  1204. }
  1205. /**
  1206. * @license
  1207. * Copyright 2019 Google LLC
  1208. *
  1209. * Licensed under the Apache License, Version 2.0 (the "License");
  1210. * you may not use this file except in compliance with the License.
  1211. * You may obtain a copy of the License at
  1212. *
  1213. * http://www.apache.org/licenses/LICENSE-2.0
  1214. *
  1215. * Unless required by applicable law or agreed to in writing, software
  1216. * distributed under the License is distributed on an "AS IS" BASIS,
  1217. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1218. * See the License for the specific language governing permissions and
  1219. * limitations under the License.
  1220. */
  1221. var IdpCredential = /** @class */ (function (_super) {
  1222. tslib.__extends(IdpCredential, _super);
  1223. function IdpCredential(params) {
  1224. var _this = _super.call(this, "custom" /* ProviderId.CUSTOM */, "custom" /* ProviderId.CUSTOM */) || this;
  1225. _this.params = params;
  1226. return _this;
  1227. }
  1228. IdpCredential.prototype._getIdTokenResponse = function (auth) {
  1229. return phone.signInWithIdp(auth, this._buildIdpRequest());
  1230. };
  1231. IdpCredential.prototype._linkToIdToken = function (auth, idToken) {
  1232. return phone.signInWithIdp(auth, this._buildIdpRequest(idToken));
  1233. };
  1234. IdpCredential.prototype._getReauthenticationResolver = function (auth) {
  1235. return phone.signInWithIdp(auth, this._buildIdpRequest());
  1236. };
  1237. IdpCredential.prototype._buildIdpRequest = function (idToken) {
  1238. var request = {
  1239. requestUri: this.params.requestUri,
  1240. sessionId: this.params.sessionId,
  1241. postBody: this.params.postBody,
  1242. tenantId: this.params.tenantId,
  1243. pendingToken: this.params.pendingToken,
  1244. returnSecureToken: true,
  1245. returnIdpCredential: true
  1246. };
  1247. if (idToken) {
  1248. request.idToken = idToken;
  1249. }
  1250. return request;
  1251. };
  1252. return IdpCredential;
  1253. }(phone.AuthCredential));
  1254. function _signIn(params) {
  1255. return phone._signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
  1256. }
  1257. function _reauth(params) {
  1258. var auth = params.auth, user = params.user;
  1259. phone._assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1260. return phone._reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
  1261. }
  1262. function _link(params) {
  1263. return tslib.__awaiter(this, void 0, void 0, function () {
  1264. var auth, user;
  1265. return tslib.__generator(this, function (_a) {
  1266. auth = params.auth, user = params.user;
  1267. phone._assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1268. return [2 /*return*/, phone._link(user, new IdpCredential(params), params.bypassAuthState)];
  1269. });
  1270. });
  1271. }
  1272. /**
  1273. * @license
  1274. * Copyright 2020 Google LLC
  1275. *
  1276. * Licensed under the Apache License, Version 2.0 (the "License");
  1277. * you may not use this file except in compliance with the License.
  1278. * You may obtain a copy of the License at
  1279. *
  1280. * http://www.apache.org/licenses/LICENSE-2.0
  1281. *
  1282. * Unless required by applicable law or agreed to in writing, software
  1283. * distributed under the License is distributed on an "AS IS" BASIS,
  1284. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1285. * See the License for the specific language governing permissions and
  1286. * limitations under the License.
  1287. */
  1288. /**
  1289. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  1290. * events
  1291. */
  1292. var AbstractPopupRedirectOperation = /** @class */ (function () {
  1293. function AbstractPopupRedirectOperation(auth, filter, resolver, user, bypassAuthState) {
  1294. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1295. this.auth = auth;
  1296. this.resolver = resolver;
  1297. this.user = user;
  1298. this.bypassAuthState = bypassAuthState;
  1299. this.pendingPromise = null;
  1300. this.eventManager = null;
  1301. this.filter = Array.isArray(filter) ? filter : [filter];
  1302. }
  1303. AbstractPopupRedirectOperation.prototype.execute = function () {
  1304. var _this = this;
  1305. return new Promise(function (resolve, reject) { return tslib.__awaiter(_this, void 0, void 0, function () {
  1306. var _a, e_1;
  1307. return tslib.__generator(this, function (_b) {
  1308. switch (_b.label) {
  1309. case 0:
  1310. this.pendingPromise = { resolve: resolve, reject: reject };
  1311. _b.label = 1;
  1312. case 1:
  1313. _b.trys.push([1, 4, , 5]);
  1314. _a = this;
  1315. return [4 /*yield*/, this.resolver._initialize(this.auth)];
  1316. case 2:
  1317. _a.eventManager = _b.sent();
  1318. return [4 /*yield*/, this.onExecution()];
  1319. case 3:
  1320. _b.sent();
  1321. this.eventManager.registerConsumer(this);
  1322. return [3 /*break*/, 5];
  1323. case 4:
  1324. e_1 = _b.sent();
  1325. this.reject(e_1);
  1326. return [3 /*break*/, 5];
  1327. case 5: return [2 /*return*/];
  1328. }
  1329. });
  1330. }); });
  1331. };
  1332. AbstractPopupRedirectOperation.prototype.onAuthEvent = function (event) {
  1333. return tslib.__awaiter(this, void 0, void 0, function () {
  1334. var urlResponse, sessionId, postBody, tenantId, error, type, params, _a, e_2;
  1335. return tslib.__generator(this, function (_b) {
  1336. switch (_b.label) {
  1337. case 0:
  1338. urlResponse = event.urlResponse, sessionId = event.sessionId, postBody = event.postBody, tenantId = event.tenantId, error = event.error, type = event.type;
  1339. if (error) {
  1340. this.reject(error);
  1341. return [2 /*return*/];
  1342. }
  1343. params = {
  1344. auth: this.auth,
  1345. requestUri: urlResponse,
  1346. sessionId: sessionId,
  1347. tenantId: tenantId || undefined,
  1348. postBody: postBody || undefined,
  1349. user: this.user,
  1350. bypassAuthState: this.bypassAuthState
  1351. };
  1352. _b.label = 1;
  1353. case 1:
  1354. _b.trys.push([1, 3, , 4]);
  1355. _a = this.resolve;
  1356. return [4 /*yield*/, this.getIdpTask(type)(params)];
  1357. case 2:
  1358. _a.apply(this, [_b.sent()]);
  1359. return [3 /*break*/, 4];
  1360. case 3:
  1361. e_2 = _b.sent();
  1362. this.reject(e_2);
  1363. return [3 /*break*/, 4];
  1364. case 4: return [2 /*return*/];
  1365. }
  1366. });
  1367. });
  1368. };
  1369. AbstractPopupRedirectOperation.prototype.onError = function (error) {
  1370. this.reject(error);
  1371. };
  1372. AbstractPopupRedirectOperation.prototype.getIdpTask = function (type) {
  1373. switch (type) {
  1374. case "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */:
  1375. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  1376. return _signIn;
  1377. case "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */:
  1378. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  1379. return _link;
  1380. case "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */:
  1381. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  1382. return _reauth;
  1383. default:
  1384. phone._fail(this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1385. }
  1386. };
  1387. AbstractPopupRedirectOperation.prototype.resolve = function (cred) {
  1388. phone.debugAssert(this.pendingPromise, 'Pending promise was never set');
  1389. this.pendingPromise.resolve(cred);
  1390. this.unregisterAndCleanUp();
  1391. };
  1392. AbstractPopupRedirectOperation.prototype.reject = function (error) {
  1393. phone.debugAssert(this.pendingPromise, 'Pending promise was never set');
  1394. this.pendingPromise.reject(error);
  1395. this.unregisterAndCleanUp();
  1396. };
  1397. AbstractPopupRedirectOperation.prototype.unregisterAndCleanUp = function () {
  1398. if (this.eventManager) {
  1399. this.eventManager.unregisterConsumer(this);
  1400. }
  1401. this.pendingPromise = null;
  1402. this.cleanUp();
  1403. };
  1404. return AbstractPopupRedirectOperation;
  1405. }());
  1406. /**
  1407. * @license
  1408. * Copyright 2020 Google LLC
  1409. *
  1410. * Licensed under the Apache License, Version 2.0 (the "License");
  1411. * you may not use this file except in compliance with the License.
  1412. * You may obtain a copy of the License at
  1413. *
  1414. * http://www.apache.org/licenses/LICENSE-2.0
  1415. *
  1416. * Unless required by applicable law or agreed to in writing, software
  1417. * distributed under the License is distributed on an "AS IS" BASIS,
  1418. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1419. * See the License for the specific language governing permissions and
  1420. * limitations under the License.
  1421. */
  1422. var _POLL_WINDOW_CLOSE_TIMEOUT = new phone.Delay(2000, 10000);
  1423. /**
  1424. * Authenticates a Firebase client using a popup-based OAuth authentication flow.
  1425. *
  1426. * @remarks
  1427. * If succeeds, returns the signed in user along with the provider's credential. If sign in was
  1428. * unsuccessful, returns an error object containing additional information about the error.
  1429. *
  1430. * @example
  1431. * ```javascript
  1432. * // Sign in using a popup.
  1433. * const provider = new FacebookAuthProvider();
  1434. * const result = await signInWithPopup(auth, provider);
  1435. *
  1436. * // The signed-in user info.
  1437. * const user = result.user;
  1438. * // This gives you a Facebook Access Token.
  1439. * const credential = provider.credentialFromResult(auth, result);
  1440. * const token = credential.accessToken;
  1441. * ```
  1442. *
  1443. * @param auth - The {@link Auth} instance.
  1444. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1445. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1446. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1447. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1448. *
  1449. *
  1450. * @public
  1451. */
  1452. function signInWithPopup(auth, provider, resolver) {
  1453. return tslib.__awaiter(this, void 0, void 0, function () {
  1454. var authInternal, resolverInternal, action;
  1455. return tslib.__generator(this, function (_a) {
  1456. authInternal = phone._castAuth(auth);
  1457. phone._assertInstanceOf(auth, provider, phone.FederatedAuthProvider);
  1458. resolverInternal = _withDefaultResolver(authInternal, resolver);
  1459. action = new PopupOperation(authInternal, "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);
  1460. return [2 /*return*/, action.executeNotNull()];
  1461. });
  1462. });
  1463. }
  1464. /**
  1465. * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
  1466. * OAuth flow.
  1467. *
  1468. * @remarks
  1469. * If the reauthentication is successful, the returned result will contain the user and the
  1470. * provider's credential.
  1471. *
  1472. * @example
  1473. * ```javascript
  1474. * // Sign in using a popup.
  1475. * const provider = new FacebookAuthProvider();
  1476. * const result = await signInWithPopup(auth, provider);
  1477. * // Reauthenticate using a popup.
  1478. * await reauthenticateWithPopup(result.user, provider);
  1479. * ```
  1480. *
  1481. * @param user - The user.
  1482. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1483. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1484. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1485. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1486. *
  1487. * @public
  1488. */
  1489. function reauthenticateWithPopup(user, provider, resolver) {
  1490. return tslib.__awaiter(this, void 0, void 0, function () {
  1491. var userInternal, resolverInternal, action;
  1492. return tslib.__generator(this, function (_a) {
  1493. userInternal = util.getModularInstance(user);
  1494. phone._assertInstanceOf(userInternal.auth, provider, phone.FederatedAuthProvider);
  1495. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  1496. action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
  1497. return [2 /*return*/, action.executeNotNull()];
  1498. });
  1499. });
  1500. }
  1501. /**
  1502. * Links the authenticated provider to the user account using a pop-up based OAuth flow.
  1503. *
  1504. * @remarks
  1505. * If the linking is successful, the returned result will contain the user and the provider's credential.
  1506. *
  1507. *
  1508. * @example
  1509. * ```javascript
  1510. * // Sign in using some other provider.
  1511. * const result = await signInWithEmailAndPassword(auth, email, password);
  1512. * // Link using a popup.
  1513. * const provider = new FacebookAuthProvider();
  1514. * await linkWithPopup(result.user, provider);
  1515. * ```
  1516. *
  1517. * @param user - The user.
  1518. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1519. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1520. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1521. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1522. *
  1523. * @public
  1524. */
  1525. function linkWithPopup(user, provider, resolver) {
  1526. return tslib.__awaiter(this, void 0, void 0, function () {
  1527. var userInternal, resolverInternal, action;
  1528. return tslib.__generator(this, function (_a) {
  1529. userInternal = util.getModularInstance(user);
  1530. phone._assertInstanceOf(userInternal.auth, provider, phone.FederatedAuthProvider);
  1531. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  1532. action = new PopupOperation(userInternal.auth, "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
  1533. return [2 /*return*/, action.executeNotNull()];
  1534. });
  1535. });
  1536. }
  1537. /**
  1538. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  1539. * events
  1540. *
  1541. */
  1542. var PopupOperation = /** @class */ (function (_super) {
  1543. tslib.__extends(PopupOperation, _super);
  1544. function PopupOperation(auth, filter, provider, resolver, user) {
  1545. var _this = _super.call(this, auth, filter, resolver, user) || this;
  1546. _this.provider = provider;
  1547. _this.authWindow = null;
  1548. _this.pollId = null;
  1549. if (PopupOperation.currentPopupAction) {
  1550. PopupOperation.currentPopupAction.cancel();
  1551. }
  1552. PopupOperation.currentPopupAction = _this;
  1553. return _this;
  1554. }
  1555. PopupOperation.prototype.executeNotNull = function () {
  1556. return tslib.__awaiter(this, void 0, void 0, function () {
  1557. var result;
  1558. return tslib.__generator(this, function (_a) {
  1559. switch (_a.label) {
  1560. case 0: return [4 /*yield*/, this.execute()];
  1561. case 1:
  1562. result = _a.sent();
  1563. phone._assert(result, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1564. return [2 /*return*/, result];
  1565. }
  1566. });
  1567. });
  1568. };
  1569. PopupOperation.prototype.onExecution = function () {
  1570. return tslib.__awaiter(this, void 0, void 0, function () {
  1571. var eventId, _a;
  1572. var _this = this;
  1573. return tslib.__generator(this, function (_b) {
  1574. switch (_b.label) {
  1575. case 0:
  1576. phone.debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
  1577. eventId = _generateEventId();
  1578. _a = this;
  1579. return [4 /*yield*/, this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
  1580. eventId)];
  1581. case 1:
  1582. _a.authWindow = _b.sent();
  1583. this.authWindow.associatedEvent = eventId;
  1584. // Check for web storage support and origin validation _after_ the popup is
  1585. // loaded. These operations are slow (~1 second or so) Rather than
  1586. // waiting on them before opening the window, optimistically open the popup
  1587. // and check for storage support at the same time. If storage support is
  1588. // not available, this will cause the whole thing to reject properly. It
  1589. // will also close the popup, but since the promise has already rejected,
  1590. // the popup closed by user poll will reject into the void.
  1591. this.resolver._originValidation(this.auth).catch(function (e) {
  1592. _this.reject(e);
  1593. });
  1594. this.resolver._isIframeWebStorageSupported(this.auth, function (isSupported) {
  1595. if (!isSupported) {
  1596. _this.reject(phone._createError(_this.auth, "web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));
  1597. }
  1598. });
  1599. // Handle user closure. Notice this does *not* use await
  1600. this.pollUserCancellation();
  1601. return [2 /*return*/];
  1602. }
  1603. });
  1604. });
  1605. };
  1606. Object.defineProperty(PopupOperation.prototype, "eventId", {
  1607. get: function () {
  1608. var _a;
  1609. return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
  1610. },
  1611. enumerable: false,
  1612. configurable: true
  1613. });
  1614. PopupOperation.prototype.cancel = function () {
  1615. this.reject(phone._createError(this.auth, "cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));
  1616. };
  1617. PopupOperation.prototype.cleanUp = function () {
  1618. if (this.authWindow) {
  1619. this.authWindow.close();
  1620. }
  1621. if (this.pollId) {
  1622. window.clearTimeout(this.pollId);
  1623. }
  1624. this.authWindow = null;
  1625. this.pollId = null;
  1626. PopupOperation.currentPopupAction = null;
  1627. };
  1628. PopupOperation.prototype.pollUserCancellation = function () {
  1629. var _this = this;
  1630. var poll = function () {
  1631. var _a, _b;
  1632. if ((_b = (_a = _this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
  1633. // Make sure that there is sufficient time for whatever action to
  1634. // complete. The window could have closed but the sign in network
  1635. // call could still be in flight.
  1636. _this.pollId = window.setTimeout(function () {
  1637. _this.pollId = null;
  1638. _this.reject(phone._createError(_this.auth, "popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));
  1639. }, 2000 /* _Timeout.AUTH_EVENT */);
  1640. return;
  1641. }
  1642. _this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
  1643. };
  1644. poll();
  1645. };
  1646. // Only one popup is ever shown at once. The lifecycle of the current popup
  1647. // can be managed / cancelled by the constructor.
  1648. PopupOperation.currentPopupAction = null;
  1649. return PopupOperation;
  1650. }(AbstractPopupRedirectOperation));
  1651. /**
  1652. * @license
  1653. * Copyright 2020 Google LLC
  1654. *
  1655. * Licensed under the Apache License, Version 2.0 (the "License");
  1656. * you may not use this file except in compliance with the License.
  1657. * You may obtain a copy of the License at
  1658. *
  1659. * http://www.apache.org/licenses/LICENSE-2.0
  1660. *
  1661. * Unless required by applicable law or agreed to in writing, software
  1662. * distributed under the License is distributed on an "AS IS" BASIS,
  1663. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1664. * See the License for the specific language governing permissions and
  1665. * limitations under the License.
  1666. */
  1667. var PENDING_REDIRECT_KEY = 'pendingRedirect';
  1668. // We only get one redirect outcome for any one auth, so just store it
  1669. // in here.
  1670. var redirectOutcomeMap = new Map();
  1671. var RedirectAction = /** @class */ (function (_super) {
  1672. tslib.__extends(RedirectAction, _super);
  1673. function RedirectAction(auth, resolver, bypassAuthState) {
  1674. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1675. var _this = _super.call(this, auth, [
  1676. "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,
  1677. "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */,
  1678. "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */,
  1679. "unknown" /* AuthEventType.UNKNOWN */
  1680. ], resolver, undefined, bypassAuthState) || this;
  1681. _this.eventId = null;
  1682. return _this;
  1683. }
  1684. /**
  1685. * Override the execute function; if we already have a redirect result, then
  1686. * just return it.
  1687. */
  1688. RedirectAction.prototype.execute = function () {
  1689. return tslib.__awaiter(this, void 0, void 0, function () {
  1690. var readyOutcome, hasPendingRedirect, result_1, _a, e_1;
  1691. return tslib.__generator(this, function (_b) {
  1692. switch (_b.label) {
  1693. case 0:
  1694. readyOutcome = redirectOutcomeMap.get(this.auth._key());
  1695. if (!!readyOutcome) return [3 /*break*/, 8];
  1696. _b.label = 1;
  1697. case 1:
  1698. _b.trys.push([1, 6, , 7]);
  1699. return [4 /*yield*/, _getAndClearPendingRedirectStatus(this.resolver, this.auth)];
  1700. case 2:
  1701. hasPendingRedirect = _b.sent();
  1702. if (!hasPendingRedirect) return [3 /*break*/, 4];
  1703. return [4 /*yield*/, _super.prototype.execute.call(this)];
  1704. case 3:
  1705. _a = _b.sent();
  1706. return [3 /*break*/, 5];
  1707. case 4:
  1708. _a = null;
  1709. _b.label = 5;
  1710. case 5:
  1711. result_1 = _a;
  1712. readyOutcome = function () { return Promise.resolve(result_1); };
  1713. return [3 /*break*/, 7];
  1714. case 6:
  1715. e_1 = _b.sent();
  1716. readyOutcome = function () { return Promise.reject(e_1); };
  1717. return [3 /*break*/, 7];
  1718. case 7:
  1719. redirectOutcomeMap.set(this.auth._key(), readyOutcome);
  1720. _b.label = 8;
  1721. case 8:
  1722. // If we're not bypassing auth state, the ready outcome should be set to
  1723. // null.
  1724. if (!this.bypassAuthState) {
  1725. redirectOutcomeMap.set(this.auth._key(), function () { return Promise.resolve(null); });
  1726. }
  1727. return [2 /*return*/, readyOutcome()];
  1728. }
  1729. });
  1730. });
  1731. };
  1732. RedirectAction.prototype.onAuthEvent = function (event) {
  1733. return tslib.__awaiter(this, void 0, void 0, function () {
  1734. var user;
  1735. return tslib.__generator(this, function (_a) {
  1736. switch (_a.label) {
  1737. case 0:
  1738. if (event.type === "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {
  1739. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  1740. }
  1741. else if (event.type === "unknown" /* AuthEventType.UNKNOWN */) {
  1742. // This is a sentinel value indicating there's no pending redirect
  1743. this.resolve(null);
  1744. return [2 /*return*/];
  1745. }
  1746. if (!event.eventId) return [3 /*break*/, 2];
  1747. return [4 /*yield*/, this.auth._redirectUserForId(event.eventId)];
  1748. case 1:
  1749. user = _a.sent();
  1750. if (user) {
  1751. this.user = user;
  1752. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  1753. }
  1754. else {
  1755. this.resolve(null);
  1756. }
  1757. _a.label = 2;
  1758. case 2: return [2 /*return*/];
  1759. }
  1760. });
  1761. });
  1762. };
  1763. RedirectAction.prototype.onExecution = function () {
  1764. return tslib.__awaiter(this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  1765. return [2 /*return*/];
  1766. }); });
  1767. };
  1768. RedirectAction.prototype.cleanUp = function () { };
  1769. return RedirectAction;
  1770. }(AbstractPopupRedirectOperation));
  1771. function _getAndClearPendingRedirectStatus(resolver, auth) {
  1772. return tslib.__awaiter(this, void 0, void 0, function () {
  1773. var key, persistence, hasPendingRedirect;
  1774. return tslib.__generator(this, function (_a) {
  1775. switch (_a.label) {
  1776. case 0:
  1777. key = pendingRedirectKey(auth);
  1778. persistence = resolverPersistence(resolver);
  1779. return [4 /*yield*/, persistence._isAvailable()];
  1780. case 1:
  1781. if (!(_a.sent())) {
  1782. return [2 /*return*/, false];
  1783. }
  1784. return [4 /*yield*/, persistence._get(key)];
  1785. case 2:
  1786. hasPendingRedirect = (_a.sent()) === 'true';
  1787. return [4 /*yield*/, persistence._remove(key)];
  1788. case 3:
  1789. _a.sent();
  1790. return [2 /*return*/, hasPendingRedirect];
  1791. }
  1792. });
  1793. });
  1794. }
  1795. function _setPendingRedirectStatus(resolver, auth) {
  1796. return tslib.__awaiter(this, void 0, void 0, function () {
  1797. return tslib.__generator(this, function (_a) {
  1798. return [2 /*return*/, resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true')];
  1799. });
  1800. });
  1801. }
  1802. function _clearRedirectOutcomes() {
  1803. redirectOutcomeMap.clear();
  1804. }
  1805. function _overrideRedirectResult(auth, result) {
  1806. redirectOutcomeMap.set(auth._key(), result);
  1807. }
  1808. function resolverPersistence(resolver) {
  1809. return phone._getInstance(resolver._redirectPersistence);
  1810. }
  1811. function pendingRedirectKey(auth) {
  1812. return phone._persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
  1813. }
  1814. /**
  1815. * @license
  1816. * Copyright 2020 Google LLC
  1817. *
  1818. * Licensed under the Apache License, Version 2.0 (the "License");
  1819. * you may not use this file except in compliance with the License.
  1820. * You may obtain a copy of the License at
  1821. *
  1822. * http://www.apache.org/licenses/LICENSE-2.0
  1823. *
  1824. * Unless required by applicable law or agreed to in writing, software
  1825. * distributed under the License is distributed on an "AS IS" BASIS,
  1826. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1827. * See the License for the specific language governing permissions and
  1828. * limitations under the License.
  1829. */
  1830. /**
  1831. * Authenticates a Firebase client using a full-page redirect flow.
  1832. *
  1833. * @remarks
  1834. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  1835. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link signInWithRedirect}.
  1836. *
  1837. * @example
  1838. * ```javascript
  1839. * // Sign in using a redirect.
  1840. * const provider = new FacebookAuthProvider();
  1841. * // You can add additional scopes to the provider:
  1842. * provider.addScope('user_birthday');
  1843. * // Start a sign in process for an unauthenticated user.
  1844. * await signInWithRedirect(auth, provider);
  1845. * // This will trigger a full page redirect away from your app
  1846. *
  1847. * // After returning from the redirect when your app initializes you can obtain the result
  1848. * const result = await getRedirectResult(auth);
  1849. * if (result) {
  1850. * // This is the signed-in user
  1851. * const user = result.user;
  1852. * // This gives you a Facebook Access Token.
  1853. * const credential = provider.credentialFromResult(auth, result);
  1854. * const token = credential.accessToken;
  1855. * }
  1856. * // As this API can be used for sign-in, linking and reauthentication,
  1857. * // check the operationType to determine what triggered this redirect
  1858. * // operation.
  1859. * const operationType = result.operationType;
  1860. * ```
  1861. *
  1862. * @param auth - The {@link Auth} instance.
  1863. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1864. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1865. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1866. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1867. *
  1868. * @public
  1869. */
  1870. function signInWithRedirect(auth, provider, resolver) {
  1871. return _signInWithRedirect(auth, provider, resolver);
  1872. }
  1873. function _signInWithRedirect(auth, provider, resolver) {
  1874. return tslib.__awaiter(this, void 0, void 0, function () {
  1875. var authInternal, resolverInternal;
  1876. return tslib.__generator(this, function (_a) {
  1877. switch (_a.label) {
  1878. case 0:
  1879. authInternal = phone._castAuth(auth);
  1880. phone._assertInstanceOf(auth, provider, phone.FederatedAuthProvider);
  1881. // Wait for auth initialization to complete, this will process pending redirects and clear the
  1882. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  1883. // redirect and creating a PENDING_REDIRECT_KEY entry.
  1884. return [4 /*yield*/, authInternal._initializationPromise];
  1885. case 1:
  1886. // Wait for auth initialization to complete, this will process pending redirects and clear the
  1887. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  1888. // redirect and creating a PENDING_REDIRECT_KEY entry.
  1889. _a.sent();
  1890. resolverInternal = _withDefaultResolver(authInternal, resolver);
  1891. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, authInternal)];
  1892. case 2:
  1893. _a.sent();
  1894. return [2 /*return*/, resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */)];
  1895. }
  1896. });
  1897. });
  1898. }
  1899. /**
  1900. * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
  1901. * @remarks
  1902. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  1903. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link reauthenticateWithRedirect}.
  1904. *
  1905. * @example
  1906. * ```javascript
  1907. * // Sign in using a redirect.
  1908. * const provider = new FacebookAuthProvider();
  1909. * const result = await signInWithRedirect(auth, provider);
  1910. * // This will trigger a full page redirect away from your app
  1911. *
  1912. * // After returning from the redirect when your app initializes you can obtain the result
  1913. * const result = await getRedirectResult(auth);
  1914. * // Reauthenticate using a redirect.
  1915. * await reauthenticateWithRedirect(result.user, provider);
  1916. * // This will again trigger a full page redirect away from your app
  1917. *
  1918. * // After returning from the redirect when your app initializes you can obtain the result
  1919. * const result = await getRedirectResult(auth);
  1920. * ```
  1921. *
  1922. * @param user - The user.
  1923. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1924. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1925. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1926. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1927. *
  1928. * @public
  1929. */
  1930. function reauthenticateWithRedirect(user, provider, resolver) {
  1931. return _reauthenticateWithRedirect(user, provider, resolver);
  1932. }
  1933. function _reauthenticateWithRedirect(user, provider, resolver) {
  1934. return tslib.__awaiter(this, void 0, void 0, function () {
  1935. var userInternal, resolverInternal, eventId;
  1936. return tslib.__generator(this, function (_a) {
  1937. switch (_a.label) {
  1938. case 0:
  1939. userInternal = util.getModularInstance(user);
  1940. phone._assertInstanceOf(userInternal.auth, provider, phone.FederatedAuthProvider);
  1941. // Wait for auth initialization to complete, this will process pending redirects and clear the
  1942. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  1943. // redirect and creating a PENDING_REDIRECT_KEY entry.
  1944. return [4 /*yield*/, userInternal.auth._initializationPromise];
  1945. case 1:
  1946. // Wait for auth initialization to complete, this will process pending redirects and clear the
  1947. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  1948. // redirect and creating a PENDING_REDIRECT_KEY entry.
  1949. _a.sent();
  1950. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  1951. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
  1952. case 2:
  1953. _a.sent();
  1954. return [4 /*yield*/, prepareUserForRedirect(userInternal)];
  1955. case 3:
  1956. eventId = _a.sent();
  1957. return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId)];
  1958. }
  1959. });
  1960. });
  1961. }
  1962. /**
  1963. * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
  1964. * @remarks
  1965. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  1966. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link linkWithRedirect}.
  1967. *
  1968. * @example
  1969. * ```javascript
  1970. * // Sign in using some other provider.
  1971. * const result = await signInWithEmailAndPassword(auth, email, password);
  1972. * // Link using a redirect.
  1973. * const provider = new FacebookAuthProvider();
  1974. * await linkWithRedirect(result.user, provider);
  1975. * // This will trigger a full page redirect away from your app
  1976. *
  1977. * // After returning from the redirect when your app initializes you can obtain the result
  1978. * const result = await getRedirectResult(auth);
  1979. * ```
  1980. *
  1981. * @param user - The user.
  1982. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1983. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1984. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1985. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1986. *
  1987. *
  1988. * @public
  1989. */
  1990. function linkWithRedirect(user, provider, resolver) {
  1991. return _linkWithRedirect(user, provider, resolver);
  1992. }
  1993. function _linkWithRedirect(user, provider, resolver) {
  1994. return tslib.__awaiter(this, void 0, void 0, function () {
  1995. var userInternal, resolverInternal, eventId;
  1996. return tslib.__generator(this, function (_a) {
  1997. switch (_a.label) {
  1998. case 0:
  1999. userInternal = util.getModularInstance(user);
  2000. phone._assertInstanceOf(userInternal.auth, provider, phone.FederatedAuthProvider);
  2001. // Wait for auth initialization to complete, this will process pending redirects and clear the
  2002. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  2003. // redirect and creating a PENDING_REDIRECT_KEY entry.
  2004. return [4 /*yield*/, userInternal.auth._initializationPromise];
  2005. case 1:
  2006. // Wait for auth initialization to complete, this will process pending redirects and clear the
  2007. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  2008. // redirect and creating a PENDING_REDIRECT_KEY entry.
  2009. _a.sent();
  2010. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  2011. return [4 /*yield*/, phone._assertLinkedStatus(false, userInternal, provider.providerId)];
  2012. case 2:
  2013. _a.sent();
  2014. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
  2015. case 3:
  2016. _a.sent();
  2017. return [4 /*yield*/, prepareUserForRedirect(userInternal)];
  2018. case 4:
  2019. eventId = _a.sent();
  2020. return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */, eventId)];
  2021. }
  2022. });
  2023. });
  2024. }
  2025. /**
  2026. * Returns a {@link UserCredential} from the redirect-based sign-in flow.
  2027. *
  2028. * @remarks
  2029. * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
  2030. * error. If no redirect operation was called, returns `null`.
  2031. *
  2032. * @example
  2033. * ```javascript
  2034. * // Sign in using a redirect.
  2035. * const provider = new FacebookAuthProvider();
  2036. * // You can add additional scopes to the provider:
  2037. * provider.addScope('user_birthday');
  2038. * // Start a sign in process for an unauthenticated user.
  2039. * await signInWithRedirect(auth, provider);
  2040. * // This will trigger a full page redirect away from your app
  2041. *
  2042. * // After returning from the redirect when your app initializes you can obtain the result
  2043. * const result = await getRedirectResult(auth);
  2044. * if (result) {
  2045. * // This is the signed-in user
  2046. * const user = result.user;
  2047. * // This gives you a Facebook Access Token.
  2048. * const credential = provider.credentialFromResult(auth, result);
  2049. * const token = credential.accessToken;
  2050. * }
  2051. * // As this API can be used for sign-in, linking and reauthentication,
  2052. * // check the operationType to determine what triggered this redirect
  2053. * // operation.
  2054. * const operationType = result.operationType;
  2055. * ```
  2056. *
  2057. * @param auth - The {@link Auth} instance.
  2058. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  2059. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  2060. *
  2061. * @public
  2062. */
  2063. function getRedirectResult(auth, resolver) {
  2064. return tslib.__awaiter(this, void 0, void 0, function () {
  2065. return tslib.__generator(this, function (_a) {
  2066. switch (_a.label) {
  2067. case 0: return [4 /*yield*/, phone._castAuth(auth)._initializationPromise];
  2068. case 1:
  2069. _a.sent();
  2070. return [2 /*return*/, _getRedirectResult(auth, resolver, false)];
  2071. }
  2072. });
  2073. });
  2074. }
  2075. function _getRedirectResult(auth, resolverExtern, bypassAuthState) {
  2076. if (bypassAuthState === void 0) { bypassAuthState = false; }
  2077. return tslib.__awaiter(this, void 0, void 0, function () {
  2078. var authInternal, resolver, action, result;
  2079. return tslib.__generator(this, function (_a) {
  2080. switch (_a.label) {
  2081. case 0:
  2082. authInternal = phone._castAuth(auth);
  2083. resolver = _withDefaultResolver(authInternal, resolverExtern);
  2084. action = new RedirectAction(authInternal, resolver, bypassAuthState);
  2085. return [4 /*yield*/, action.execute()];
  2086. case 1:
  2087. result = _a.sent();
  2088. if (!(result && !bypassAuthState)) return [3 /*break*/, 4];
  2089. delete result.user._redirectEventId;
  2090. return [4 /*yield*/, authInternal._persistUserIfCurrent(result.user)];
  2091. case 2:
  2092. _a.sent();
  2093. return [4 /*yield*/, authInternal._setRedirectUser(null, resolverExtern)];
  2094. case 3:
  2095. _a.sent();
  2096. _a.label = 4;
  2097. case 4: return [2 /*return*/, result];
  2098. }
  2099. });
  2100. });
  2101. }
  2102. function prepareUserForRedirect(user) {
  2103. return tslib.__awaiter(this, void 0, void 0, function () {
  2104. var eventId;
  2105. return tslib.__generator(this, function (_a) {
  2106. switch (_a.label) {
  2107. case 0:
  2108. eventId = _generateEventId("".concat(user.uid, ":::"));
  2109. user._redirectEventId = eventId;
  2110. return [4 /*yield*/, user.auth._setRedirectUser(user)];
  2111. case 1:
  2112. _a.sent();
  2113. return [4 /*yield*/, user.auth._persistUserIfCurrent(user)];
  2114. case 2:
  2115. _a.sent();
  2116. return [2 /*return*/, eventId];
  2117. }
  2118. });
  2119. });
  2120. }
  2121. /**
  2122. * @license
  2123. * Copyright 2020 Google LLC
  2124. *
  2125. * Licensed under the Apache License, Version 2.0 (the "License");
  2126. * you may not use this file except in compliance with the License.
  2127. * You may obtain a copy of the License at
  2128. *
  2129. * http://www.apache.org/licenses/LICENSE-2.0
  2130. *
  2131. * Unless required by applicable law or agreed to in writing, software
  2132. * distributed under the License is distributed on an "AS IS" BASIS,
  2133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2134. * See the License for the specific language governing permissions and
  2135. * limitations under the License.
  2136. */
  2137. // The amount of time to store the UIDs of seen events; this is
  2138. // set to 10 min by default
  2139. var EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
  2140. var AuthEventManager = /** @class */ (function () {
  2141. function AuthEventManager(auth) {
  2142. this.auth = auth;
  2143. this.cachedEventUids = new Set();
  2144. this.consumers = new Set();
  2145. this.queuedRedirectEvent = null;
  2146. this.hasHandledPotentialRedirect = false;
  2147. this.lastProcessedEventTime = Date.now();
  2148. }
  2149. AuthEventManager.prototype.registerConsumer = function (authEventConsumer) {
  2150. this.consumers.add(authEventConsumer);
  2151. if (this.queuedRedirectEvent &&
  2152. this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
  2153. this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
  2154. this.saveEventToCache(this.queuedRedirectEvent);
  2155. this.queuedRedirectEvent = null;
  2156. }
  2157. };
  2158. AuthEventManager.prototype.unregisterConsumer = function (authEventConsumer) {
  2159. this.consumers.delete(authEventConsumer);
  2160. };
  2161. AuthEventManager.prototype.onEvent = function (event) {
  2162. var _this = this;
  2163. // Check if the event has already been handled
  2164. if (this.hasEventBeenHandled(event)) {
  2165. return false;
  2166. }
  2167. var handled = false;
  2168. this.consumers.forEach(function (consumer) {
  2169. if (_this.isEventForConsumer(event, consumer)) {
  2170. handled = true;
  2171. _this.sendToConsumer(event, consumer);
  2172. _this.saveEventToCache(event);
  2173. }
  2174. });
  2175. if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
  2176. // If we've already seen a redirect before, or this is a popup event,
  2177. // bail now
  2178. return handled;
  2179. }
  2180. this.hasHandledPotentialRedirect = true;
  2181. // If the redirect wasn't handled, hang on to it
  2182. if (!handled) {
  2183. this.queuedRedirectEvent = event;
  2184. handled = true;
  2185. }
  2186. return handled;
  2187. };
  2188. AuthEventManager.prototype.sendToConsumer = function (event, consumer) {
  2189. var _a;
  2190. if (event.error && !isNullRedirectEvent(event)) {
  2191. var code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
  2192. "internal-error" /* AuthErrorCode.INTERNAL_ERROR */;
  2193. consumer.onError(phone._createError(this.auth, code));
  2194. }
  2195. else {
  2196. consumer.onAuthEvent(event);
  2197. }
  2198. };
  2199. AuthEventManager.prototype.isEventForConsumer = function (event, consumer) {
  2200. var eventIdMatches = consumer.eventId === null ||
  2201. (!!event.eventId && event.eventId === consumer.eventId);
  2202. return consumer.filter.includes(event.type) && eventIdMatches;
  2203. };
  2204. AuthEventManager.prototype.hasEventBeenHandled = function (event) {
  2205. if (Date.now() - this.lastProcessedEventTime >=
  2206. EVENT_DUPLICATION_CACHE_DURATION_MS) {
  2207. this.cachedEventUids.clear();
  2208. }
  2209. return this.cachedEventUids.has(eventUid(event));
  2210. };
  2211. AuthEventManager.prototype.saveEventToCache = function (event) {
  2212. this.cachedEventUids.add(eventUid(event));
  2213. this.lastProcessedEventTime = Date.now();
  2214. };
  2215. return AuthEventManager;
  2216. }());
  2217. function eventUid(e) {
  2218. return [e.type, e.eventId, e.sessionId, e.tenantId].filter(function (v) { return v; }).join('-');
  2219. }
  2220. function isNullRedirectEvent(_a) {
  2221. var type = _a.type, error = _a.error;
  2222. return (type === "unknown" /* AuthEventType.UNKNOWN */ &&
  2223. (error === null || error === void 0 ? void 0 : error.code) === "auth/".concat("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */));
  2224. }
  2225. function isRedirectEvent(event) {
  2226. switch (event.type) {
  2227. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  2228. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  2229. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  2230. return true;
  2231. case "unknown" /* AuthEventType.UNKNOWN */:
  2232. return isNullRedirectEvent(event);
  2233. default:
  2234. return false;
  2235. }
  2236. }
  2237. /**
  2238. * @license
  2239. * Copyright 2020 Google LLC
  2240. *
  2241. * Licensed under the Apache License, Version 2.0 (the "License");
  2242. * you may not use this file except in compliance with the License.
  2243. * You may obtain a copy of the License at
  2244. *
  2245. * http://www.apache.org/licenses/LICENSE-2.0
  2246. *
  2247. * Unless required by applicable law or agreed to in writing, software
  2248. * distributed under the License is distributed on an "AS IS" BASIS,
  2249. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2250. * See the License for the specific language governing permissions and
  2251. * limitations under the License.
  2252. */
  2253. function _getProjectConfig(auth, request) {
  2254. if (request === void 0) { request = {}; }
  2255. return tslib.__awaiter(this, void 0, void 0, function () {
  2256. return tslib.__generator(this, function (_a) {
  2257. return [2 /*return*/, phone._performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/projects" /* Endpoint.GET_PROJECT_CONFIG */, request)];
  2258. });
  2259. });
  2260. }
  2261. /**
  2262. * @license
  2263. * Copyright 2020 Google LLC
  2264. *
  2265. * Licensed under the Apache License, Version 2.0 (the "License");
  2266. * you may not use this file except in compliance with the License.
  2267. * You may obtain a copy of the License at
  2268. *
  2269. * http://www.apache.org/licenses/LICENSE-2.0
  2270. *
  2271. * Unless required by applicable law or agreed to in writing, software
  2272. * distributed under the License is distributed on an "AS IS" BASIS,
  2273. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2274. * See the License for the specific language governing permissions and
  2275. * limitations under the License.
  2276. */
  2277. var IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  2278. var HTTP_REGEX = /^https?/;
  2279. function _validateOrigin$1(auth) {
  2280. return tslib.__awaiter(this, void 0, void 0, function () {
  2281. var authorizedDomains, _i, authorizedDomains_1, domain;
  2282. return tslib.__generator(this, function (_a) {
  2283. switch (_a.label) {
  2284. case 0:
  2285. // Skip origin validation if we are in an emulated environment
  2286. if (auth.config.emulator) {
  2287. return [2 /*return*/];
  2288. }
  2289. return [4 /*yield*/, _getProjectConfig(auth)];
  2290. case 1:
  2291. authorizedDomains = (_a.sent()).authorizedDomains;
  2292. for (_i = 0, authorizedDomains_1 = authorizedDomains; _i < authorizedDomains_1.length; _i++) {
  2293. domain = authorizedDomains_1[_i];
  2294. try {
  2295. if (matchDomain(domain)) {
  2296. return [2 /*return*/];
  2297. }
  2298. }
  2299. catch (_b) {
  2300. // Do nothing if there's a URL error; just continue searching
  2301. }
  2302. }
  2303. // In the old SDK, this error also provides helpful messages.
  2304. phone._fail(auth, "unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */);
  2305. return [2 /*return*/];
  2306. }
  2307. });
  2308. });
  2309. }
  2310. function matchDomain(expected) {
  2311. var currentUrl = phone._getCurrentUrl();
  2312. var _a = new URL(currentUrl), protocol = _a.protocol, hostname = _a.hostname;
  2313. if (expected.startsWith('chrome-extension://')) {
  2314. var ceUrl = new URL(expected);
  2315. if (ceUrl.hostname === '' && hostname === '') {
  2316. // For some reason we're not parsing chrome URLs properly
  2317. return (protocol === 'chrome-extension:' &&
  2318. expected.replace('chrome-extension://', '') ===
  2319. currentUrl.replace('chrome-extension://', ''));
  2320. }
  2321. return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
  2322. }
  2323. if (!HTTP_REGEX.test(protocol)) {
  2324. return false;
  2325. }
  2326. if (IP_ADDRESS_REGEX.test(expected)) {
  2327. // The domain has to be exactly equal to the pattern, as an IP domain will
  2328. // only contain the IP, no extra character.
  2329. return hostname === expected;
  2330. }
  2331. // Dots in pattern should be escaped.
  2332. var escapedDomainPattern = expected.replace(/\./g, '\\.');
  2333. // Non ip address domains.
  2334. // domain.com = *.domain.com OR domain.com
  2335. var re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
  2336. return re.test(hostname);
  2337. }
  2338. /**
  2339. * @license
  2340. * Copyright 2020 Google LLC.
  2341. *
  2342. * Licensed under the Apache License, Version 2.0 (the "License");
  2343. * you may not use this file except in compliance with the License.
  2344. * You may obtain a copy of the License at
  2345. *
  2346. * http://www.apache.org/licenses/LICENSE-2.0
  2347. *
  2348. * Unless required by applicable law or agreed to in writing, software
  2349. * distributed under the License is distributed on an "AS IS" BASIS,
  2350. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2351. * See the License for the specific language governing permissions and
  2352. * limitations under the License.
  2353. */
  2354. var NETWORK_TIMEOUT = new phone.Delay(30000, 60000);
  2355. /**
  2356. * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
  2357. * it will stop working after a retrial. This is a hack to fix this issue.
  2358. */
  2359. function resetUnloadedGapiModules() {
  2360. // Clear last failed gapi.load state to force next gapi.load to first
  2361. // load the failed gapi.iframes module.
  2362. // Get gapix.beacon context.
  2363. var beacon = phone._window().___jsl;
  2364. // Get current hint.
  2365. if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
  2366. // Get gapi hint.
  2367. for (var _i = 0, _a = Object.keys(beacon.H); _i < _a.length; _i++) {
  2368. var hint = _a[_i];
  2369. // Requested modules.
  2370. beacon.H[hint].r = beacon.H[hint].r || [];
  2371. // Loaded modules.
  2372. beacon.H[hint].L = beacon.H[hint].L || [];
  2373. // Set requested modules to a copy of the loaded modules.
  2374. beacon.H[hint].r = tslib.__spreadArray([], beacon.H[hint].L, true);
  2375. // Clear pending callbacks.
  2376. if (beacon.CP) {
  2377. for (var i = 0; i < beacon.CP.length; i++) {
  2378. // Remove all failed pending callbacks.
  2379. beacon.CP[i] = null;
  2380. }
  2381. }
  2382. }
  2383. }
  2384. }
  2385. function loadGapi(auth) {
  2386. return new Promise(function (resolve, reject) {
  2387. var _a, _b, _c;
  2388. // Function to run when gapi.load is ready.
  2389. function loadGapiIframe() {
  2390. // The developer may have tried to previously run gapi.load and failed.
  2391. // Run this to fix that.
  2392. resetUnloadedGapiModules();
  2393. gapi.load('gapi.iframes', {
  2394. callback: function () {
  2395. resolve(gapi.iframes.getContext());
  2396. },
  2397. ontimeout: function () {
  2398. // The above reset may be sufficient, but having this reset after
  2399. // failure ensures that if the developer calls gapi.load after the
  2400. // connection is re-established and before another attempt to embed
  2401. // the iframe, it would work and would not be broken because of our
  2402. // failed attempt.
  2403. // Timeout when gapi.iframes.Iframe not loaded.
  2404. resetUnloadedGapiModules();
  2405. reject(phone._createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  2406. },
  2407. timeout: NETWORK_TIMEOUT.get()
  2408. });
  2409. }
  2410. if ((_b = (_a = phone._window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
  2411. // If gapi.iframes.Iframe available, resolve.
  2412. resolve(gapi.iframes.getContext());
  2413. }
  2414. else if (!!((_c = phone._window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
  2415. // Gapi loader ready, load gapi.iframes.
  2416. loadGapiIframe();
  2417. }
  2418. else {
  2419. // Create a new iframe callback when this is called so as not to overwrite
  2420. // any previous defined callback. This happens if this method is called
  2421. // multiple times in parallel and could result in the later callback
  2422. // overwriting the previous one. This would end up with a iframe
  2423. // timeout.
  2424. var cbName = phone._generateCallbackName('iframefcb');
  2425. // GApi loader not available, dynamically load platform.js.
  2426. phone._window()[cbName] = function () {
  2427. // GApi loader should be ready.
  2428. if (!!gapi.load) {
  2429. loadGapiIframe();
  2430. }
  2431. else {
  2432. // Gapi loader failed, throw error.
  2433. reject(phone._createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  2434. }
  2435. };
  2436. // Load GApi loader.
  2437. return phone._loadJS("https://apis.google.com/js/api.js?onload=".concat(cbName))
  2438. .catch(function (e) { return reject(e); });
  2439. }
  2440. }).catch(function (error) {
  2441. // Reset cached promise to allow for retrial.
  2442. cachedGApiLoader = null;
  2443. throw error;
  2444. });
  2445. }
  2446. var cachedGApiLoader = null;
  2447. function _loadGapi(auth) {
  2448. cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  2449. return cachedGApiLoader;
  2450. }
  2451. /**
  2452. * @license
  2453. * Copyright 2020 Google LLC.
  2454. *
  2455. * Licensed under the Apache License, Version 2.0 (the "License");
  2456. * you may not use this file except in compliance with the License.
  2457. * You may obtain a copy of the License at
  2458. *
  2459. * http://www.apache.org/licenses/LICENSE-2.0
  2460. *
  2461. * Unless required by applicable law or agreed to in writing, software
  2462. * distributed under the License is distributed on an "AS IS" BASIS,
  2463. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2464. * See the License for the specific language governing permissions and
  2465. * limitations under the License.
  2466. */
  2467. var PING_TIMEOUT = new phone.Delay(5000, 15000);
  2468. var IFRAME_PATH = '__/auth/iframe';
  2469. var EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
  2470. var IFRAME_ATTRIBUTES = {
  2471. style: {
  2472. position: 'absolute',
  2473. top: '-100px',
  2474. width: '1px',
  2475. height: '1px'
  2476. },
  2477. 'aria-hidden': 'true',
  2478. tabindex: '-1'
  2479. };
  2480. // Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
  2481. // anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
  2482. var EID_FROM_APIHOST = new Map([
  2483. ["identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */, 'p'],
  2484. ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
  2485. ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
  2486. ]);
  2487. function getIframeUrl(auth) {
  2488. var config = auth.config;
  2489. phone._assert(config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  2490. var url = config.emulator
  2491. ? phone._emulatorUrl(config, EMULATED_IFRAME_PATH)
  2492. : "https://".concat(auth.config.authDomain, "/").concat(IFRAME_PATH);
  2493. var params = {
  2494. apiKey: config.apiKey,
  2495. appName: auth.name,
  2496. v: app.SDK_VERSION
  2497. };
  2498. var eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  2499. if (eid) {
  2500. params.eid = eid;
  2501. }
  2502. var frameworks = auth._getFrameworks();
  2503. if (frameworks.length) {
  2504. params.fw = frameworks.join(',');
  2505. }
  2506. return "".concat(url, "?").concat(util.querystring(params).slice(1));
  2507. }
  2508. function _openIframe(auth) {
  2509. return tslib.__awaiter(this, void 0, void 0, function () {
  2510. var context, gapi;
  2511. var _this = this;
  2512. return tslib.__generator(this, function (_a) {
  2513. switch (_a.label) {
  2514. case 0: return [4 /*yield*/, _loadGapi(auth)];
  2515. case 1:
  2516. context = _a.sent();
  2517. gapi = phone._window().gapi;
  2518. phone._assert(gapi, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2519. return [2 /*return*/, context.open({
  2520. where: document.body,
  2521. url: getIframeUrl(auth),
  2522. messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
  2523. attributes: IFRAME_ATTRIBUTES,
  2524. dontclear: true
  2525. }, function (iframe) {
  2526. return new Promise(function (resolve, reject) { return tslib.__awaiter(_this, void 0, void 0, function () {
  2527. // Clear timer and resolve pending iframe ready promise.
  2528. function clearTimerAndResolve() {
  2529. phone._window().clearTimeout(networkErrorTimer);
  2530. resolve(iframe);
  2531. }
  2532. var networkError, networkErrorTimer;
  2533. return tslib.__generator(this, function (_a) {
  2534. switch (_a.label) {
  2535. case 0: return [4 /*yield*/, iframe.restyle({
  2536. // Prevent iframe from closing on mouse out.
  2537. setHideOnLeave: false
  2538. })];
  2539. case 1:
  2540. _a.sent();
  2541. networkError = phone._createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  2542. networkErrorTimer = phone._window().setTimeout(function () {
  2543. reject(networkError);
  2544. }, PING_TIMEOUT.get());
  2545. // This returns an IThenable. However the reject part does not call
  2546. // when the iframe is not loaded.
  2547. iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, function () {
  2548. reject(networkError);
  2549. });
  2550. return [2 /*return*/];
  2551. }
  2552. });
  2553. }); });
  2554. })];
  2555. }
  2556. });
  2557. });
  2558. }
  2559. /**
  2560. * @license
  2561. * Copyright 2020 Google LLC.
  2562. *
  2563. * Licensed under the Apache License, Version 2.0 (the "License");
  2564. * you may not use this file except in compliance with the License.
  2565. * You may obtain a copy of the License at
  2566. *
  2567. * http://www.apache.org/licenses/LICENSE-2.0
  2568. *
  2569. * Unless required by applicable law or agreed to in writing, software
  2570. * distributed under the License is distributed on an "AS IS" BASIS,
  2571. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2572. * See the License for the specific language governing permissions and
  2573. * limitations under the License.
  2574. */
  2575. var BASE_POPUP_OPTIONS = {
  2576. location: 'yes',
  2577. resizable: 'yes',
  2578. statusbar: 'yes',
  2579. toolbar: 'no'
  2580. };
  2581. var DEFAULT_WIDTH = 500;
  2582. var DEFAULT_HEIGHT = 600;
  2583. var TARGET_BLANK = '_blank';
  2584. var FIREFOX_EMPTY_URL = 'http://localhost';
  2585. var AuthPopup = /** @class */ (function () {
  2586. function AuthPopup(window) {
  2587. this.window = window;
  2588. this.associatedEvent = null;
  2589. }
  2590. AuthPopup.prototype.close = function () {
  2591. if (this.window) {
  2592. try {
  2593. this.window.close();
  2594. }
  2595. catch (e) { }
  2596. }
  2597. };
  2598. return AuthPopup;
  2599. }());
  2600. function _open(auth, url, name, width, height) {
  2601. if (width === void 0) { width = DEFAULT_WIDTH; }
  2602. if (height === void 0) { height = DEFAULT_HEIGHT; }
  2603. var top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  2604. var left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  2605. var target = '';
  2606. var options = tslib.__assign(tslib.__assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top: top, left: left });
  2607. // Chrome iOS 7 and 8 is returning an undefined popup win when target is
  2608. // specified, even though the popup is not necessarily blocked.
  2609. var ua = util.getUA().toLowerCase();
  2610. if (name) {
  2611. target = phone._isChromeIOS(ua) ? TARGET_BLANK : name;
  2612. }
  2613. if (phone._isFirefox(ua)) {
  2614. // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
  2615. url = url || FIREFOX_EMPTY_URL;
  2616. // Firefox disables by default scrolling on popup windows, which can create
  2617. // issues when the user has many Google accounts, for instance.
  2618. options.scrollbars = 'yes';
  2619. }
  2620. var optionsString = Object.entries(options).reduce(function (accum, _a) {
  2621. var key = _a[0], value = _a[1];
  2622. return "".concat(accum).concat(key, "=").concat(value, ",");
  2623. }, '');
  2624. if (phone._isIOSStandalone(ua) && target !== '_self') {
  2625. openAsNewWindowIOS(url || '', target);
  2626. return new AuthPopup(null);
  2627. }
  2628. // about:blank getting sanitized causing browsers like IE/Edge to display
  2629. // brief error message before redirecting to handler.
  2630. var newWin = window.open(url || '', target, optionsString);
  2631. phone._assert(newWin, auth, "popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */);
  2632. // Flaky on IE edge, encapsulate with a try and catch.
  2633. try {
  2634. newWin.focus();
  2635. }
  2636. catch (e) { }
  2637. return new AuthPopup(newWin);
  2638. }
  2639. function openAsNewWindowIOS(url, target) {
  2640. var el = document.createElement('a');
  2641. el.href = url;
  2642. el.target = target;
  2643. var click = document.createEvent('MouseEvent');
  2644. click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  2645. el.dispatchEvent(click);
  2646. }
  2647. /**
  2648. * @license
  2649. * Copyright 2021 Google LLC
  2650. *
  2651. * Licensed under the Apache License, Version 2.0 (the "License");
  2652. * you may not use this file except in compliance with the License.
  2653. * You may obtain a copy of the License at
  2654. *
  2655. * http://www.apache.org/licenses/LICENSE-2.0
  2656. *
  2657. * Unless required by applicable law or agreed to in writing, software
  2658. * distributed under the License is distributed on an "AS IS" BASIS,
  2659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2660. * See the License for the specific language governing permissions and
  2661. * limitations under the License.
  2662. */
  2663. /**
  2664. * URL for Authentication widget which will initiate the OAuth handshake
  2665. *
  2666. * @internal
  2667. */
  2668. var WIDGET_PATH = '__/auth/handler';
  2669. /**
  2670. * URL for emulated environment
  2671. *
  2672. * @internal
  2673. */
  2674. var EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
  2675. function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  2676. phone._assert(auth.config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  2677. phone._assert(auth.config.apiKey, auth, "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */);
  2678. var params = {
  2679. apiKey: auth.config.apiKey,
  2680. appName: auth.name,
  2681. authType: authType,
  2682. redirectUrl: redirectUrl,
  2683. v: app.SDK_VERSION,
  2684. eventId: eventId
  2685. };
  2686. if (provider instanceof phone.FederatedAuthProvider) {
  2687. provider.setDefaultLanguage(auth.languageCode);
  2688. params.providerId = provider.providerId || '';
  2689. if (!util.isEmpty(provider.getCustomParameters())) {
  2690. params.customParameters = JSON.stringify(provider.getCustomParameters());
  2691. }
  2692. // TODO set additionalParams from the provider as well?
  2693. for (var _i = 0, _a = Object.entries(additionalParams || {}); _i < _a.length; _i++) {
  2694. var _b = _a[_i], key = _b[0], value = _b[1];
  2695. params[key] = value;
  2696. }
  2697. }
  2698. if (provider instanceof phone.BaseOAuthProvider) {
  2699. var scopes = provider.getScopes().filter(function (scope) { return scope !== ''; });
  2700. if (scopes.length > 0) {
  2701. params.scopes = scopes.join(',');
  2702. }
  2703. }
  2704. if (auth.tenantId) {
  2705. params.tid = auth.tenantId;
  2706. }
  2707. // TODO: maybe set eid as endipointId
  2708. // TODO: maybe set fw as Frameworks.join(",")
  2709. var paramsDict = params;
  2710. for (var _c = 0, _d = Object.keys(paramsDict); _c < _d.length; _c++) {
  2711. var key = _d[_c];
  2712. if (paramsDict[key] === undefined) {
  2713. delete paramsDict[key];
  2714. }
  2715. }
  2716. return "".concat(getHandlerBase(auth), "?").concat(util.querystring(paramsDict).slice(1));
  2717. }
  2718. function getHandlerBase(_a) {
  2719. var config = _a.config;
  2720. if (!config.emulator) {
  2721. return "https://".concat(config.authDomain, "/").concat(WIDGET_PATH);
  2722. }
  2723. return phone._emulatorUrl(config, EMULATOR_WIDGET_PATH);
  2724. }
  2725. /**
  2726. * @license
  2727. * Copyright 2020 Google LLC
  2728. *
  2729. * Licensed under the Apache License, Version 2.0 (the "License");
  2730. * you may not use this file except in compliance with the License.
  2731. * You may obtain a copy of the License at
  2732. *
  2733. * http://www.apache.org/licenses/LICENSE-2.0
  2734. *
  2735. * Unless required by applicable law or agreed to in writing, software
  2736. * distributed under the License is distributed on an "AS IS" BASIS,
  2737. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2738. * See the License for the specific language governing permissions and
  2739. * limitations under the License.
  2740. */
  2741. /**
  2742. * The special web storage event
  2743. *
  2744. */
  2745. var WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
  2746. var BrowserPopupRedirectResolver = /** @class */ (function () {
  2747. function BrowserPopupRedirectResolver() {
  2748. this.eventManagers = {};
  2749. this.iframes = {};
  2750. this.originValidationPromises = {};
  2751. this._redirectPersistence = browserSessionPersistence;
  2752. this._completeRedirectFn = _getRedirectResult;
  2753. this._overrideRedirectResult = _overrideRedirectResult;
  2754. }
  2755. // Wrapping in async even though we don't await anywhere in order
  2756. // to make sure errors are raised as promise rejections
  2757. BrowserPopupRedirectResolver.prototype._openPopup = function (auth, provider, authType, eventId) {
  2758. var _a;
  2759. return tslib.__awaiter(this, void 0, void 0, function () {
  2760. var url;
  2761. return tslib.__generator(this, function (_b) {
  2762. phone.debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
  2763. url = _getRedirectUrl(auth, provider, authType, phone._getCurrentUrl(), eventId);
  2764. return [2 /*return*/, _open(auth, url, _generateEventId())];
  2765. });
  2766. });
  2767. };
  2768. BrowserPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  2769. return tslib.__awaiter(this, void 0, void 0, function () {
  2770. return tslib.__generator(this, function (_a) {
  2771. switch (_a.label) {
  2772. case 0: return [4 /*yield*/, this._originValidation(auth)];
  2773. case 1:
  2774. _a.sent();
  2775. phone._setWindowLocation(_getRedirectUrl(auth, provider, authType, phone._getCurrentUrl(), eventId));
  2776. return [2 /*return*/, new Promise(function () { })];
  2777. }
  2778. });
  2779. });
  2780. };
  2781. BrowserPopupRedirectResolver.prototype._initialize = function (auth) {
  2782. var _this = this;
  2783. var key = auth._key();
  2784. if (this.eventManagers[key]) {
  2785. var _a = this.eventManagers[key], manager = _a.manager, promise_1 = _a.promise;
  2786. if (manager) {
  2787. return Promise.resolve(manager);
  2788. }
  2789. else {
  2790. phone.debugAssert(promise_1, 'If manager is not set, promise should be');
  2791. return promise_1;
  2792. }
  2793. }
  2794. var promise = this.initAndGetManager(auth);
  2795. this.eventManagers[key] = { promise: promise };
  2796. // If the promise is rejected, the key should be removed so that the
  2797. // operation can be retried later.
  2798. promise.catch(function () {
  2799. delete _this.eventManagers[key];
  2800. });
  2801. return promise;
  2802. };
  2803. BrowserPopupRedirectResolver.prototype.initAndGetManager = function (auth) {
  2804. return tslib.__awaiter(this, void 0, void 0, function () {
  2805. var iframe, manager;
  2806. return tslib.__generator(this, function (_a) {
  2807. switch (_a.label) {
  2808. case 0: return [4 /*yield*/, _openIframe(auth)];
  2809. case 1:
  2810. iframe = _a.sent();
  2811. manager = new AuthEventManager(auth);
  2812. iframe.register('authEvent', function (iframeEvent) {
  2813. phone._assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */);
  2814. // TODO: Consider splitting redirect and popup events earlier on
  2815. var handled = manager.onEvent(iframeEvent.authEvent);
  2816. return { status: handled ? "ACK" /* GapiOutcome.ACK */ : "ERROR" /* GapiOutcome.ERROR */ };
  2817. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  2818. this.eventManagers[auth._key()] = { manager: manager };
  2819. this.iframes[auth._key()] = iframe;
  2820. return [2 /*return*/, manager];
  2821. }
  2822. });
  2823. });
  2824. };
  2825. BrowserPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (auth, cb) {
  2826. var iframe = this.iframes[auth._key()];
  2827. iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, function (result) {
  2828. var _a;
  2829. var isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
  2830. if (isSupported !== undefined) {
  2831. cb(!!isSupported);
  2832. }
  2833. phone._fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2834. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  2835. };
  2836. BrowserPopupRedirectResolver.prototype._originValidation = function (auth) {
  2837. var key = auth._key();
  2838. if (!this.originValidationPromises[key]) {
  2839. this.originValidationPromises[key] = _validateOrigin$1(auth);
  2840. }
  2841. return this.originValidationPromises[key];
  2842. };
  2843. Object.defineProperty(BrowserPopupRedirectResolver.prototype, "_shouldInitProactively", {
  2844. get: function () {
  2845. // Mobile browsers and Safari need to optimistically initialize
  2846. return phone._isMobileBrowser() || phone._isSafari() || phone._isIOS();
  2847. },
  2848. enumerable: false,
  2849. configurable: true
  2850. });
  2851. return BrowserPopupRedirectResolver;
  2852. }());
  2853. /**
  2854. * An implementation of {@link PopupRedirectResolver} suitable for browser
  2855. * based applications.
  2856. *
  2857. * @public
  2858. */
  2859. var browserPopupRedirectResolver = BrowserPopupRedirectResolver;
  2860. /**
  2861. * @license
  2862. * Copyright 2021 Google LLC
  2863. *
  2864. * Licensed under the Apache License, Version 2.0 (the "License");
  2865. * you may not use this file except in compliance with the License.
  2866. * You may obtain a copy of the License at
  2867. *
  2868. * http://www.apache.org/licenses/LICENSE-2.0
  2869. *
  2870. * Unless required by applicable law or agreed to in writing, software
  2871. * distributed under the License is distributed on an "AS IS" BASIS,
  2872. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2873. * See the License for the specific language governing permissions and
  2874. * limitations under the License.
  2875. */
  2876. var DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
  2877. var authIdTokenMaxAge = util.getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
  2878. var lastPostedIdToken = null;
  2879. var mintCookieFactory = function (url) { return function (user) { return tslib.__awaiter(void 0, void 0, void 0, function () {
  2880. var idTokenResult, _a, idTokenAge, idToken;
  2881. return tslib.__generator(this, function (_b) {
  2882. switch (_b.label) {
  2883. case 0:
  2884. _a = user;
  2885. if (!_a) return [3 /*break*/, 2];
  2886. return [4 /*yield*/, user.getIdTokenResult()];
  2887. case 1:
  2888. _a = (_b.sent());
  2889. _b.label = 2;
  2890. case 2:
  2891. idTokenResult = _a;
  2892. idTokenAge = idTokenResult &&
  2893. (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;
  2894. if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
  2895. return [2 /*return*/];
  2896. }
  2897. idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  2898. if (lastPostedIdToken === idToken) {
  2899. return [2 /*return*/];
  2900. }
  2901. lastPostedIdToken = idToken;
  2902. return [4 /*yield*/, fetch(url, {
  2903. method: idToken ? 'POST' : 'DELETE',
  2904. headers: idToken
  2905. ? {
  2906. 'Authorization': "Bearer ".concat(idToken)
  2907. }
  2908. : {}
  2909. })];
  2910. case 3:
  2911. _b.sent();
  2912. return [2 /*return*/];
  2913. }
  2914. });
  2915. }); }; };
  2916. /**
  2917. * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
  2918. * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
  2919. *
  2920. * @param app - The Firebase App.
  2921. *
  2922. * @public
  2923. */
  2924. function getAuth(app$1) {
  2925. if (app$1 === void 0) { app$1 = app.getApp(); }
  2926. var provider = app._getProvider(app$1, 'auth');
  2927. if (provider.isInitialized()) {
  2928. return provider.getImmediate();
  2929. }
  2930. var auth = phone.initializeAuth(app$1, {
  2931. popupRedirectResolver: browserPopupRedirectResolver,
  2932. persistence: [
  2933. indexedDBLocalPersistence,
  2934. browserLocalPersistence,
  2935. browserSessionPersistence
  2936. ]
  2937. });
  2938. var authTokenSyncUrl = util.getExperimentalSetting('authTokenSyncURL');
  2939. if (authTokenSyncUrl) {
  2940. var mintCookie_1 = mintCookieFactory(authTokenSyncUrl);
  2941. phone.beforeAuthStateChanged(auth, mintCookie_1, function () {
  2942. return mintCookie_1(auth.currentUser);
  2943. });
  2944. phone.onIdTokenChanged(auth, function (user) { return mintCookie_1(user); });
  2945. }
  2946. var authEmulatorHost = util.getDefaultEmulatorHost('auth');
  2947. if (authEmulatorHost) {
  2948. phone.connectAuthEmulator(auth, "http://".concat(authEmulatorHost));
  2949. }
  2950. return auth;
  2951. }
  2952. phone.registerAuth("Browser" /* ClientPlatform.BROWSER */);
  2953. /**
  2954. * @license
  2955. * Copyright 2021 Google LLC
  2956. *
  2957. * Licensed under the Apache License, Version 2.0 (the "License");
  2958. * you may not use this file except in compliance with the License.
  2959. * You may obtain a copy of the License at
  2960. *
  2961. * http://www.apache.org/licenses/LICENSE-2.0
  2962. *
  2963. * Unless required by applicable law or agreed to in writing, software
  2964. * distributed under the License is distributed on an "AS IS" BASIS,
  2965. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2966. * See the License for the specific language governing permissions and
  2967. * limitations under the License.
  2968. */
  2969. function _cordovaWindow() {
  2970. return window;
  2971. }
  2972. /**
  2973. * @license
  2974. * Copyright 2020 Google LLC
  2975. *
  2976. * Licensed under the Apache License, Version 2.0 (the "License");
  2977. * you may not use this file except in compliance with the License.
  2978. * You may obtain a copy of the License at
  2979. *
  2980. * http://www.apache.org/licenses/LICENSE-2.0
  2981. *
  2982. * Unless required by applicable law or agreed to in writing, software
  2983. * distributed under the License is distributed on an "AS IS" BASIS,
  2984. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2985. * See the License for the specific language governing permissions and
  2986. * limitations under the License.
  2987. */
  2988. /**
  2989. * How long to wait after the app comes back into focus before concluding that
  2990. * the user closed the sign in tab.
  2991. */
  2992. var REDIRECT_TIMEOUT_MS = 2000;
  2993. /**
  2994. * Generates the URL for the OAuth handler.
  2995. */
  2996. function _generateHandlerUrl(auth, event, provider) {
  2997. var _a;
  2998. return tslib.__awaiter(this, void 0, void 0, function () {
  2999. var BuildInfo, sessionDigest, additionalParams;
  3000. return tslib.__generator(this, function (_b) {
  3001. switch (_b.label) {
  3002. case 0:
  3003. BuildInfo = _cordovaWindow().BuildInfo;
  3004. phone.debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');
  3005. return [4 /*yield*/, computeSha256(event.sessionId)];
  3006. case 1:
  3007. sessionDigest = _b.sent();
  3008. additionalParams = {};
  3009. if (phone._isIOS()) {
  3010. // iOS app identifier
  3011. additionalParams['ibi'] = BuildInfo.packageName;
  3012. }
  3013. else if (phone._isAndroid()) {
  3014. // Android app identifier
  3015. additionalParams['apn'] = BuildInfo.packageName;
  3016. }
  3017. else {
  3018. phone._fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  3019. }
  3020. // Add the display name if available
  3021. if (BuildInfo.displayName) {
  3022. additionalParams['appDisplayName'] = BuildInfo.displayName;
  3023. }
  3024. // Attached the hashed session ID
  3025. additionalParams['sessionId'] = sessionDigest;
  3026. return [2 /*return*/, _getRedirectUrl(auth, provider, event.type, undefined, (_a = event.eventId) !== null && _a !== void 0 ? _a : undefined, additionalParams)];
  3027. }
  3028. });
  3029. });
  3030. }
  3031. /**
  3032. * Validates that this app is valid for this project configuration
  3033. */
  3034. function _validateOrigin(auth) {
  3035. return tslib.__awaiter(this, void 0, void 0, function () {
  3036. var BuildInfo, request;
  3037. return tslib.__generator(this, function (_a) {
  3038. switch (_a.label) {
  3039. case 0:
  3040. BuildInfo = _cordovaWindow().BuildInfo;
  3041. request = {};
  3042. if (phone._isIOS()) {
  3043. request.iosBundleId = BuildInfo.packageName;
  3044. }
  3045. else if (phone._isAndroid()) {
  3046. request.androidPackageName = BuildInfo.packageName;
  3047. }
  3048. else {
  3049. phone._fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  3050. }
  3051. // Will fail automatically if package name is not authorized
  3052. return [4 /*yield*/, _getProjectConfig(auth, request)];
  3053. case 1:
  3054. // Will fail automatically if package name is not authorized
  3055. _a.sent();
  3056. return [2 /*return*/];
  3057. }
  3058. });
  3059. });
  3060. }
  3061. function _performRedirect(handlerUrl) {
  3062. // Get the cordova plugins
  3063. var cordova = _cordovaWindow().cordova;
  3064. return new Promise(function (resolve) {
  3065. cordova.plugins.browsertab.isAvailable(function (browserTabIsAvailable) {
  3066. var iabRef = null;
  3067. if (browserTabIsAvailable) {
  3068. cordova.plugins.browsertab.openUrl(handlerUrl);
  3069. }
  3070. else {
  3071. // TODO: Return the inappbrowser ref that's returned from the open call
  3072. iabRef = cordova.InAppBrowser.open(handlerUrl, phone._isIOS7Or8() ? '_blank' : '_system', 'location=yes');
  3073. }
  3074. resolve(iabRef);
  3075. });
  3076. });
  3077. }
  3078. /**
  3079. * This function waits for app activity to be seen before resolving. It does
  3080. * this by attaching listeners to various dom events. Once the app is determined
  3081. * to be visible, this promise resolves. AFTER that resolution, the listeners
  3082. * are detached and any browser tabs left open will be closed.
  3083. */
  3084. function _waitForAppResume(auth, eventListener, iabRef) {
  3085. return tslib.__awaiter(this, void 0, void 0, function () {
  3086. var cordova, cleanup;
  3087. return tslib.__generator(this, function (_a) {
  3088. switch (_a.label) {
  3089. case 0:
  3090. cordova = _cordovaWindow().cordova;
  3091. cleanup = function () { };
  3092. _a.label = 1;
  3093. case 1:
  3094. _a.trys.push([1, , 3, 4]);
  3095. return [4 /*yield*/, new Promise(function (resolve, reject) {
  3096. var onCloseTimer = null;
  3097. // DEFINE ALL THE CALLBACKS =====
  3098. function authEventSeen() {
  3099. var _a;
  3100. // Auth event was detected. Resolve this promise and close the extra
  3101. // window if it's still open.
  3102. resolve();
  3103. var closeBrowserTab = (_a = cordova.plugins.browsertab) === null || _a === void 0 ? void 0 : _a.close;
  3104. if (typeof closeBrowserTab === 'function') {
  3105. closeBrowserTab();
  3106. }
  3107. // Close inappbrowser emebedded webview in iOS7 and 8 case if still
  3108. // open.
  3109. if (typeof (iabRef === null || iabRef === void 0 ? void 0 : iabRef.close) === 'function') {
  3110. iabRef.close();
  3111. }
  3112. }
  3113. function resumed() {
  3114. if (onCloseTimer) {
  3115. // This code already ran; do not rerun.
  3116. return;
  3117. }
  3118. onCloseTimer = window.setTimeout(function () {
  3119. // Wait two seeconds after resume then reject.
  3120. reject(phone._createError(auth, "redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */));
  3121. }, REDIRECT_TIMEOUT_MS);
  3122. }
  3123. function visibilityChanged() {
  3124. if ((document === null || document === void 0 ? void 0 : document.visibilityState) === 'visible') {
  3125. resumed();
  3126. }
  3127. }
  3128. // ATTACH ALL THE LISTENERS =====
  3129. // Listen for the auth event
  3130. eventListener.addPassiveListener(authEventSeen);
  3131. // Listen for resume and visibility events
  3132. document.addEventListener('resume', resumed, false);
  3133. if (phone._isAndroid()) {
  3134. document.addEventListener('visibilitychange', visibilityChanged, false);
  3135. }
  3136. // SETUP THE CLEANUP FUNCTION =====
  3137. cleanup = function () {
  3138. eventListener.removePassiveListener(authEventSeen);
  3139. document.removeEventListener('resume', resumed, false);
  3140. document.removeEventListener('visibilitychange', visibilityChanged, false);
  3141. if (onCloseTimer) {
  3142. window.clearTimeout(onCloseTimer);
  3143. }
  3144. };
  3145. })];
  3146. case 2:
  3147. _a.sent();
  3148. return [3 /*break*/, 4];
  3149. case 3:
  3150. cleanup();
  3151. return [7 /*endfinally*/];
  3152. case 4: return [2 /*return*/];
  3153. }
  3154. });
  3155. });
  3156. }
  3157. /**
  3158. * Checks the configuration of the Cordova environment. This has no side effect
  3159. * if the configuration is correct; otherwise it throws an error with the
  3160. * missing plugin.
  3161. */
  3162. function _checkCordovaConfiguration(auth) {
  3163. var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
  3164. var win = _cordovaWindow();
  3165. // Check all dependencies installed.
  3166. // https://github.com/nordnet/cordova-universal-links-plugin
  3167. // Note that cordova-universal-links-plugin has been abandoned.
  3168. // A fork with latest fixes is available at:
  3169. // https://www.npmjs.com/package/cordova-universal-links-plugin-fix
  3170. phone._assert(typeof ((_a = win === null || win === void 0 ? void 0 : win.universalLinks) === null || _a === void 0 ? void 0 : _a.subscribe) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  3171. missingPlugin: 'cordova-universal-links-plugin-fix'
  3172. });
  3173. // https://www.npmjs.com/package/cordova-plugin-buildinfo
  3174. phone._assert(typeof ((_b = win === null || win === void 0 ? void 0 : win.BuildInfo) === null || _b === void 0 ? void 0 : _b.packageName) !== 'undefined', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  3175. missingPlugin: 'cordova-plugin-buildInfo'
  3176. });
  3177. // https://github.com/google/cordova-plugin-browsertab
  3178. phone._assert(typeof ((_e = (_d = (_c = win === null || win === void 0 ? void 0 : win.cordova) === null || _c === void 0 ? void 0 : _c.plugins) === null || _d === void 0 ? void 0 : _d.browsertab) === null || _e === void 0 ? void 0 : _e.openUrl) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  3179. missingPlugin: 'cordova-plugin-browsertab'
  3180. });
  3181. phone._assert(typeof ((_h = (_g = (_f = win === null || win === void 0 ? void 0 : win.cordova) === null || _f === void 0 ? void 0 : _f.plugins) === null || _g === void 0 ? void 0 : _g.browsertab) === null || _h === void 0 ? void 0 : _h.isAvailable) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  3182. missingPlugin: 'cordova-plugin-browsertab'
  3183. });
  3184. // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/
  3185. phone._assert(typeof ((_k = (_j = win === null || win === void 0 ? void 0 : win.cordova) === null || _j === void 0 ? void 0 : _j.InAppBrowser) === null || _k === void 0 ? void 0 : _k.open) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  3186. missingPlugin: 'cordova-plugin-inappbrowser'
  3187. });
  3188. }
  3189. /**
  3190. * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only
  3191. * available in "secure" contexts, which covers Cordova (which is served on a file
  3192. * protocol).
  3193. */
  3194. function computeSha256(sessionId) {
  3195. return tslib.__awaiter(this, void 0, void 0, function () {
  3196. var bytes, buf, arr;
  3197. return tslib.__generator(this, function (_a) {
  3198. switch (_a.label) {
  3199. case 0:
  3200. bytes = stringToArrayBuffer(sessionId);
  3201. return [4 /*yield*/, crypto.subtle.digest('SHA-256', bytes)];
  3202. case 1:
  3203. buf = _a.sent();
  3204. arr = Array.from(new Uint8Array(buf));
  3205. return [2 /*return*/, arr.map(function (num) { return num.toString(16).padStart(2, '0'); }).join('')];
  3206. }
  3207. });
  3208. });
  3209. }
  3210. function stringToArrayBuffer(str) {
  3211. // This function is only meant to deal with an ASCII charset and makes
  3212. // certain simplifying assumptions.
  3213. phone.debugAssert(/[0-9a-zA-Z]+/.test(str), 'Can only convert alpha-numeric strings');
  3214. if (typeof TextEncoder !== 'undefined') {
  3215. return new TextEncoder().encode(str);
  3216. }
  3217. var buff = new ArrayBuffer(str.length);
  3218. var view = new Uint8Array(buff);
  3219. for (var i = 0; i < str.length; i++) {
  3220. view[i] = str.charCodeAt(i);
  3221. }
  3222. return view;
  3223. }
  3224. /**
  3225. * @license
  3226. * Copyright 2020 Google LLC
  3227. *
  3228. * Licensed under the Apache License, Version 2.0 (the "License");
  3229. * you may not use this file except in compliance with the License.
  3230. * You may obtain a copy of the License at
  3231. *
  3232. * http://www.apache.org/licenses/LICENSE-2.0
  3233. *
  3234. * Unless required by applicable law or agreed to in writing, software
  3235. * distributed under the License is distributed on an "AS IS" BASIS,
  3236. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3237. * See the License for the specific language governing permissions and
  3238. * limitations under the License.
  3239. */
  3240. var SESSION_ID_LENGTH = 20;
  3241. /** Custom AuthEventManager that adds passive listeners to events */
  3242. var CordovaAuthEventManager = /** @class */ (function (_super) {
  3243. tslib.__extends(CordovaAuthEventManager, _super);
  3244. function CordovaAuthEventManager() {
  3245. var _this = _super !== null && _super.apply(this, arguments) || this;
  3246. _this.passiveListeners = new Set();
  3247. _this.initPromise = new Promise(function (resolve) {
  3248. _this.resolveInialized = resolve;
  3249. });
  3250. return _this;
  3251. }
  3252. CordovaAuthEventManager.prototype.addPassiveListener = function (cb) {
  3253. this.passiveListeners.add(cb);
  3254. };
  3255. CordovaAuthEventManager.prototype.removePassiveListener = function (cb) {
  3256. this.passiveListeners.delete(cb);
  3257. };
  3258. // In a Cordova environment, this manager can live through multiple redirect
  3259. // operations
  3260. CordovaAuthEventManager.prototype.resetRedirect = function () {
  3261. this.queuedRedirectEvent = null;
  3262. this.hasHandledPotentialRedirect = false;
  3263. };
  3264. /** Override the onEvent method */
  3265. CordovaAuthEventManager.prototype.onEvent = function (event) {
  3266. this.resolveInialized();
  3267. this.passiveListeners.forEach(function (cb) { return cb(event); });
  3268. return _super.prototype.onEvent.call(this, event);
  3269. };
  3270. CordovaAuthEventManager.prototype.initialized = function () {
  3271. return tslib.__awaiter(this, void 0, void 0, function () {
  3272. return tslib.__generator(this, function (_a) {
  3273. switch (_a.label) {
  3274. case 0: return [4 /*yield*/, this.initPromise];
  3275. case 1:
  3276. _a.sent();
  3277. return [2 /*return*/];
  3278. }
  3279. });
  3280. });
  3281. };
  3282. return CordovaAuthEventManager;
  3283. }(AuthEventManager));
  3284. /**
  3285. * Generates a (partial) {@link AuthEvent}.
  3286. */
  3287. function _generateNewEvent(auth, type, eventId) {
  3288. if (eventId === void 0) { eventId = null; }
  3289. return {
  3290. type: type,
  3291. eventId: eventId,
  3292. urlResponse: null,
  3293. sessionId: generateSessionId(),
  3294. postBody: null,
  3295. tenantId: auth.tenantId,
  3296. error: phone._createError(auth, "no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */)
  3297. };
  3298. }
  3299. function _savePartialEvent(auth, event) {
  3300. return storage()._set(persistenceKey(auth), event);
  3301. }
  3302. function _getAndRemoveEvent(auth) {
  3303. return tslib.__awaiter(this, void 0, void 0, function () {
  3304. var event;
  3305. return tslib.__generator(this, function (_a) {
  3306. switch (_a.label) {
  3307. case 0: return [4 /*yield*/, storage()._get(persistenceKey(auth))];
  3308. case 1:
  3309. event = (_a.sent());
  3310. if (!event) return [3 /*break*/, 3];
  3311. return [4 /*yield*/, storage()._remove(persistenceKey(auth))];
  3312. case 2:
  3313. _a.sent();
  3314. _a.label = 3;
  3315. case 3: return [2 /*return*/, event];
  3316. }
  3317. });
  3318. });
  3319. }
  3320. function _eventFromPartialAndUrl(partialEvent, url) {
  3321. var _a, _b;
  3322. // Parse the deep link within the dynamic link URL.
  3323. var callbackUrl = _getDeepLinkFromCallback(url);
  3324. // Confirm it is actually a callback URL.
  3325. // Currently the universal link will be of this format:
  3326. // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>
  3327. // This is a fake URL but is not intended to take the user anywhere
  3328. // and just redirect to the app.
  3329. if (callbackUrl.includes('/__/auth/callback')) {
  3330. // Check if there is an error in the URL.
  3331. // This mechanism is also used to pass errors back to the app:
  3332. // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>
  3333. var params = searchParamsOrEmpty(callbackUrl);
  3334. // Get the error object corresponding to the stringified error if found.
  3335. var errorObject = params['firebaseError']
  3336. ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))
  3337. : null;
  3338. var code = (_b = (_a = errorObject === null || errorObject === void 0 ? void 0 : errorObject['code']) === null || _a === void 0 ? void 0 : _a.split('auth/')) === null || _b === void 0 ? void 0 : _b[1];
  3339. var error = code ? phone._createError(code) : null;
  3340. if (error) {
  3341. return {
  3342. type: partialEvent.type,
  3343. eventId: partialEvent.eventId,
  3344. tenantId: partialEvent.tenantId,
  3345. error: error,
  3346. urlResponse: null,
  3347. sessionId: null,
  3348. postBody: null
  3349. };
  3350. }
  3351. else {
  3352. return {
  3353. type: partialEvent.type,
  3354. eventId: partialEvent.eventId,
  3355. tenantId: partialEvent.tenantId,
  3356. sessionId: partialEvent.sessionId,
  3357. urlResponse: callbackUrl,
  3358. postBody: null
  3359. };
  3360. }
  3361. }
  3362. return null;
  3363. }
  3364. function generateSessionId() {
  3365. var chars = [];
  3366. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  3367. for (var i = 0; i < SESSION_ID_LENGTH; i++) {
  3368. var idx = Math.floor(Math.random() * allowedChars.length);
  3369. chars.push(allowedChars.charAt(idx));
  3370. }
  3371. return chars.join('');
  3372. }
  3373. function storage() {
  3374. return phone._getInstance(browserLocalPersistence);
  3375. }
  3376. function persistenceKey(auth) {
  3377. return phone._persistenceKeyName("authEvent" /* KeyName.AUTH_EVENT */, auth.config.apiKey, auth.name);
  3378. }
  3379. function parseJsonOrNull(json) {
  3380. try {
  3381. return JSON.parse(json);
  3382. }
  3383. catch (e) {
  3384. return null;
  3385. }
  3386. }
  3387. // Exported for testing
  3388. function _getDeepLinkFromCallback(url) {
  3389. var params = searchParamsOrEmpty(url);
  3390. var link = params['link'] ? decodeURIComponent(params['link']) : undefined;
  3391. // Double link case (automatic redirect)
  3392. var doubleDeepLink = searchParamsOrEmpty(link)['link'];
  3393. // iOS custom scheme links.
  3394. var iOSDeepLink = params['deep_link_id']
  3395. ? decodeURIComponent(params['deep_link_id'])
  3396. : undefined;
  3397. var iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];
  3398. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  3399. }
  3400. /**
  3401. * Optimistically tries to get search params from a string, or else returns an
  3402. * empty search params object.
  3403. */
  3404. function searchParamsOrEmpty(url) {
  3405. if (!(url === null || url === void 0 ? void 0 : url.includes('?'))) {
  3406. return {};
  3407. }
  3408. var _a = url.split('?'); _a[0]; var rest = _a.slice(1);
  3409. return util.querystringDecode(rest.join('?'));
  3410. }
  3411. /**
  3412. * @license
  3413. * Copyright 2021 Google LLC
  3414. *
  3415. * Licensed under the Apache License, Version 2.0 (the "License");
  3416. * you may not use this file except in compliance with the License.
  3417. * You may obtain a copy of the License at
  3418. *
  3419. * http://www.apache.org/licenses/LICENSE-2.0
  3420. *
  3421. * Unless required by applicable law or agreed to in writing, software
  3422. * distributed under the License is distributed on an "AS IS" BASIS,
  3423. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3424. * See the License for the specific language governing permissions and
  3425. * limitations under the License.
  3426. */
  3427. /**
  3428. * How long to wait for the initial auth event before concluding no
  3429. * redirect pending
  3430. */
  3431. var INITIAL_EVENT_TIMEOUT_MS = 500;
  3432. var CordovaPopupRedirectResolver = /** @class */ (function () {
  3433. function CordovaPopupRedirectResolver() {
  3434. this._redirectPersistence = browserSessionPersistence;
  3435. this._shouldInitProactively = true; // This is lightweight for Cordova
  3436. this.eventManagers = new Map();
  3437. this.originValidationPromises = {};
  3438. this._completeRedirectFn = _getRedirectResult;
  3439. this._overrideRedirectResult = _overrideRedirectResult;
  3440. }
  3441. CordovaPopupRedirectResolver.prototype._initialize = function (auth) {
  3442. return tslib.__awaiter(this, void 0, void 0, function () {
  3443. var key, manager;
  3444. return tslib.__generator(this, function (_a) {
  3445. key = auth._key();
  3446. manager = this.eventManagers.get(key);
  3447. if (!manager) {
  3448. manager = new CordovaAuthEventManager(auth);
  3449. this.eventManagers.set(key, manager);
  3450. this.attachCallbackListeners(auth, manager);
  3451. }
  3452. return [2 /*return*/, manager];
  3453. });
  3454. });
  3455. };
  3456. CordovaPopupRedirectResolver.prototype._openPopup = function (auth) {
  3457. phone._fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  3458. };
  3459. CordovaPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  3460. return tslib.__awaiter(this, void 0, void 0, function () {
  3461. var manager, event, url, iabRef;
  3462. return tslib.__generator(this, function (_a) {
  3463. switch (_a.label) {
  3464. case 0:
  3465. _checkCordovaConfiguration(auth);
  3466. return [4 /*yield*/, this._initialize(auth)];
  3467. case 1:
  3468. manager = _a.sent();
  3469. return [4 /*yield*/, manager.initialized()];
  3470. case 2:
  3471. _a.sent();
  3472. // Reset the persisted redirect states. This does not matter on Web where
  3473. // the redirect always blows away application state entirely. On Cordova,
  3474. // the app maintains control flow through the redirect.
  3475. manager.resetRedirect();
  3476. _clearRedirectOutcomes();
  3477. return [4 /*yield*/, this._originValidation(auth)];
  3478. case 3:
  3479. _a.sent();
  3480. event = _generateNewEvent(auth, authType, eventId);
  3481. return [4 /*yield*/, _savePartialEvent(auth, event)];
  3482. case 4:
  3483. _a.sent();
  3484. return [4 /*yield*/, _generateHandlerUrl(auth, event, provider)];
  3485. case 5:
  3486. url = _a.sent();
  3487. return [4 /*yield*/, _performRedirect(url)];
  3488. case 6:
  3489. iabRef = _a.sent();
  3490. return [2 /*return*/, _waitForAppResume(auth, manager, iabRef)];
  3491. }
  3492. });
  3493. });
  3494. };
  3495. CordovaPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (_auth, _cb) {
  3496. throw new Error('Method not implemented.');
  3497. };
  3498. CordovaPopupRedirectResolver.prototype._originValidation = function (auth) {
  3499. var key = auth._key();
  3500. if (!this.originValidationPromises[key]) {
  3501. this.originValidationPromises[key] = _validateOrigin(auth);
  3502. }
  3503. return this.originValidationPromises[key];
  3504. };
  3505. CordovaPopupRedirectResolver.prototype.attachCallbackListeners = function (auth, manager) {
  3506. var _this = this;
  3507. // Get the global plugins
  3508. var _a = _cordovaWindow(), universalLinks = _a.universalLinks, handleOpenURL = _a.handleOpenURL, BuildInfo = _a.BuildInfo;
  3509. var noEventTimeout = setTimeout(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  3510. return tslib.__generator(this, function (_a) {
  3511. switch (_a.label) {
  3512. case 0:
  3513. // We didn't see that initial event. Clear any pending object and
  3514. // dispatch no event
  3515. return [4 /*yield*/, _getAndRemoveEvent(auth)];
  3516. case 1:
  3517. // We didn't see that initial event. Clear any pending object and
  3518. // dispatch no event
  3519. _a.sent();
  3520. manager.onEvent(generateNoEvent());
  3521. return [2 /*return*/];
  3522. }
  3523. });
  3524. }); }, INITIAL_EVENT_TIMEOUT_MS);
  3525. var universalLinksCb = function (eventData) { return tslib.__awaiter(_this, void 0, void 0, function () {
  3526. var partialEvent, finalEvent;
  3527. return tslib.__generator(this, function (_a) {
  3528. switch (_a.label) {
  3529. case 0:
  3530. // We have an event so we can clear the no event timeout
  3531. clearTimeout(noEventTimeout);
  3532. return [4 /*yield*/, _getAndRemoveEvent(auth)];
  3533. case 1:
  3534. partialEvent = _a.sent();
  3535. finalEvent = null;
  3536. if (partialEvent && (eventData === null || eventData === void 0 ? void 0 : eventData['url'])) {
  3537. finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);
  3538. }
  3539. // If finalEvent is never filled, trigger with no event
  3540. manager.onEvent(finalEvent || generateNoEvent());
  3541. return [2 /*return*/];
  3542. }
  3543. });
  3544. }); };
  3545. // Universal links subscriber doesn't exist for iOS, so we need to check
  3546. if (typeof universalLinks !== 'undefined' &&
  3547. typeof universalLinks.subscribe === 'function') {
  3548. universalLinks.subscribe(null, universalLinksCb);
  3549. }
  3550. // iOS 7 or 8 custom URL schemes.
  3551. // This is also the current default behavior for iOS 9+.
  3552. // For this to work, cordova-plugin-customurlscheme needs to be installed.
  3553. // https://github.com/EddyVerbruggen/Custom-URL-scheme
  3554. // Do not overwrite the existing developer's URL handler.
  3555. var existingHandleOpenURL = handleOpenURL;
  3556. var packagePrefix = "".concat(BuildInfo.packageName.toLowerCase(), "://");
  3557. _cordovaWindow().handleOpenURL = function (url) { return tslib.__awaiter(_this, void 0, void 0, function () {
  3558. return tslib.__generator(this, function (_a) {
  3559. if (url.toLowerCase().startsWith(packagePrefix)) {
  3560. // We want this intentionally to float
  3561. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3562. universalLinksCb({ url: url });
  3563. }
  3564. // Call the developer's handler if it is present.
  3565. if (typeof existingHandleOpenURL === 'function') {
  3566. try {
  3567. existingHandleOpenURL(url);
  3568. }
  3569. catch (e) {
  3570. // This is a developer error. Don't stop the flow of the SDK.
  3571. console.error(e);
  3572. }
  3573. }
  3574. return [2 /*return*/];
  3575. });
  3576. }); };
  3577. };
  3578. return CordovaPopupRedirectResolver;
  3579. }());
  3580. /**
  3581. * An implementation of {@link PopupRedirectResolver} suitable for Cordova
  3582. * based applications.
  3583. *
  3584. * @public
  3585. */
  3586. var cordovaPopupRedirectResolver = CordovaPopupRedirectResolver;
  3587. function generateNoEvent() {
  3588. return {
  3589. type: "unknown" /* AuthEventType.UNKNOWN */,
  3590. eventId: null,
  3591. sessionId: null,
  3592. urlResponse: null,
  3593. postBody: null,
  3594. tenantId: null,
  3595. error: phone._createError("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */)
  3596. };
  3597. }
  3598. /**
  3599. * @license
  3600. * Copyright 2017 Google LLC
  3601. *
  3602. * Licensed under the Apache License, Version 2.0 (the "License");
  3603. * you may not use this file except in compliance with the License.
  3604. * You may obtain a copy of the License at
  3605. *
  3606. * http://www.apache.org/licenses/LICENSE-2.0
  3607. *
  3608. * Unless required by applicable law or agreed to in writing, software
  3609. * distributed under the License is distributed on an "AS IS" BASIS,
  3610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3611. * See the License for the specific language governing permissions and
  3612. * limitations under the License.
  3613. */
  3614. // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.
  3615. // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out
  3616. // of autogenerated documentation pages to reduce accidental misuse.
  3617. function addFrameworkForLogging(auth, framework) {
  3618. phone._castAuth(auth)._logFramework(framework);
  3619. }
  3620. exports.ActionCodeOperation = phone.ActionCodeOperation;
  3621. exports.ActionCodeURL = phone.ActionCodeURL;
  3622. exports.AuthCredential = phone.AuthCredential;
  3623. exports.AuthErrorCodes = phone.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;
  3624. exports.AuthImpl = phone.AuthImpl;
  3625. exports.EmailAuthCredential = phone.EmailAuthCredential;
  3626. exports.EmailAuthProvider = phone.EmailAuthProvider;
  3627. exports.FacebookAuthProvider = phone.FacebookAuthProvider;
  3628. exports.FactorId = phone.FactorId;
  3629. exports.FetchProvider = phone.FetchProvider;
  3630. exports.GithubAuthProvider = phone.GithubAuthProvider;
  3631. exports.GoogleAuthProvider = phone.GoogleAuthProvider;
  3632. exports.OAuthCredential = phone.OAuthCredential;
  3633. exports.OAuthProvider = phone.OAuthProvider;
  3634. exports.OperationType = phone.OperationType;
  3635. exports.PhoneAuthCredential = phone.PhoneAuthCredential;
  3636. exports.PhoneAuthProvider = phone.PhoneAuthProvider;
  3637. exports.PhoneMultiFactorGenerator = phone.PhoneMultiFactorGenerator;
  3638. exports.ProviderId = phone.ProviderId;
  3639. exports.RecaptchaVerifier = phone.RecaptchaVerifier;
  3640. exports.SAMLAuthCredential = phone.SAMLAuthCredential;
  3641. exports.SAMLAuthProvider = phone.SAMLAuthProvider;
  3642. exports.SignInMethod = phone.SignInMethod;
  3643. exports.TwitterAuthProvider = phone.TwitterAuthProvider;
  3644. exports.UserImpl = phone.UserImpl;
  3645. exports._assert = phone._assert;
  3646. exports._castAuth = phone._castAuth;
  3647. exports._fail = phone._fail;
  3648. exports._getClientVersion = phone._getClientVersion;
  3649. exports._getInstance = phone._getInstance;
  3650. exports._persistenceKeyName = phone._persistenceKeyName;
  3651. exports.applyActionCode = phone.applyActionCode;
  3652. exports.beforeAuthStateChanged = phone.beforeAuthStateChanged;
  3653. exports.checkActionCode = phone.checkActionCode;
  3654. exports.confirmPasswordReset = phone.confirmPasswordReset;
  3655. exports.connectAuthEmulator = phone.connectAuthEmulator;
  3656. exports.createUserWithEmailAndPassword = phone.createUserWithEmailAndPassword;
  3657. exports.debugErrorMap = phone.debugErrorMap;
  3658. exports.deleteUser = phone.deleteUser;
  3659. exports.fetchSignInMethodsForEmail = phone.fetchSignInMethodsForEmail;
  3660. exports.getAdditionalUserInfo = phone.getAdditionalUserInfo;
  3661. exports.getIdToken = phone.getIdToken;
  3662. exports.getIdTokenResult = phone.getIdTokenResult;
  3663. exports.getMultiFactorResolver = phone.getMultiFactorResolver;
  3664. exports.inMemoryPersistence = phone.inMemoryPersistence;
  3665. exports.initializeAuth = phone.initializeAuth;
  3666. exports.isSignInWithEmailLink = phone.isSignInWithEmailLink;
  3667. exports.linkWithCredential = phone.linkWithCredential;
  3668. exports.linkWithPhoneNumber = phone.linkWithPhoneNumber;
  3669. exports.multiFactor = phone.multiFactor;
  3670. exports.onAuthStateChanged = phone.onAuthStateChanged;
  3671. exports.onIdTokenChanged = phone.onIdTokenChanged;
  3672. exports.parseActionCodeURL = phone.parseActionCodeURL;
  3673. exports.prodErrorMap = phone.prodErrorMap;
  3674. exports.reauthenticateWithCredential = phone.reauthenticateWithCredential;
  3675. exports.reauthenticateWithPhoneNumber = phone.reauthenticateWithPhoneNumber;
  3676. exports.reload = phone.reload;
  3677. exports.sendEmailVerification = phone.sendEmailVerification;
  3678. exports.sendPasswordResetEmail = phone.sendPasswordResetEmail;
  3679. exports.sendSignInLinkToEmail = phone.sendSignInLinkToEmail;
  3680. exports.setPersistence = phone.setPersistence;
  3681. exports.signInAnonymously = phone.signInAnonymously;
  3682. exports.signInWithCredential = phone.signInWithCredential;
  3683. exports.signInWithCustomToken = phone.signInWithCustomToken;
  3684. exports.signInWithEmailAndPassword = phone.signInWithEmailAndPassword;
  3685. exports.signInWithEmailLink = phone.signInWithEmailLink;
  3686. exports.signInWithPhoneNumber = phone.signInWithPhoneNumber;
  3687. exports.signOut = phone.signOut;
  3688. exports.unlink = phone.unlink;
  3689. exports.updateCurrentUser = phone.updateCurrentUser;
  3690. exports.updateEmail = phone.updateEmail;
  3691. exports.updatePassword = phone.updatePassword;
  3692. exports.updatePhoneNumber = phone.updatePhoneNumber;
  3693. exports.updateProfile = phone.updateProfile;
  3694. exports.useDeviceLanguage = phone.useDeviceLanguage;
  3695. exports.verifyBeforeUpdateEmail = phone.verifyBeforeUpdateEmail;
  3696. exports.verifyPasswordResetCode = phone.verifyPasswordResetCode;
  3697. exports.AuthPopup = AuthPopup;
  3698. exports._generateEventId = _generateEventId;
  3699. exports._getRedirectResult = _getRedirectResult;
  3700. exports._overrideRedirectResult = _overrideRedirectResult;
  3701. exports.addFrameworkForLogging = addFrameworkForLogging;
  3702. exports.browserLocalPersistence = browserLocalPersistence;
  3703. exports.browserPopupRedirectResolver = browserPopupRedirectResolver;
  3704. exports.browserSessionPersistence = browserSessionPersistence;
  3705. exports.cordovaPopupRedirectResolver = cordovaPopupRedirectResolver;
  3706. exports.getAuth = getAuth;
  3707. exports.getRedirectResult = getRedirectResult;
  3708. exports.indexedDBLocalPersistence = indexedDBLocalPersistence;
  3709. exports.linkWithPopup = linkWithPopup;
  3710. exports.linkWithRedirect = linkWithRedirect;
  3711. exports.reauthenticateWithPopup = reauthenticateWithPopup;
  3712. exports.reauthenticateWithRedirect = reauthenticateWithRedirect;
  3713. exports.signInWithPopup = signInWithPopup;
  3714. exports.signInWithRedirect = signInWithRedirect;
  3715. //# sourceMappingURL=internal.js.map