No Description
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.

internal.js 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. import { ap as _isIOS, aq as _isAndroid, ar as _fail, as as _getRedirectUrl, at as debugAssert, au as _getProjectConfig, av as _isIOS7Or8, aw as _assert, ax as _createError, ay as AuthEventManager, az as _getInstance, b as browserLocalPersistence, aA as _persistenceKeyName, aB as _clearRedirectOutcomes, a as browserSessionPersistence, aC as _getRedirectResult, aD as _overrideRedirectResult, aE as _castAuth } from './index-624a9c08.js';
  2. export { A as ActionCodeOperation, ad as ActionCodeURL, H as AuthCredential, D as AuthErrorCodes, aG as AuthImpl, aJ as AuthPopup, I as EmailAuthCredential, M as EmailAuthProvider, N as FacebookAuthProvider, F as FactorId, aK as FetchProvider, T as GithubAuthProvider, Q as GoogleAuthProvider, J as OAuthCredential, U as OAuthProvider, O as OperationType, K as PhoneAuthCredential, P as PhoneAuthProvider, m as PhoneMultiFactorGenerator, o as ProviderId, R as RecaptchaVerifier, aL as SAMLAuthCredential, V as SAMLAuthProvider, S as SignInMethod, W as TwitterAuthProvider, aF as UserImpl, aw as _assert, aE as _castAuth, ar as _fail, aI as _generateEventId, aH as _getClientVersion, az as _getInstance, aC as _getRedirectResult, aD as _overrideRedirectResult, aA as _persistenceKeyName, a2 as applyActionCode, t as beforeAuthStateChanged, b as browserLocalPersistence, k as browserPopupRedirectResolver, a as browserSessionPersistence, a3 as checkActionCode, a1 as confirmPasswordReset, G as connectAuthEmulator, a5 as createUserWithEmailAndPassword, B as debugErrorMap, z as deleteUser, aa as fetchSignInMethodsForEmail, al as getAdditionalUserInfo, n as getAuth, ai as getIdToken, aj as getIdTokenResult, an as getMultiFactorResolver, j as getRedirectResult, L as inMemoryPersistence, i as indexedDBLocalPersistence, E as initializeAuth, a8 as isSignInWithEmailLink, Z as linkWithCredential, l as linkWithPhoneNumber, d as linkWithPopup, g as linkWithRedirect, ao as multiFactor, v as onAuthStateChanged, q as onIdTokenChanged, ae as parseActionCodeURL, C as prodErrorMap, _ as reauthenticateWithCredential, r as reauthenticateWithPhoneNumber, e as reauthenticateWithPopup, h as reauthenticateWithRedirect, am as reload, ab as sendEmailVerification, a0 as sendPasswordResetEmail, a7 as sendSignInLinkToEmail, p as setPersistence, X as signInAnonymously, Y as signInWithCredential, $ as signInWithCustomToken, a6 as signInWithEmailAndPassword, a9 as signInWithEmailLink, s as signInWithPhoneNumber, c as signInWithPopup, f as signInWithRedirect, y as signOut, ak as unlink, x as updateCurrentUser, ag as updateEmail, ah as updatePassword, u as updatePhoneNumber, af as updateProfile, w as useDeviceLanguage, ac as verifyBeforeUpdateEmail, a4 as verifyPasswordResetCode } from './index-624a9c08.js';
  3. import { __awaiter, __generator, __extends } from 'tslib';
  4. import { querystringDecode } from '@firebase/util';
  5. import '@firebase/app';
  6. import '@firebase/logger';
  7. import '@firebase/component';
  8. /**
  9. * @license
  10. * Copyright 2021 Google LLC
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. function _cordovaWindow() {
  25. return window;
  26. }
  27. /**
  28. * @license
  29. * Copyright 2020 Google LLC
  30. *
  31. * Licensed under the Apache License, Version 2.0 (the "License");
  32. * you may not use this file except in compliance with the License.
  33. * You may obtain a copy of the License at
  34. *
  35. * http://www.apache.org/licenses/LICENSE-2.0
  36. *
  37. * Unless required by applicable law or agreed to in writing, software
  38. * distributed under the License is distributed on an "AS IS" BASIS,
  39. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. * See the License for the specific language governing permissions and
  41. * limitations under the License.
  42. */
  43. /**
  44. * How long to wait after the app comes back into focus before concluding that
  45. * the user closed the sign in tab.
  46. */
  47. var REDIRECT_TIMEOUT_MS = 2000;
  48. /**
  49. * Generates the URL for the OAuth handler.
  50. */
  51. function _generateHandlerUrl(auth, event, provider) {
  52. var _a;
  53. return __awaiter(this, void 0, void 0, function () {
  54. var BuildInfo, sessionDigest, additionalParams;
  55. return __generator(this, function (_b) {
  56. switch (_b.label) {
  57. case 0:
  58. BuildInfo = _cordovaWindow().BuildInfo;
  59. debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');
  60. return [4 /*yield*/, computeSha256(event.sessionId)];
  61. case 1:
  62. sessionDigest = _b.sent();
  63. additionalParams = {};
  64. if (_isIOS()) {
  65. // iOS app identifier
  66. additionalParams['ibi'] = BuildInfo.packageName;
  67. }
  68. else if (_isAndroid()) {
  69. // Android app identifier
  70. additionalParams['apn'] = BuildInfo.packageName;
  71. }
  72. else {
  73. _fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  74. }
  75. // Add the display name if available
  76. if (BuildInfo.displayName) {
  77. additionalParams['appDisplayName'] = BuildInfo.displayName;
  78. }
  79. // Attached the hashed session ID
  80. additionalParams['sessionId'] = sessionDigest;
  81. return [2 /*return*/, _getRedirectUrl(auth, provider, event.type, undefined, (_a = event.eventId) !== null && _a !== void 0 ? _a : undefined, additionalParams)];
  82. }
  83. });
  84. });
  85. }
  86. /**
  87. * Validates that this app is valid for this project configuration
  88. */
  89. function _validateOrigin(auth) {
  90. return __awaiter(this, void 0, void 0, function () {
  91. var BuildInfo, request;
  92. return __generator(this, function (_a) {
  93. switch (_a.label) {
  94. case 0:
  95. BuildInfo = _cordovaWindow().BuildInfo;
  96. request = {};
  97. if (_isIOS()) {
  98. request.iosBundleId = BuildInfo.packageName;
  99. }
  100. else if (_isAndroid()) {
  101. request.androidPackageName = BuildInfo.packageName;
  102. }
  103. else {
  104. _fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  105. }
  106. // Will fail automatically if package name is not authorized
  107. return [4 /*yield*/, _getProjectConfig(auth, request)];
  108. case 1:
  109. // Will fail automatically if package name is not authorized
  110. _a.sent();
  111. return [2 /*return*/];
  112. }
  113. });
  114. });
  115. }
  116. function _performRedirect(handlerUrl) {
  117. // Get the cordova plugins
  118. var cordova = _cordovaWindow().cordova;
  119. return new Promise(function (resolve) {
  120. cordova.plugins.browsertab.isAvailable(function (browserTabIsAvailable) {
  121. var iabRef = null;
  122. if (browserTabIsAvailable) {
  123. cordova.plugins.browsertab.openUrl(handlerUrl);
  124. }
  125. else {
  126. // TODO: Return the inappbrowser ref that's returned from the open call
  127. iabRef = cordova.InAppBrowser.open(handlerUrl, _isIOS7Or8() ? '_blank' : '_system', 'location=yes');
  128. }
  129. resolve(iabRef);
  130. });
  131. });
  132. }
  133. /**
  134. * This function waits for app activity to be seen before resolving. It does
  135. * this by attaching listeners to various dom events. Once the app is determined
  136. * to be visible, this promise resolves. AFTER that resolution, the listeners
  137. * are detached and any browser tabs left open will be closed.
  138. */
  139. function _waitForAppResume(auth, eventListener, iabRef) {
  140. return __awaiter(this, void 0, void 0, function () {
  141. var cordova, cleanup;
  142. return __generator(this, function (_a) {
  143. switch (_a.label) {
  144. case 0:
  145. cordova = _cordovaWindow().cordova;
  146. cleanup = function () { };
  147. _a.label = 1;
  148. case 1:
  149. _a.trys.push([1, , 3, 4]);
  150. return [4 /*yield*/, new Promise(function (resolve, reject) {
  151. var onCloseTimer = null;
  152. // DEFINE ALL THE CALLBACKS =====
  153. function authEventSeen() {
  154. var _a;
  155. // Auth event was detected. Resolve this promise and close the extra
  156. // window if it's still open.
  157. resolve();
  158. var closeBrowserTab = (_a = cordova.plugins.browsertab) === null || _a === void 0 ? void 0 : _a.close;
  159. if (typeof closeBrowserTab === 'function') {
  160. closeBrowserTab();
  161. }
  162. // Close inappbrowser emebedded webview in iOS7 and 8 case if still
  163. // open.
  164. if (typeof (iabRef === null || iabRef === void 0 ? void 0 : iabRef.close) === 'function') {
  165. iabRef.close();
  166. }
  167. }
  168. function resumed() {
  169. if (onCloseTimer) {
  170. // This code already ran; do not rerun.
  171. return;
  172. }
  173. onCloseTimer = window.setTimeout(function () {
  174. // Wait two seeconds after resume then reject.
  175. reject(_createError(auth, "redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */));
  176. }, REDIRECT_TIMEOUT_MS);
  177. }
  178. function visibilityChanged() {
  179. if ((document === null || document === void 0 ? void 0 : document.visibilityState) === 'visible') {
  180. resumed();
  181. }
  182. }
  183. // ATTACH ALL THE LISTENERS =====
  184. // Listen for the auth event
  185. eventListener.addPassiveListener(authEventSeen);
  186. // Listen for resume and visibility events
  187. document.addEventListener('resume', resumed, false);
  188. if (_isAndroid()) {
  189. document.addEventListener('visibilitychange', visibilityChanged, false);
  190. }
  191. // SETUP THE CLEANUP FUNCTION =====
  192. cleanup = function () {
  193. eventListener.removePassiveListener(authEventSeen);
  194. document.removeEventListener('resume', resumed, false);
  195. document.removeEventListener('visibilitychange', visibilityChanged, false);
  196. if (onCloseTimer) {
  197. window.clearTimeout(onCloseTimer);
  198. }
  199. };
  200. })];
  201. case 2:
  202. _a.sent();
  203. return [3 /*break*/, 4];
  204. case 3:
  205. cleanup();
  206. return [7 /*endfinally*/];
  207. case 4: return [2 /*return*/];
  208. }
  209. });
  210. });
  211. }
  212. /**
  213. * Checks the configuration of the Cordova environment. This has no side effect
  214. * if the configuration is correct; otherwise it throws an error with the
  215. * missing plugin.
  216. */
  217. function _checkCordovaConfiguration(auth) {
  218. var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
  219. var win = _cordovaWindow();
  220. // Check all dependencies installed.
  221. // https://github.com/nordnet/cordova-universal-links-plugin
  222. // Note that cordova-universal-links-plugin has been abandoned.
  223. // A fork with latest fixes is available at:
  224. // https://www.npmjs.com/package/cordova-universal-links-plugin-fix
  225. _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 */, {
  226. missingPlugin: 'cordova-universal-links-plugin-fix'
  227. });
  228. // https://www.npmjs.com/package/cordova-plugin-buildinfo
  229. _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 */, {
  230. missingPlugin: 'cordova-plugin-buildInfo'
  231. });
  232. // https://github.com/google/cordova-plugin-browsertab
  233. _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 */, {
  234. missingPlugin: 'cordova-plugin-browsertab'
  235. });
  236. _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 */, {
  237. missingPlugin: 'cordova-plugin-browsertab'
  238. });
  239. // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/
  240. _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 */, {
  241. missingPlugin: 'cordova-plugin-inappbrowser'
  242. });
  243. }
  244. /**
  245. * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only
  246. * available in "secure" contexts, which covers Cordova (which is served on a file
  247. * protocol).
  248. */
  249. function computeSha256(sessionId) {
  250. return __awaiter(this, void 0, void 0, function () {
  251. var bytes, buf, arr;
  252. return __generator(this, function (_a) {
  253. switch (_a.label) {
  254. case 0:
  255. bytes = stringToArrayBuffer(sessionId);
  256. return [4 /*yield*/, crypto.subtle.digest('SHA-256', bytes)];
  257. case 1:
  258. buf = _a.sent();
  259. arr = Array.from(new Uint8Array(buf));
  260. return [2 /*return*/, arr.map(function (num) { return num.toString(16).padStart(2, '0'); }).join('')];
  261. }
  262. });
  263. });
  264. }
  265. function stringToArrayBuffer(str) {
  266. // This function is only meant to deal with an ASCII charset and makes
  267. // certain simplifying assumptions.
  268. debugAssert(/[0-9a-zA-Z]+/.test(str), 'Can only convert alpha-numeric strings');
  269. if (typeof TextEncoder !== 'undefined') {
  270. return new TextEncoder().encode(str);
  271. }
  272. var buff = new ArrayBuffer(str.length);
  273. var view = new Uint8Array(buff);
  274. for (var i = 0; i < str.length; i++) {
  275. view[i] = str.charCodeAt(i);
  276. }
  277. return view;
  278. }
  279. /**
  280. * @license
  281. * Copyright 2020 Google LLC
  282. *
  283. * Licensed under the Apache License, Version 2.0 (the "License");
  284. * you may not use this file except in compliance with the License.
  285. * You may obtain a copy of the License at
  286. *
  287. * http://www.apache.org/licenses/LICENSE-2.0
  288. *
  289. * Unless required by applicable law or agreed to in writing, software
  290. * distributed under the License is distributed on an "AS IS" BASIS,
  291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  292. * See the License for the specific language governing permissions and
  293. * limitations under the License.
  294. */
  295. var SESSION_ID_LENGTH = 20;
  296. /** Custom AuthEventManager that adds passive listeners to events */
  297. var CordovaAuthEventManager = /** @class */ (function (_super) {
  298. __extends(CordovaAuthEventManager, _super);
  299. function CordovaAuthEventManager() {
  300. var _this = _super !== null && _super.apply(this, arguments) || this;
  301. _this.passiveListeners = new Set();
  302. _this.initPromise = new Promise(function (resolve) {
  303. _this.resolveInialized = resolve;
  304. });
  305. return _this;
  306. }
  307. CordovaAuthEventManager.prototype.addPassiveListener = function (cb) {
  308. this.passiveListeners.add(cb);
  309. };
  310. CordovaAuthEventManager.prototype.removePassiveListener = function (cb) {
  311. this.passiveListeners.delete(cb);
  312. };
  313. // In a Cordova environment, this manager can live through multiple redirect
  314. // operations
  315. CordovaAuthEventManager.prototype.resetRedirect = function () {
  316. this.queuedRedirectEvent = null;
  317. this.hasHandledPotentialRedirect = false;
  318. };
  319. /** Override the onEvent method */
  320. CordovaAuthEventManager.prototype.onEvent = function (event) {
  321. this.resolveInialized();
  322. this.passiveListeners.forEach(function (cb) { return cb(event); });
  323. return _super.prototype.onEvent.call(this, event);
  324. };
  325. CordovaAuthEventManager.prototype.initialized = function () {
  326. return __awaiter(this, void 0, void 0, function () {
  327. return __generator(this, function (_a) {
  328. switch (_a.label) {
  329. case 0: return [4 /*yield*/, this.initPromise];
  330. case 1:
  331. _a.sent();
  332. return [2 /*return*/];
  333. }
  334. });
  335. });
  336. };
  337. return CordovaAuthEventManager;
  338. }(AuthEventManager));
  339. /**
  340. * Generates a (partial) {@link AuthEvent}.
  341. */
  342. function _generateNewEvent(auth, type, eventId) {
  343. if (eventId === void 0) { eventId = null; }
  344. return {
  345. type: type,
  346. eventId: eventId,
  347. urlResponse: null,
  348. sessionId: generateSessionId(),
  349. postBody: null,
  350. tenantId: auth.tenantId,
  351. error: _createError(auth, "no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */)
  352. };
  353. }
  354. function _savePartialEvent(auth, event) {
  355. return storage()._set(persistenceKey(auth), event);
  356. }
  357. function _getAndRemoveEvent(auth) {
  358. return __awaiter(this, void 0, void 0, function () {
  359. var event;
  360. return __generator(this, function (_a) {
  361. switch (_a.label) {
  362. case 0: return [4 /*yield*/, storage()._get(persistenceKey(auth))];
  363. case 1:
  364. event = (_a.sent());
  365. if (!event) return [3 /*break*/, 3];
  366. return [4 /*yield*/, storage()._remove(persistenceKey(auth))];
  367. case 2:
  368. _a.sent();
  369. _a.label = 3;
  370. case 3: return [2 /*return*/, event];
  371. }
  372. });
  373. });
  374. }
  375. function _eventFromPartialAndUrl(partialEvent, url) {
  376. var _a, _b;
  377. // Parse the deep link within the dynamic link URL.
  378. var callbackUrl = _getDeepLinkFromCallback(url);
  379. // Confirm it is actually a callback URL.
  380. // Currently the universal link will be of this format:
  381. // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>
  382. // This is a fake URL but is not intended to take the user anywhere
  383. // and just redirect to the app.
  384. if (callbackUrl.includes('/__/auth/callback')) {
  385. // Check if there is an error in the URL.
  386. // This mechanism is also used to pass errors back to the app:
  387. // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>
  388. var params = searchParamsOrEmpty(callbackUrl);
  389. // Get the error object corresponding to the stringified error if found.
  390. var errorObject = params['firebaseError']
  391. ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))
  392. : null;
  393. 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];
  394. var error = code ? _createError(code) : null;
  395. if (error) {
  396. return {
  397. type: partialEvent.type,
  398. eventId: partialEvent.eventId,
  399. tenantId: partialEvent.tenantId,
  400. error: error,
  401. urlResponse: null,
  402. sessionId: null,
  403. postBody: null
  404. };
  405. }
  406. else {
  407. return {
  408. type: partialEvent.type,
  409. eventId: partialEvent.eventId,
  410. tenantId: partialEvent.tenantId,
  411. sessionId: partialEvent.sessionId,
  412. urlResponse: callbackUrl,
  413. postBody: null
  414. };
  415. }
  416. }
  417. return null;
  418. }
  419. function generateSessionId() {
  420. var chars = [];
  421. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  422. for (var i = 0; i < SESSION_ID_LENGTH; i++) {
  423. var idx = Math.floor(Math.random() * allowedChars.length);
  424. chars.push(allowedChars.charAt(idx));
  425. }
  426. return chars.join('');
  427. }
  428. function storage() {
  429. return _getInstance(browserLocalPersistence);
  430. }
  431. function persistenceKey(auth) {
  432. return _persistenceKeyName("authEvent" /* KeyName.AUTH_EVENT */, auth.config.apiKey, auth.name);
  433. }
  434. function parseJsonOrNull(json) {
  435. try {
  436. return JSON.parse(json);
  437. }
  438. catch (e) {
  439. return null;
  440. }
  441. }
  442. // Exported for testing
  443. function _getDeepLinkFromCallback(url) {
  444. var params = searchParamsOrEmpty(url);
  445. var link = params['link'] ? decodeURIComponent(params['link']) : undefined;
  446. // Double link case (automatic redirect)
  447. var doubleDeepLink = searchParamsOrEmpty(link)['link'];
  448. // iOS custom scheme links.
  449. var iOSDeepLink = params['deep_link_id']
  450. ? decodeURIComponent(params['deep_link_id'])
  451. : undefined;
  452. var iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];
  453. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  454. }
  455. /**
  456. * Optimistically tries to get search params from a string, or else returns an
  457. * empty search params object.
  458. */
  459. function searchParamsOrEmpty(url) {
  460. if (!(url === null || url === void 0 ? void 0 : url.includes('?'))) {
  461. return {};
  462. }
  463. var _a = url.split('?'); _a[0]; var rest = _a.slice(1);
  464. return querystringDecode(rest.join('?'));
  465. }
  466. /**
  467. * @license
  468. * Copyright 2021 Google LLC
  469. *
  470. * Licensed under the Apache License, Version 2.0 (the "License");
  471. * you may not use this file except in compliance with the License.
  472. * You may obtain a copy of the License at
  473. *
  474. * http://www.apache.org/licenses/LICENSE-2.0
  475. *
  476. * Unless required by applicable law or agreed to in writing, software
  477. * distributed under the License is distributed on an "AS IS" BASIS,
  478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  479. * See the License for the specific language governing permissions and
  480. * limitations under the License.
  481. */
  482. /**
  483. * How long to wait for the initial auth event before concluding no
  484. * redirect pending
  485. */
  486. var INITIAL_EVENT_TIMEOUT_MS = 500;
  487. var CordovaPopupRedirectResolver = /** @class */ (function () {
  488. function CordovaPopupRedirectResolver() {
  489. this._redirectPersistence = browserSessionPersistence;
  490. this._shouldInitProactively = true; // This is lightweight for Cordova
  491. this.eventManagers = new Map();
  492. this.originValidationPromises = {};
  493. this._completeRedirectFn = _getRedirectResult;
  494. this._overrideRedirectResult = _overrideRedirectResult;
  495. }
  496. CordovaPopupRedirectResolver.prototype._initialize = function (auth) {
  497. return __awaiter(this, void 0, void 0, function () {
  498. var key, manager;
  499. return __generator(this, function (_a) {
  500. key = auth._key();
  501. manager = this.eventManagers.get(key);
  502. if (!manager) {
  503. manager = new CordovaAuthEventManager(auth);
  504. this.eventManagers.set(key, manager);
  505. this.attachCallbackListeners(auth, manager);
  506. }
  507. return [2 /*return*/, manager];
  508. });
  509. });
  510. };
  511. CordovaPopupRedirectResolver.prototype._openPopup = function (auth) {
  512. _fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  513. };
  514. CordovaPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  515. return __awaiter(this, void 0, void 0, function () {
  516. var manager, event, url, iabRef;
  517. return __generator(this, function (_a) {
  518. switch (_a.label) {
  519. case 0:
  520. _checkCordovaConfiguration(auth);
  521. return [4 /*yield*/, this._initialize(auth)];
  522. case 1:
  523. manager = _a.sent();
  524. return [4 /*yield*/, manager.initialized()];
  525. case 2:
  526. _a.sent();
  527. // Reset the persisted redirect states. This does not matter on Web where
  528. // the redirect always blows away application state entirely. On Cordova,
  529. // the app maintains control flow through the redirect.
  530. manager.resetRedirect();
  531. _clearRedirectOutcomes();
  532. return [4 /*yield*/, this._originValidation(auth)];
  533. case 3:
  534. _a.sent();
  535. event = _generateNewEvent(auth, authType, eventId);
  536. return [4 /*yield*/, _savePartialEvent(auth, event)];
  537. case 4:
  538. _a.sent();
  539. return [4 /*yield*/, _generateHandlerUrl(auth, event, provider)];
  540. case 5:
  541. url = _a.sent();
  542. return [4 /*yield*/, _performRedirect(url)];
  543. case 6:
  544. iabRef = _a.sent();
  545. return [2 /*return*/, _waitForAppResume(auth, manager, iabRef)];
  546. }
  547. });
  548. });
  549. };
  550. CordovaPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (_auth, _cb) {
  551. throw new Error('Method not implemented.');
  552. };
  553. CordovaPopupRedirectResolver.prototype._originValidation = function (auth) {
  554. var key = auth._key();
  555. if (!this.originValidationPromises[key]) {
  556. this.originValidationPromises[key] = _validateOrigin(auth);
  557. }
  558. return this.originValidationPromises[key];
  559. };
  560. CordovaPopupRedirectResolver.prototype.attachCallbackListeners = function (auth, manager) {
  561. var _this = this;
  562. // Get the global plugins
  563. var _a = _cordovaWindow(), universalLinks = _a.universalLinks, handleOpenURL = _a.handleOpenURL, BuildInfo = _a.BuildInfo;
  564. var noEventTimeout = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
  565. return __generator(this, function (_a) {
  566. switch (_a.label) {
  567. case 0:
  568. // We didn't see that initial event. Clear any pending object and
  569. // dispatch no event
  570. return [4 /*yield*/, _getAndRemoveEvent(auth)];
  571. case 1:
  572. // We didn't see that initial event. Clear any pending object and
  573. // dispatch no event
  574. _a.sent();
  575. manager.onEvent(generateNoEvent());
  576. return [2 /*return*/];
  577. }
  578. });
  579. }); }, INITIAL_EVENT_TIMEOUT_MS);
  580. var universalLinksCb = function (eventData) { return __awaiter(_this, void 0, void 0, function () {
  581. var partialEvent, finalEvent;
  582. return __generator(this, function (_a) {
  583. switch (_a.label) {
  584. case 0:
  585. // We have an event so we can clear the no event timeout
  586. clearTimeout(noEventTimeout);
  587. return [4 /*yield*/, _getAndRemoveEvent(auth)];
  588. case 1:
  589. partialEvent = _a.sent();
  590. finalEvent = null;
  591. if (partialEvent && (eventData === null || eventData === void 0 ? void 0 : eventData['url'])) {
  592. finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);
  593. }
  594. // If finalEvent is never filled, trigger with no event
  595. manager.onEvent(finalEvent || generateNoEvent());
  596. return [2 /*return*/];
  597. }
  598. });
  599. }); };
  600. // Universal links subscriber doesn't exist for iOS, so we need to check
  601. if (typeof universalLinks !== 'undefined' &&
  602. typeof universalLinks.subscribe === 'function') {
  603. universalLinks.subscribe(null, universalLinksCb);
  604. }
  605. // iOS 7 or 8 custom URL schemes.
  606. // This is also the current default behavior for iOS 9+.
  607. // For this to work, cordova-plugin-customurlscheme needs to be installed.
  608. // https://github.com/EddyVerbruggen/Custom-URL-scheme
  609. // Do not overwrite the existing developer's URL handler.
  610. var existingHandleOpenURL = handleOpenURL;
  611. var packagePrefix = "".concat(BuildInfo.packageName.toLowerCase(), "://");
  612. _cordovaWindow().handleOpenURL = function (url) { return __awaiter(_this, void 0, void 0, function () {
  613. return __generator(this, function (_a) {
  614. if (url.toLowerCase().startsWith(packagePrefix)) {
  615. // We want this intentionally to float
  616. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  617. universalLinksCb({ url: url });
  618. }
  619. // Call the developer's handler if it is present.
  620. if (typeof existingHandleOpenURL === 'function') {
  621. try {
  622. existingHandleOpenURL(url);
  623. }
  624. catch (e) {
  625. // This is a developer error. Don't stop the flow of the SDK.
  626. console.error(e);
  627. }
  628. }
  629. return [2 /*return*/];
  630. });
  631. }); };
  632. };
  633. return CordovaPopupRedirectResolver;
  634. }());
  635. /**
  636. * An implementation of {@link PopupRedirectResolver} suitable for Cordova
  637. * based applications.
  638. *
  639. * @public
  640. */
  641. var cordovaPopupRedirectResolver = CordovaPopupRedirectResolver;
  642. function generateNoEvent() {
  643. return {
  644. type: "unknown" /* AuthEventType.UNKNOWN */,
  645. eventId: null,
  646. sessionId: null,
  647. urlResponse: null,
  648. postBody: null,
  649. tenantId: null,
  650. error: _createError("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */)
  651. };
  652. }
  653. /**
  654. * @license
  655. * Copyright 2017 Google LLC
  656. *
  657. * Licensed under the Apache License, Version 2.0 (the "License");
  658. * you may not use this file except in compliance with the License.
  659. * You may obtain a copy of the License at
  660. *
  661. * http://www.apache.org/licenses/LICENSE-2.0
  662. *
  663. * Unless required by applicable law or agreed to in writing, software
  664. * distributed under the License is distributed on an "AS IS" BASIS,
  665. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  666. * See the License for the specific language governing permissions and
  667. * limitations under the License.
  668. */
  669. // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.
  670. // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out
  671. // of autogenerated documentation pages to reduce accidental misuse.
  672. function addFrameworkForLogging(auth, framework) {
  673. _castAuth(auth)._logFramework(framework);
  674. }
  675. export { addFrameworkForLogging, cordovaPopupRedirectResolver };
  676. //# sourceMappingURL=internal.js.map