UNPKG

489 kBJavaScriptView Raw
1import { __spreadArray, __assign, __awaiter, __generator, __rest, __extends } from 'tslib';
2import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, isIE, getUA, createSubscribe, querystringDecode, extractQuerystring, isEmpty } from '@firebase/util';
3import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
4import { Logger, LogLevel } from '@firebase/logger';
5import { Component } from '@firebase/component';
6
7/**
8 * @license
9 * Copyright 2021 Google LLC
10 *
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
14 *
15 * http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
22 */
23/**
24 * An enum of factors that may be used for multifactor authentication.
25 *
26 * @public
27 */
28var FactorId = {
29 /** Phone as second factor */
30 PHONE: 'phone'
31};
32/**
33 * Enumeration of supported providers.
34 *
35 * @public
36 */
37var ProviderId = {
38 /** Facebook provider ID */
39 FACEBOOK: 'facebook.com',
40 /** GitHub provider ID */
41 GITHUB: 'github.com',
42 /** Google provider ID */
43 GOOGLE: 'google.com',
44 /** Password provider */
45 PASSWORD: 'password',
46 /** Phone provider */
47 PHONE: 'phone',
48 /** Twitter provider ID */
49 TWITTER: 'twitter.com'
50};
51/**
52 * Enumeration of supported sign-in methods.
53 *
54 * @public
55 */
56var SignInMethod = {
57 /** Email link sign in method */
58 EMAIL_LINK: 'emailLink',
59 /** Email/password sign in method */
60 EMAIL_PASSWORD: 'password',
61 /** Facebook sign in method */
62 FACEBOOK: 'facebook.com',
63 /** GitHub sign in method */
64 GITHUB: 'github.com',
65 /** Google sign in method */
66 GOOGLE: 'google.com',
67 /** Phone sign in method */
68 PHONE: 'phone',
69 /** Twitter sign in method */
70 TWITTER: 'twitter.com'
71};
72/**
73 * Enumeration of supported operation types.
74 *
75 * @public
76 */
77var OperationType = {
78 /** Operation involving linking an additional provider to an already signed-in user. */
79 LINK: 'link',
80 /** Operation involving using a provider to reauthenticate an already signed-in user. */
81 REAUTHENTICATE: 'reauthenticate',
82 /** Operation involving signing in a user. */
83 SIGN_IN: 'signIn'
84};
85/**
86 * An enumeration of the possible email action types.
87 *
88 * @public
89 */
90var ActionCodeOperation = {
91 /** The email link sign-in action. */
92 EMAIL_SIGNIN: 'EMAIL_SIGNIN',
93 /** The password reset action. */
94 PASSWORD_RESET: 'PASSWORD_RESET',
95 /** The email revocation action. */
96 RECOVER_EMAIL: 'RECOVER_EMAIL',
97 /** The revert second factor addition email action. */
98 REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
99 /** The revert second factor addition email action. */
100 VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
101 /** The email verification action. */
102 VERIFY_EMAIL: 'VERIFY_EMAIL'
103};
104
105/**
106 * @license
107 * Copyright 2020 Google LLC
108 *
109 * Licensed under the Apache License, Version 2.0 (the "License");
110 * you may not use this file except in compliance with the License.
111 * You may obtain a copy of the License at
112 *
113 * http://www.apache.org/licenses/LICENSE-2.0
114 *
115 * Unless required by applicable law or agreed to in writing, software
116 * distributed under the License is distributed on an "AS IS" BASIS,
117 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
118 * See the License for the specific language governing permissions and
119 * limitations under the License.
120 */
121function _debugErrorMap() {
122 var _a;
123 return _a = {},
124 _a["admin-restricted-operation" /* ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
125 _a["argument-error" /* ARGUMENT_ERROR */] = '',
126 _a["app-not-authorized" /* APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
127 'authorized to use Firebase Authentication with the provided API key. ' +
128 'Review your key configuration in the Google API console.',
129 _a["app-not-installed" /* APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
130 'Android package name or iOS bundle ID) provided is not installed on ' +
131 'this device.',
132 _a["captcha-check-failed" /* CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
133 'already used or the domain associated with it does not match the list ' +
134 'of whitelisted domains.',
135 _a["code-expired" /* CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
136 'again.',
137 _a["cordova-not-ready" /* CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
138 _a["cors-unsupported" /* CORS_UNSUPPORTED */] = 'This browser is not supported.',
139 _a["credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
140 _a["custom-token-mismatch" /* CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
141 _a["requires-recent-login" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
142 'again before retrying this request.',
143 _a["dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
144 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
145 'starting any other Firebase SDK.',
146 _a["dynamic-link-not-activated" /* DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
147 'conditions.',
148 _a["email-change-needs-verification" /* EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
149 _a["email-already-in-use" /* EMAIL_EXISTS */] = 'The email address is already in use by another account.',
150 _a["emulator-config-failed" /* EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
151 'no longer be configured to use the emulator. Try calling ' +
152 '"connectAuthEmulator()" sooner.',
153 _a["expired-action-code" /* EXPIRED_OOB_CODE */] = 'The action code has expired.',
154 _a["cancelled-popup-request" /* EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
155 _a["internal-error" /* INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
156 _a["invalid-app-credential" /* INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
157 ' The reCAPTCHA token response is either invalid or expired.',
158 _a["invalid-app-id" /* INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
159 _a["invalid-user-token" /* INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
160 "if the user's token has been tampered with, or if the user isn't for " +
161 'the project associated with this API key.',
162 _a["invalid-auth-event" /* INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
163 _a["invalid-verification-code" /* INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
164 'invalid. Please resend the verification code sms and be sure to use the ' +
165 'verification code provided by the user.',
166 _a["invalid-continue-uri" /* INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
167 _a["invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
168 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
169 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
170 'cordova-plugin-customurlscheme.',
171 _a["invalid-custom-token" /* INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
172 _a["invalid-dynamic-link-domain" /* INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
173 _a["invalid-email" /* INVALID_EMAIL */] = 'The email address is badly formatted.',
174 _a["invalid-emulator-scheme" /* INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
175 _a["invalid-api-key" /* INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
176 _a["invalid-cert-hash" /* INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
177 _a["invalid-credential" /* INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
178 _a["invalid-message-payload" /* INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
179 'Please fix by going to the Auth email templates section in the Firebase Console.',
180 _a["invalid-multi-factor-session" /* INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
181 _a["invalid-oauth-provider" /* INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
182 'only supports OAuth providers.',
183 _a["invalid-oauth-client-id" /* INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
184 'specified API key.',
185 _a["unauthorized-domain" /* INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
186 'project. Edit the list of authorized domains from the Firebase console.',
187 _a["invalid-action-code" /* INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
188 'expired, or has already been used.',
189 _a["wrong-password" /* INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
190 _a["invalid-persistence-type" /* INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
191 _a["invalid-phone-number" /* INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
192 'phone number in a format that can be parsed into E.164 format. E.164 ' +
193 'phone numbers are written in the format [+][country code][subscriber ' +
194 'number including area code].',
195 _a["invalid-provider-id" /* INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
196 _a["invalid-recipient-email" /* INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
197 'recipient email address is invalid.',
198 _a["invalid-sender" /* INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
199 'Please fix by going to the Auth email templates section in the Firebase Console.',
200 _a["invalid-verification-id" /* INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
201 _a["invalid-tenant-id" /* INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
202 _a["login-blocked" /* LOGIN_BLOCKED */] = "Login blocked by user-provided method: {$originalMessage}",
203 _a["missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
204 _a["auth-domain-config-required" /* MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
205 'by following the instructions in the Firebase console.',
206 _a["missing-app-credential" /* MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
207 'assertion. A reCAPTCHA response token needs to be provided.',
208 _a["missing-verification-code" /* MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
209 _a["missing-continue-uri" /* MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
210 _a["missing-iframe-start" /* MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
211 _a["missing-ios-bundle-id" /* MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
212 _a["missing-or-invalid-nonce" /* MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
213 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
214 'in the ID token payload.',
215 _a["missing-multi-factor-info" /* MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
216 _a["missing-multi-factor-session" /* MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
217 _a["missing-phone-number" /* MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
218 _a["missing-verification-id" /* MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
219 _a["app-deleted" /* MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
220 _a["multi-factor-info-not-found" /* MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
221 _a["multi-factor-auth-required" /* MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
222 _a["account-exists-with-different-credential" /* NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
223 'sign-in credentials. Sign in using a provider associated with this ' +
224 'email address.',
225 _a["network-request-failed" /* NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
226 _a["no-auth-event" /* NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
227 _a["no-such-provider" /* NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
228 _a["null-user" /* NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
229 'requires a non-null user object.',
230 _a["operation-not-allowed" /* OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
231 'Enable it in the Firebase console, under the sign-in method tab of the ' +
232 'Auth section.',
233 _a["operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
234 'running on. "location.protocol" must be http, https or chrome-extension' +
235 ' and web storage must be enabled.',
236 _a["popup-blocked" /* POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
237 _a["popup-closed-by-user" /* POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
238 _a["provider-already-linked" /* PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
239 _a["quota-exceeded" /* QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
240 _a["redirect-cancelled-by-user" /* REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
241 _a["redirect-operation-pending" /* REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
242 _a["rejected-credential" /* REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
243 _a["second-factor-already-in-use" /* SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
244 _a["maximum-second-factor-count-exceeded" /* SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
245 _a["tenant-id-mismatch" /* TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
246 _a["timeout" /* TIMEOUT */] = 'The operation has timed out.',
247 _a["user-token-expired" /* TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
248 _a["too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
249 'Try again later.',
250 _a["unauthorized-continue-uri" /* UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
251 'the domain in the Firebase console.',
252 _a["unsupported-first-factor" /* UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
253 _a["unsupported-persistence-type" /* UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
254 _a["unsupported-tenant-operation" /* UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
255 _a["unverified-email" /* UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
256 _a["user-cancelled" /* USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
257 _a["user-not-found" /* USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
258 'have been deleted.',
259 _a["user-disabled" /* USER_DISABLED */] = 'The user account has been disabled by an administrator.',
260 _a["user-mismatch" /* USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
261 _a["user-signed-out" /* USER_SIGNED_OUT */] = '',
262 _a["weak-password" /* WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
263 _a["web-storage-unsupported" /* WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
264 _a["already-initialized" /* ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
265 'different options. To avoid this error, call initializeAuth() with the ' +
266 'same options as when it was originally called, or call getAuth() to return the' +
267 ' already initialized instance.',
268 _a;
269}
270function _prodErrorMap() {
271 var _a;
272 // We will include this one message in the prod error map since by the very
273 // nature of this error, developers will never be able to see the message
274 // using the debugErrorMap (which is installed during auth initialization).
275 return _a = {},
276 _a["dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
277 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
278 'starting any other Firebase SDK.',
279 _a;
280}
281/**
282 * A verbose error map with detailed descriptions for most error codes.
283 *
284 * See discussion at {@link AuthErrorMap}
285 *
286 * @public
287 */
288var debugErrorMap = _debugErrorMap;
289/**
290 * A minimal error map with all verbose error messages stripped.
291 *
292 * See discussion at {@link AuthErrorMap}
293 *
294 * @public
295 */
296var prodErrorMap = _prodErrorMap;
297var _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
298/**
299 * A map of potential `Auth` error codes, for easier comparison with errors
300 * thrown by the SDK.
301 *
302 * @remarks
303 * Note that you can't tree-shake individual keys
304 * in the map, so by using the map you might substantially increase your
305 * bundle size.
306 *
307 * @public
308 */
309var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
310 ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
311 ARGUMENT_ERROR: 'auth/argument-error',
312 APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
313 APP_NOT_INSTALLED: 'auth/app-not-installed',
314 CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
315 CODE_EXPIRED: 'auth/code-expired',
316 CORDOVA_NOT_READY: 'auth/cordova-not-ready',
317 CORS_UNSUPPORTED: 'auth/cors-unsupported',
318 CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
319 CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
320 CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
321 DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
322 DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
323 EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
324 EMAIL_EXISTS: 'auth/email-already-in-use',
325 EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
326 EXPIRED_OOB_CODE: 'auth/expired-action-code',
327 EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
328 INTERNAL_ERROR: 'auth/internal-error',
329 INVALID_API_KEY: 'auth/invalid-api-key',
330 INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
331 INVALID_APP_ID: 'auth/invalid-app-id',
332 INVALID_AUTH: 'auth/invalid-user-token',
333 INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
334 INVALID_CERT_HASH: 'auth/invalid-cert-hash',
335 INVALID_CODE: 'auth/invalid-verification-code',
336 INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
337 INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
338 INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
339 INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
340 INVALID_EMAIL: 'auth/invalid-email',
341 INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
342 INVALID_IDP_RESPONSE: 'auth/invalid-credential',
343 INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
344 INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
345 INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
346 INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
347 INVALID_OOB_CODE: 'auth/invalid-action-code',
348 INVALID_ORIGIN: 'auth/unauthorized-domain',
349 INVALID_PASSWORD: 'auth/wrong-password',
350 INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
351 INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
352 INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
353 INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
354 INVALID_SENDER: 'auth/invalid-sender',
355 INVALID_SESSION_INFO: 'auth/invalid-verification-id',
356 INVALID_TENANT_ID: 'auth/invalid-tenant-id',
357 MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
358 MFA_REQUIRED: 'auth/multi-factor-auth-required',
359 MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
360 MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
361 MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
362 MISSING_CODE: 'auth/missing-verification-code',
363 MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
364 MISSING_IFRAME_START: 'auth/missing-iframe-start',
365 MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
366 MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
367 MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
368 MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
369 MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
370 MISSING_SESSION_INFO: 'auth/missing-verification-id',
371 MODULE_DESTROYED: 'auth/app-deleted',
372 NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
373 NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
374 NULL_USER: 'auth/null-user',
375 NO_AUTH_EVENT: 'auth/no-auth-event',
376 NO_SUCH_PROVIDER: 'auth/no-such-provider',
377 OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
378 OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
379 POPUP_BLOCKED: 'auth/popup-blocked',
380 POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
381 PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
382 QUOTA_EXCEEDED: 'auth/quota-exceeded',
383 REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
384 REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
385 REJECTED_CREDENTIAL: 'auth/rejected-credential',
386 SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
387 SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
388 TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
389 TIMEOUT: 'auth/timeout',
390 TOKEN_EXPIRED: 'auth/user-token-expired',
391 TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
392 UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
393 UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
394 UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
395 UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
396 UNVERIFIED_EMAIL: 'auth/unverified-email',
397 USER_CANCELLED: 'auth/user-cancelled',
398 USER_DELETED: 'auth/user-not-found',
399 USER_DISABLED: 'auth/user-disabled',
400 USER_MISMATCH: 'auth/user-mismatch',
401 USER_SIGNED_OUT: 'auth/user-signed-out',
402 WEAK_PASSWORD: 'auth/weak-password',
403 WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
404 ALREADY_INITIALIZED: 'auth/already-initialized'
405};
406
407/**
408 * @license
409 * Copyright 2020 Google LLC
410 *
411 * Licensed under the Apache License, Version 2.0 (the "License");
412 * you may not use this file except in compliance with the License.
413 * You may obtain a copy of the License at
414 *
415 * http://www.apache.org/licenses/LICENSE-2.0
416 *
417 * Unless required by applicable law or agreed to in writing, software
418 * distributed under the License is distributed on an "AS IS" BASIS,
419 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
420 * See the License for the specific language governing permissions and
421 * limitations under the License.
422 */
423var logClient = new Logger('@firebase/auth');
424function _logError(msg) {
425 var args = [];
426 for (var _i = 1; _i < arguments.length; _i++) {
427 args[_i - 1] = arguments[_i];
428 }
429 if (logClient.logLevel <= LogLevel.ERROR) {
430 logClient.error.apply(logClient, __spreadArray(["Auth (" + SDK_VERSION + "): " + msg], args));
431 }
432}
433
434/**
435 * @license
436 * Copyright 2020 Google LLC
437 *
438 * Licensed under the Apache License, Version 2.0 (the "License");
439 * you may not use this file except in compliance with the License.
440 * You may obtain a copy of the License at
441 *
442 * http://www.apache.org/licenses/LICENSE-2.0
443 *
444 * Unless required by applicable law or agreed to in writing, software
445 * distributed under the License is distributed on an "AS IS" BASIS,
446 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
447 * See the License for the specific language governing permissions and
448 * limitations under the License.
449 */
450function _fail(authOrCode) {
451 var rest = [];
452 for (var _i = 1; _i < arguments.length; _i++) {
453 rest[_i - 1] = arguments[_i];
454 }
455 throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest));
456}
457function _createError(authOrCode) {
458 var rest = [];
459 for (var _i = 1; _i < arguments.length; _i++) {
460 rest[_i - 1] = arguments[_i];
461 }
462 return createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest));
463}
464function _errorWithCustomMessage(auth, code, message) {
465 var _a;
466 var errorMap = __assign(__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
467 var factory = new ErrorFactory('auth', 'Firebase', errorMap);
468 return factory.create(code, {
469 appName: auth.name,
470 });
471}
472function _assertInstanceOf(auth, object, instance) {
473 var constructorInstance = instance;
474 if (!(object instanceof constructorInstance)) {
475 if (constructorInstance.name !== object.constructor.name) {
476 _fail(auth, "argument-error" /* ARGUMENT_ERROR */);
477 }
478 throw _errorWithCustomMessage(auth, "argument-error" /* ARGUMENT_ERROR */, "Type of " + object.constructor.name + " does not match expected instance." +
479 "Did you pass a reference from a different Auth SDK?");
480 }
481}
482function createErrorInternal(authOrCode) {
483 var _a;
484 var rest = [];
485 for (var _i = 1; _i < arguments.length; _i++) {
486 rest[_i - 1] = arguments[_i];
487 }
488 if (typeof authOrCode !== 'string') {
489 var code = rest[0];
490 var fullParams = __spreadArray([], rest.slice(1));
491 if (fullParams[0]) {
492 fullParams[0].appName = authOrCode.name;
493 }
494 return (_a = authOrCode._errorFactory).create.apply(_a, __spreadArray([code], fullParams));
495 }
496 return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, __spreadArray([authOrCode], rest));
497}
498function _assert(assertion, authOrCode) {
499 var rest = [];
500 for (var _i = 2; _i < arguments.length; _i++) {
501 rest[_i - 2] = arguments[_i];
502 }
503 if (!assertion) {
504 throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest));
505 }
506}
507/**
508 * Unconditionally fails, throwing an internal error with the given message.
509 *
510 * @param failure type of failure encountered
511 * @throws Error
512 */
513function debugFail(failure) {
514 // Log the failure in addition to throw an exception, just in case the
515 // exception is swallowed.
516 var message = "INTERNAL ASSERTION FAILED: " + failure;
517 _logError(message);
518 // NOTE: We don't use FirebaseError here because these are internal failures
519 // that cannot be handled by the user. (Also it would create a circular
520 // dependency between the error and assert modules which doesn't work.)
521 throw new Error(message);
522}
523/**
524 * Fails if the given assertion condition is false, throwing an Error with the
525 * given message if it did.
526 *
527 * @param assertion
528 * @param message
529 */
530function debugAssert(assertion, message) {
531 if (!assertion) {
532 debugFail(message);
533 }
534}
535
536/**
537 * @license
538 * Copyright 2020 Google LLC
539 *
540 * Licensed under the Apache License, Version 2.0 (the "License");
541 * you may not use this file except in compliance with the License.
542 * You may obtain a copy of the License at
543 *
544 * http://www.apache.org/licenses/LICENSE-2.0
545 *
546 * Unless required by applicable law or agreed to in writing, software
547 * distributed under the License is distributed on an "AS IS" BASIS,
548 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
549 * See the License for the specific language governing permissions and
550 * limitations under the License.
551 */
552var instanceCache = new Map();
553function _getInstance(cls) {
554 debugAssert(cls instanceof Function, 'Expected a class definition');
555 var instance = instanceCache.get(cls);
556 if (instance) {
557 debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
558 return instance;
559 }
560 instance = new cls();
561 instanceCache.set(cls, instance);
562 return instance;
563}
564
565/**
566 * @license
567 * Copyright 2020 Google LLC
568 *
569 * Licensed under the Apache License, Version 2.0 (the "License");
570 * you may not use this file except in compliance with the License.
571 * You may obtain a copy of the License at
572 *
573 * http://www.apache.org/licenses/LICENSE-2.0
574 *
575 * Unless required by applicable law or agreed to in writing, software
576 * distributed under the License is distributed on an "AS IS" BASIS,
577 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
578 * See the License for the specific language governing permissions and
579 * limitations under the License.
580 */
581/**
582 * Initializes an {@link Auth} instance with fine-grained control over
583 * {@link Dependencies}.
584 *
585 * @remarks
586 *
587 * This function allows more control over the {@link Auth} instance than
588 * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
589 * the {@link Dependencies}. In general, `getAuth` is the easiest way to
590 * initialize Auth and works for most use cases. Use `initializeAuth` if you
591 * need control over which persistence layer is used, or to minimize bundle
592 * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
593 *
594 * For example, if your app only uses anonymous accounts and you only want
595 * accounts saved for the current session, initialize `Auth` with:
596 *
597 * ```js
598 * const auth = initializeAuth(app, {
599 * persistence: browserSessionPersistence,
600 * popupRedirectResolver: undefined,
601 * });
602 * ```
603 *
604 * @public
605 */
606function initializeAuth(app, deps) {
607 var provider = _getProvider(app, 'auth');
608 if (provider.isInitialized()) {
609 var auth_1 = provider.getImmediate();
610 var initialOptions = provider.getOptions();
611 if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
612 return auth_1;
613 }
614 else {
615 _fail(auth_1, "already-initialized" /* ALREADY_INITIALIZED */);
616 }
617 }
618 var auth = provider.initialize({ options: deps });
619 return auth;
620}
621function _initializeAuthInstance(auth, deps) {
622 var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
623 var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
624 if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
625 auth._updateErrorMap(deps.errorMap);
626 }
627 // This promise is intended to float; auth initialization happens in the
628 // background, meanwhile the auth object may be used by the app.
629 // eslint-disable-next-line @typescript-eslint/no-floating-promises
630 auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
631}
632
633/**
634 * @license
635 * Copyright 2020 Google LLC
636 *
637 * Licensed under the Apache License, Version 2.0 (the "License");
638 * you may not use this file except in compliance with the License.
639 * You may obtain a copy of the License at
640 *
641 * http://www.apache.org/licenses/LICENSE-2.0
642 *
643 * Unless required by applicable law or agreed to in writing, software
644 * distributed under the License is distributed on an "AS IS" BASIS,
645 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
646 * See the License for the specific language governing permissions and
647 * limitations under the License.
648 */
649function _getCurrentUrl() {
650 var _a;
651 return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
652}
653function _isHttpOrHttps() {
654 return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
655}
656function _getCurrentScheme() {
657 var _a;
658 return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
659}
660
661/**
662 * @license
663 * Copyright 2020 Google LLC
664 *
665 * Licensed under the Apache License, Version 2.0 (the "License");
666 * you may not use this file except in compliance with the License.
667 * You may obtain a copy of the License at
668 *
669 * http://www.apache.org/licenses/LICENSE-2.0
670 *
671 * Unless required by applicable law or agreed to in writing, software
672 * distributed under the License is distributed on an "AS IS" BASIS,
673 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
674 * See the License for the specific language governing permissions and
675 * limitations under the License.
676 */
677/**
678 * Determine whether the browser is working online
679 */
680function _isOnline() {
681 if (typeof navigator !== 'undefined' &&
682 navigator &&
683 'onLine' in navigator &&
684 typeof navigator.onLine === 'boolean' &&
685 // Apply only for traditional web apps and Chrome extensions.
686 // This is especially true for Cordova apps which have unreliable
687 // navigator.onLine behavior unless cordova-plugin-network-information is
688 // installed which overwrites the native navigator.onLine value and
689 // defines navigator.connection.
690 (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
691 return navigator.onLine;
692 }
693 // If we can't determine the state, assume it is online.
694 return true;
695}
696function _getUserLanguage() {
697 if (typeof navigator === 'undefined') {
698 return null;
699 }
700 var navigatorLanguage = navigator;
701 return (
702 // Most reliable, but only supported in Chrome/Firefox.
703 (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
704 // Supported in most browsers, but returns the language of the browser
705 // UI, not the language set in browser settings.
706 navigatorLanguage.language ||
707 // Couldn't determine language.
708 null);
709}
710
711/**
712 * @license
713 * Copyright 2020 Google LLC
714 *
715 * Licensed under the Apache License, Version 2.0 (the "License");
716 * you may not use this file except in compliance with the License.
717 * You may obtain a copy of the License at
718 *
719 * http://www.apache.org/licenses/LICENSE-2.0
720 *
721 * Unless required by applicable law or agreed to in writing, software
722 * distributed under the License is distributed on an "AS IS" BASIS,
723 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
724 * See the License for the specific language governing permissions and
725 * limitations under the License.
726 */
727/**
728 * A structure to help pick between a range of long and short delay durations
729 * depending on the current environment. In general, the long delay is used for
730 * mobile environments whereas short delays are used for desktop environments.
731 */
732var Delay = /** @class */ (function () {
733 function Delay(shortDelay, longDelay) {
734 this.shortDelay = shortDelay;
735 this.longDelay = longDelay;
736 // Internal error when improperly initialized.
737 debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
738 this.isMobile = isMobileCordova() || isReactNative();
739 }
740 Delay.prototype.get = function () {
741 if (!_isOnline()) {
742 // Pick the shorter timeout.
743 return Math.min(5000 /* OFFLINE */, this.shortDelay);
744 }
745 // If running in a mobile environment, return the long delay, otherwise
746 // return the short delay.
747 // This could be improved in the future to dynamically change based on other
748 // variables instead of just reading the current environment.
749 return this.isMobile ? this.longDelay : this.shortDelay;
750 };
751 return Delay;
752}());
753
754/**
755 * @license
756 * Copyright 2020 Google LLC
757 *
758 * Licensed under the Apache License, Version 2.0 (the "License");
759 * you may not use this file except in compliance with the License.
760 * You may obtain a copy of the License at
761 *
762 * http://www.apache.org/licenses/LICENSE-2.0
763 *
764 * Unless required by applicable law or agreed to in writing, software
765 * distributed under the License is distributed on an "AS IS" BASIS,
766 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
767 * See the License for the specific language governing permissions and
768 * limitations under the License.
769 */
770function _emulatorUrl(config, path) {
771 debugAssert(config.emulator, 'Emulator should always be set here');
772 var url = config.emulator.url;
773 if (!path) {
774 return url;
775 }
776 return "" + url + (path.startsWith('/') ? path.slice(1) : path);
777}
778
779/**
780 * @license
781 * Copyright 2020 Google LLC
782 *
783 * Licensed under the Apache License, Version 2.0 (the "License");
784 * you may not use this file except in compliance with the License.
785 * You may obtain a copy of the License at
786 *
787 * http://www.apache.org/licenses/LICENSE-2.0
788 *
789 * Unless required by applicable law or agreed to in writing, software
790 * distributed under the License is distributed on an "AS IS" BASIS,
791 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
792 * See the License for the specific language governing permissions and
793 * limitations under the License.
794 */
795var FetchProvider = /** @class */ (function () {
796 function FetchProvider() {
797 }
798 FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
799 this.fetchImpl = fetchImpl;
800 if (headersImpl) {
801 this.headersImpl = headersImpl;
802 }
803 if (responseImpl) {
804 this.responseImpl = responseImpl;
805 }
806 };
807 FetchProvider.fetch = function () {
808 if (this.fetchImpl) {
809 return this.fetchImpl;
810 }
811 if (typeof self !== 'undefined' && 'fetch' in self) {
812 return self.fetch;
813 }
814 debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
815 };
816 FetchProvider.headers = function () {
817 if (this.headersImpl) {
818 return this.headersImpl;
819 }
820 if (typeof self !== 'undefined' && 'Headers' in self) {
821 return self.Headers;
822 }
823 debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
824 };
825 FetchProvider.response = function () {
826 if (this.responseImpl) {
827 return this.responseImpl;
828 }
829 if (typeof self !== 'undefined' && 'Response' in self) {
830 return self.Response;
831 }
832 debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
833 };
834 return FetchProvider;
835}());
836
837/**
838 * @license
839 * Copyright 2020 Google LLC
840 *
841 * Licensed under the Apache License, Version 2.0 (the "License");
842 * you may not use this file except in compliance with the License.
843 * You may obtain a copy of the License at
844 *
845 * http://www.apache.org/licenses/LICENSE-2.0
846 *
847 * Unless required by applicable law or agreed to in writing, software
848 * distributed under the License is distributed on an "AS IS" BASIS,
849 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
850 * See the License for the specific language governing permissions and
851 * limitations under the License.
852 */
853var _a$1;
854/**
855 * Map from errors returned by the server to errors to developer visible errors
856 */
857var SERVER_ERROR_MAP = (_a$1 = {},
858 // Custom token errors.
859 _a$1["CREDENTIAL_MISMATCH" /* CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* CREDENTIAL_MISMATCH */,
860 // This can only happen if the SDK sends a bad request.
861 _a$1["MISSING_CUSTOM_TOKEN" /* MISSING_CUSTOM_TOKEN */] = "internal-error" /* INTERNAL_ERROR */,
862 // Create Auth URI errors.
863 _a$1["INVALID_IDENTIFIER" /* INVALID_IDENTIFIER */] = "invalid-email" /* INVALID_EMAIL */,
864 // This can only happen if the SDK sends a bad request.
865 _a$1["MISSING_CONTINUE_URI" /* MISSING_CONTINUE_URI */] = "internal-error" /* INTERNAL_ERROR */,
866 // Sign in with email and password errors (some apply to sign up too).
867 _a$1["INVALID_PASSWORD" /* INVALID_PASSWORD */] = "wrong-password" /* INVALID_PASSWORD */,
868 // This can only happen if the SDK sends a bad request.
869 _a$1["MISSING_PASSWORD" /* MISSING_PASSWORD */] = "internal-error" /* INTERNAL_ERROR */,
870 // Sign up with email and password errors.
871 _a$1["EMAIL_EXISTS" /* EMAIL_EXISTS */] = "email-already-in-use" /* EMAIL_EXISTS */,
872 _a$1["PASSWORD_LOGIN_DISABLED" /* PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* OPERATION_NOT_ALLOWED */,
873 // Verify assertion for sign in with credential errors:
874 _a$1["INVALID_IDP_RESPONSE" /* INVALID_IDP_RESPONSE */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
875 _a$1["INVALID_PENDING_TOKEN" /* INVALID_PENDING_TOKEN */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
876 _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */,
877 // This can only happen if the SDK sends a bad request.
878 _a$1["MISSING_REQ_TYPE" /* MISSING_REQ_TYPE */] = "internal-error" /* INTERNAL_ERROR */,
879 // Send Password reset email errors:
880 _a$1["EMAIL_NOT_FOUND" /* EMAIL_NOT_FOUND */] = "user-not-found" /* USER_DELETED */,
881 _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */,
882 _a$1["EXPIRED_OOB_CODE" /* EXPIRED_OOB_CODE */] = "expired-action-code" /* EXPIRED_OOB_CODE */,
883 _a$1["INVALID_OOB_CODE" /* INVALID_OOB_CODE */] = "invalid-action-code" /* INVALID_OOB_CODE */,
884 // This can only happen if the SDK sends a bad request.
885 _a$1["MISSING_OOB_CODE" /* MISSING_OOB_CODE */] = "internal-error" /* INTERNAL_ERROR */,
886 // Operations that require ID token in request:
887 _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
888 _a$1["INVALID_ID_TOKEN" /* INVALID_ID_TOKEN */] = "invalid-user-token" /* INVALID_AUTH */,
889 _a$1["TOKEN_EXPIRED" /* TOKEN_EXPIRED */] = "user-token-expired" /* TOKEN_EXPIRED */,
890 _a$1["USER_NOT_FOUND" /* USER_NOT_FOUND */] = "user-token-expired" /* TOKEN_EXPIRED */,
891 // Other errors.
892 _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */,
893 // Phone Auth related errors.
894 _a$1["INVALID_CODE" /* INVALID_CODE */] = "invalid-verification-code" /* INVALID_CODE */,
895 _a$1["INVALID_SESSION_INFO" /* INVALID_SESSION_INFO */] = "invalid-verification-id" /* INVALID_SESSION_INFO */,
896 _a$1["INVALID_TEMPORARY_PROOF" /* INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
897 _a$1["MISSING_SESSION_INFO" /* MISSING_SESSION_INFO */] = "missing-verification-id" /* MISSING_SESSION_INFO */,
898 _a$1["SESSION_EXPIRED" /* SESSION_EXPIRED */] = "code-expired" /* CODE_EXPIRED */,
899 // Other action code errors when additional settings passed.
900 // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
901 // This is OK as this error will be caught by client side validation.
902 _a$1["MISSING_ANDROID_PACKAGE_NAME" /* MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */,
903 _a$1["UNAUTHORIZED_DOMAIN" /* UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* UNAUTHORIZED_DOMAIN */,
904 // getProjectConfig errors when clientId is passed.
905 _a$1["INVALID_OAUTH_CLIENT_ID" /* INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* INVALID_OAUTH_CLIENT_ID */,
906 // User actions (sign-up or deletion) disabled errors.
907 _a$1["ADMIN_ONLY_OPERATION" /* ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* ADMIN_ONLY_OPERATION */,
908 // Multi factor related errors.
909 _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* INVALID_MFA_SESSION */,
910 _a$1["MFA_ENROLLMENT_NOT_FOUND" /* MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* MFA_INFO_NOT_FOUND */,
911 _a$1["MISSING_MFA_ENROLLMENT_ID" /* MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* MISSING_MFA_INFO */,
912 _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* MISSING_MFA_SESSION */,
913 _a$1["SECOND_FACTOR_EXISTS" /* SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* SECOND_FACTOR_ALREADY_ENROLLED */,
914 _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* SECOND_FACTOR_LIMIT_EXCEEDED */,
915 // Blocking functions related errors.
916 _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* INTERNAL_ERROR */,
917 _a$1);
918
919/**
920 * @license
921 * Copyright 2020 Google LLC
922 *
923 * Licensed under the Apache License, Version 2.0 (the "License");
924 * you may not use this file except in compliance with the License.
925 * You may obtain a copy of the License at
926 *
927 * http://www.apache.org/licenses/LICENSE-2.0
928 *
929 * Unless required by applicable law or agreed to in writing, software
930 * distributed under the License is distributed on an "AS IS" BASIS,
931 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
932 * See the License for the specific language governing permissions and
933 * limitations under the License.
934 */
935var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
936function _addTidIfNecessary(auth, request) {
937 if (auth.tenantId && !request.tenantId) {
938 return __assign(__assign({}, request), { tenantId: auth.tenantId });
939 }
940 return request;
941}
942function _performApiRequest(auth, method, path, request, customErrorMap) {
943 if (customErrorMap === void 0) { customErrorMap = {}; }
944 return __awaiter(this, void 0, void 0, function () {
945 var _this = this;
946 return __generator(this, function (_a) {
947 return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return __awaiter(_this, void 0, void 0, function () {
948 var body, params, query, headers;
949 return __generator(this, function (_a) {
950 switch (_a.label) {
951 case 0:
952 body = {};
953 params = {};
954 if (request) {
955 if (method === "GET" /* GET */) {
956 params = request;
957 }
958 else {
959 body = {
960 body: JSON.stringify(request)
961 };
962 }
963 }
964 query = querystring(__assign({ key: auth.config.apiKey }, params)).slice(1);
965 return [4 /*yield*/, auth._getAdditionalHeaders()];
966 case 1:
967 headers = _a.sent();
968 headers["Content-Type" /* CONTENT_TYPE */] = 'application/json';
969 if (auth.languageCode) {
970 headers["X-Firebase-Locale" /* X_FIREBASE_LOCALE */] = auth.languageCode;
971 }
972 return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), __assign({ method: method,
973 headers: headers, referrerPolicy: 'no-referrer' }, body))];
974 }
975 });
976 }); })];
977 });
978 });
979}
980function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
981 return __awaiter(this, void 0, void 0, function () {
982 var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
983 return __generator(this, function (_b) {
984 switch (_b.label) {
985 case 0:
986 auth._canInitEmulator = false;
987 errorMap = __assign(__assign({}, SERVER_ERROR_MAP), customErrorMap);
988 _b.label = 1;
989 case 1:
990 _b.trys.push([1, 4, , 5]);
991 networkTimeout = new NetworkTimeout(auth);
992 return [4 /*yield*/, Promise.race([
993 fetchFn(),
994 networkTimeout.promise
995 ])];
996 case 2:
997 response = _b.sent();
998 // If we've reached this point, the fetch succeeded and the networkTimeout
999 // didn't throw; clear the network timeout delay so that Node won't hang
1000 networkTimeout.clearNetworkTimeout();
1001 return [4 /*yield*/, response.json()];
1002 case 3:
1003 json = _b.sent();
1004 if ('needConfirmation' in json) {
1005 throw _makeTaggedError(auth, "account-exists-with-different-credential" /* NEED_CONFIRMATION */, json);
1006 }
1007 if (response.ok && !('errorMessage' in json)) {
1008 return [2 /*return*/, json];
1009 }
1010 else {
1011 errorMessage = response.ok ? json.errorMessage : json.error.message;
1012 _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
1013 if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* FEDERATED_USER_ID_ALREADY_LINKED */) {
1014 throw _makeTaggedError(auth, "credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */, json);
1015 }
1016 else if (serverErrorCode === "EMAIL_EXISTS" /* EMAIL_EXISTS */) {
1017 throw _makeTaggedError(auth, "email-already-in-use" /* EMAIL_EXISTS */, json);
1018 }
1019 authError = errorMap[serverErrorCode] ||
1020 serverErrorCode
1021 .toLowerCase()
1022 .replace(/[_\s]+/g, '-');
1023 if (serverErrorMessage) {
1024 throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
1025 }
1026 else {
1027 _fail(auth, authError);
1028 }
1029 }
1030 return [3 /*break*/, 5];
1031 case 4:
1032 e_1 = _b.sent();
1033 if (e_1 instanceof FirebaseError) {
1034 throw e_1;
1035 }
1036 _fail(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */);
1037 return [3 /*break*/, 5];
1038 case 5: return [2 /*return*/];
1039 }
1040 });
1041 });
1042}
1043function _performSignInRequest(auth, method, path, request, customErrorMap) {
1044 if (customErrorMap === void 0) { customErrorMap = {}; }
1045 return __awaiter(this, void 0, void 0, function () {
1046 var serverResponse;
1047 return __generator(this, function (_a) {
1048 switch (_a.label) {
1049 case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
1050 case 1:
1051 serverResponse = (_a.sent());
1052 if ('mfaPendingCredential' in serverResponse) {
1053 _fail(auth, "multi-factor-auth-required" /* MFA_REQUIRED */, {
1054 _serverResponse: serverResponse
1055 });
1056 }
1057 return [2 /*return*/, serverResponse];
1058 }
1059 });
1060 });
1061}
1062function _getFinalTarget(auth, host, path, query) {
1063 var base = "" + host + path + "?" + query;
1064 if (!auth.config.emulator) {
1065 return auth.config.apiScheme + "://" + base;
1066 }
1067 return _emulatorUrl(auth.config, base);
1068}
1069var NetworkTimeout = /** @class */ (function () {
1070 function NetworkTimeout(auth) {
1071 var _this = this;
1072 this.auth = auth;
1073 // Node timers and browser timers are fundamentally incompatible, but we
1074 // don't care about the value here
1075 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1076 this.timer = null;
1077 this.promise = new Promise(function (_, reject) {
1078 _this.timer = setTimeout(function () {
1079 return reject(_createError(_this.auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
1080 }, DEFAULT_API_TIMEOUT_MS.get());
1081 });
1082 }
1083 NetworkTimeout.prototype.clearNetworkTimeout = function () {
1084 clearTimeout(this.timer);
1085 };
1086 return NetworkTimeout;
1087}());
1088function _makeTaggedError(auth, code, response) {
1089 var errorParams = {
1090 appName: auth.name
1091 };
1092 if (response.email) {
1093 errorParams.email = response.email;
1094 }
1095 if (response.phoneNumber) {
1096 errorParams.phoneNumber = response.phoneNumber;
1097 }
1098 var error = _createError(auth, code, errorParams);
1099 // We know customData is defined on error because errorParams is defined
1100 error.customData._tokenResponse = response;
1101 return error;
1102}
1103
1104/**
1105 * @license
1106 * Copyright 2020 Google LLC
1107 *
1108 * Licensed under the Apache License, Version 2.0 (the "License");
1109 * you may not use this file except in compliance with the License.
1110 * You may obtain a copy of the License at
1111 *
1112 * http://www.apache.org/licenses/LICENSE-2.0
1113 *
1114 * Unless required by applicable law or agreed to in writing, software
1115 * distributed under the License is distributed on an "AS IS" BASIS,
1116 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1117 * See the License for the specific language governing permissions and
1118 * limitations under the License.
1119 */
1120function deleteAccount(auth, request) {
1121 return __awaiter(this, void 0, void 0, function () {
1122 return __generator(this, function (_a) {
1123 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:delete" /* DELETE_ACCOUNT */, request)];
1124 });
1125 });
1126}
1127function deleteLinkedAccounts(auth, request) {
1128 return __awaiter(this, void 0, void 0, function () {
1129 return __generator(this, function (_a) {
1130 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
1131 });
1132 });
1133}
1134function getAccountInfo(auth, request) {
1135 return __awaiter(this, void 0, void 0, function () {
1136 return __generator(this, function (_a) {
1137 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:lookup" /* GET_ACCOUNT_INFO */, request)];
1138 });
1139 });
1140}
1141
1142/**
1143 * @license
1144 * Copyright 2020 Google LLC
1145 *
1146 * Licensed under the Apache License, Version 2.0 (the "License");
1147 * you may not use this file except in compliance with the License.
1148 * You may obtain a copy of the License at
1149 *
1150 * http://www.apache.org/licenses/LICENSE-2.0
1151 *
1152 * Unless required by applicable law or agreed to in writing, software
1153 * distributed under the License is distributed on an "AS IS" BASIS,
1154 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1155 * See the License for the specific language governing permissions and
1156 * limitations under the License.
1157 */
1158function utcTimestampToDateString(utcTimestamp) {
1159 if (!utcTimestamp) {
1160 return undefined;
1161 }
1162 try {
1163 // Convert to date object.
1164 var date = new Date(Number(utcTimestamp));
1165 // Test date is valid.
1166 if (!isNaN(date.getTime())) {
1167 // Convert to UTC date string.
1168 return date.toUTCString();
1169 }
1170 }
1171 catch (e) {
1172 // Do nothing. undefined will be returned.
1173 }
1174 return undefined;
1175}
1176
1177/**
1178 * @license
1179 * Copyright 2020 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 * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
1195 *
1196 * @remarks
1197 * Returns the current token if it has not expired or if it will not expire in the next five
1198 * minutes. Otherwise, this will refresh the token and return a new one.
1199 *
1200 * @param user - The user.
1201 * @param forceRefresh - Force refresh regardless of token expiration.
1202 *
1203 * @public
1204 */
1205function getIdToken(user, forceRefresh) {
1206 if (forceRefresh === void 0) { forceRefresh = false; }
1207 return getModularInstance(user).getIdToken(forceRefresh);
1208}
1209/**
1210 * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
1211 *
1212 * @remarks
1213 * Returns the current token if it has not expired or if it will not expire in the next five
1214 * minutes. Otherwise, this will refresh the token and return a new one.
1215 *
1216 * @param user - The user.
1217 * @param forceRefresh - Force refresh regardless of token expiration.
1218 *
1219 * @public
1220 */
1221function getIdTokenResult(user, forceRefresh) {
1222 if (forceRefresh === void 0) { forceRefresh = false; }
1223 return __awaiter(this, void 0, void 0, function () {
1224 var userInternal, token, claims, firebase, signInProvider;
1225 return __generator(this, function (_a) {
1226 switch (_a.label) {
1227 case 0:
1228 userInternal = getModularInstance(user);
1229 return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
1230 case 1:
1231 token = _a.sent();
1232 claims = _parseToken(token);
1233 _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* INTERNAL_ERROR */);
1234 firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
1235 signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
1236 return [2 /*return*/, {
1237 claims: claims,
1238 token: token,
1239 authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
1240 issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
1241 expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
1242 signInProvider: signInProvider || null,
1243 signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
1244 }];
1245 }
1246 });
1247 });
1248}
1249function secondsStringToMilliseconds(seconds) {
1250 return Number(seconds) * 1000;
1251}
1252function _parseToken(token) {
1253 var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
1254 if (algorithm === undefined ||
1255 payload === undefined ||
1256 signature === undefined) {
1257 _logError('JWT malformed, contained fewer than 3 sections');
1258 return null;
1259 }
1260 try {
1261 var decoded = base64Decode(payload);
1262 if (!decoded) {
1263 _logError('Failed to decode base64 JWT payload');
1264 return null;
1265 }
1266 return JSON.parse(decoded);
1267 }
1268 catch (e) {
1269 _logError('Caught error parsing JWT payload as JSON', e);
1270 return null;
1271 }
1272}
1273/**
1274 * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
1275 */
1276function _tokenExpiresIn(token) {
1277 var parsedToken = _parseToken(token);
1278 _assert(parsedToken, "internal-error" /* INTERNAL_ERROR */);
1279 _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1280 _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1281 return Number(parsedToken.exp) - Number(parsedToken.iat);
1282}
1283
1284/**
1285 * @license
1286 * Copyright 2020 Google LLC
1287 *
1288 * Licensed under the Apache License, Version 2.0 (the "License");
1289 * you may not use this file except in compliance with the License.
1290 * You may obtain a copy of the License at
1291 *
1292 * http://www.apache.org/licenses/LICENSE-2.0
1293 *
1294 * Unless required by applicable law or agreed to in writing, software
1295 * distributed under the License is distributed on an "AS IS" BASIS,
1296 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1297 * See the License for the specific language governing permissions and
1298 * limitations under the License.
1299 */
1300function _logoutIfInvalidated(user, promise, bypassAuthState) {
1301 if (bypassAuthState === void 0) { bypassAuthState = false; }
1302 return __awaiter(this, void 0, void 0, function () {
1303 var e_1;
1304 return __generator(this, function (_a) {
1305 switch (_a.label) {
1306 case 0:
1307 if (bypassAuthState) {
1308 return [2 /*return*/, promise];
1309 }
1310 _a.label = 1;
1311 case 1:
1312 _a.trys.push([1, 3, , 6]);
1313 return [4 /*yield*/, promise];
1314 case 2: return [2 /*return*/, _a.sent()];
1315 case 3:
1316 e_1 = _a.sent();
1317 if (!(e_1 instanceof FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
1318 if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
1319 return [4 /*yield*/, user.auth.signOut()];
1320 case 4:
1321 _a.sent();
1322 _a.label = 5;
1323 case 5: throw e_1;
1324 case 6: return [2 /*return*/];
1325 }
1326 });
1327 });
1328}
1329function isUserInvalidated(_a) {
1330 var code = _a.code;
1331 return (code === "auth/" + "user-disabled" /* USER_DISABLED */ ||
1332 code === "auth/" + "user-token-expired" /* TOKEN_EXPIRED */);
1333}
1334
1335/**
1336 * @license
1337 * Copyright 2020 Google LLC
1338 *
1339 * Licensed under the Apache License, Version 2.0 (the "License");
1340 * you may not use this file except in compliance with the License.
1341 * You may obtain a copy of the License at
1342 *
1343 * http://www.apache.org/licenses/LICENSE-2.0
1344 *
1345 * Unless required by applicable law or agreed to in writing, software
1346 * distributed under the License is distributed on an "AS IS" BASIS,
1347 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1348 * See the License for the specific language governing permissions and
1349 * limitations under the License.
1350 */
1351var ProactiveRefresh = /** @class */ (function () {
1352 function ProactiveRefresh(user) {
1353 this.user = user;
1354 this.isRunning = false;
1355 // Node timers and browser timers return fundamentally different types.
1356 // We don't actually care what the value is but TS won't accept unknown and
1357 // we can't cast properly in both environments.
1358 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1359 this.timerId = null;
1360 this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;
1361 }
1362 ProactiveRefresh.prototype._start = function () {
1363 if (this.isRunning) {
1364 return;
1365 }
1366 this.isRunning = true;
1367 this.schedule();
1368 };
1369 ProactiveRefresh.prototype._stop = function () {
1370 if (!this.isRunning) {
1371 return;
1372 }
1373 this.isRunning = false;
1374 if (this.timerId !== null) {
1375 clearTimeout(this.timerId);
1376 }
1377 };
1378 ProactiveRefresh.prototype.getInterval = function (wasError) {
1379 var _a;
1380 if (wasError) {
1381 var interval = this.errorBackoff;
1382 this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* RETRY_BACKOFF_MAX */);
1383 return interval;
1384 }
1385 else {
1386 // Reset the error backoff
1387 this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;
1388 var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
1389 var interval = expTime - Date.now() - 300000 /* OFFSET */;
1390 return Math.max(0, interval);
1391 }
1392 };
1393 ProactiveRefresh.prototype.schedule = function (wasError) {
1394 var _this = this;
1395 if (wasError === void 0) { wasError = false; }
1396 if (!this.isRunning) {
1397 // Just in case...
1398 return;
1399 }
1400 var interval = this.getInterval(wasError);
1401 this.timerId = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1402 return __generator(this, function (_a) {
1403 switch (_a.label) {
1404 case 0: return [4 /*yield*/, this.iteration()];
1405 case 1:
1406 _a.sent();
1407 return [2 /*return*/];
1408 }
1409 });
1410 }); }, interval);
1411 };
1412 ProactiveRefresh.prototype.iteration = function () {
1413 return __awaiter(this, void 0, void 0, function () {
1414 var e_1;
1415 return __generator(this, function (_a) {
1416 switch (_a.label) {
1417 case 0:
1418 _a.trys.push([0, 2, , 3]);
1419 return [4 /*yield*/, this.user.getIdToken(true)];
1420 case 1:
1421 _a.sent();
1422 return [3 /*break*/, 3];
1423 case 2:
1424 e_1 = _a.sent();
1425 // Only retry on network errors
1426 if (e_1.code === "auth/" + "network-request-failed" /* NETWORK_REQUEST_FAILED */) {
1427 this.schedule(/* wasError */ true);
1428 }
1429 return [2 /*return*/];
1430 case 3:
1431 this.schedule();
1432 return [2 /*return*/];
1433 }
1434 });
1435 });
1436 };
1437 return ProactiveRefresh;
1438}());
1439
1440/**
1441 * @license
1442 * Copyright 2020 Google LLC
1443 *
1444 * Licensed under the Apache License, Version 2.0 (the "License");
1445 * you may not use this file except in compliance with the License.
1446 * You may obtain a copy of the License at
1447 *
1448 * http://www.apache.org/licenses/LICENSE-2.0
1449 *
1450 * Unless required by applicable law or agreed to in writing, software
1451 * distributed under the License is distributed on an "AS IS" BASIS,
1452 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1453 * See the License for the specific language governing permissions and
1454 * limitations under the License.
1455 */
1456var UserMetadata = /** @class */ (function () {
1457 function UserMetadata(createdAt, lastLoginAt) {
1458 this.createdAt = createdAt;
1459 this.lastLoginAt = lastLoginAt;
1460 this._initializeTime();
1461 }
1462 UserMetadata.prototype._initializeTime = function () {
1463 this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
1464 this.creationTime = utcTimestampToDateString(this.createdAt);
1465 };
1466 UserMetadata.prototype._copy = function (metadata) {
1467 this.createdAt = metadata.createdAt;
1468 this.lastLoginAt = metadata.lastLoginAt;
1469 this._initializeTime();
1470 };
1471 UserMetadata.prototype.toJSON = function () {
1472 return {
1473 createdAt: this.createdAt,
1474 lastLoginAt: this.lastLoginAt
1475 };
1476 };
1477 return UserMetadata;
1478}());
1479
1480/**
1481 * @license
1482 * Copyright 2019 Google LLC
1483 *
1484 * Licensed under the Apache License, Version 2.0 (the "License");
1485 * you may not use this file except in compliance with the License.
1486 * You may obtain a copy of the License at
1487 *
1488 * http://www.apache.org/licenses/LICENSE-2.0
1489 *
1490 * Unless required by applicable law or agreed to in writing, software
1491 * distributed under the License is distributed on an "AS IS" BASIS,
1492 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1493 * See the License for the specific language governing permissions and
1494 * limitations under the License.
1495 */
1496function _reloadWithoutSaving(user) {
1497 var _a;
1498 return __awaiter(this, void 0, void 0, function () {
1499 var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
1500 return __generator(this, function (_b) {
1501 switch (_b.label) {
1502 case 0:
1503 auth = user.auth;
1504 return [4 /*yield*/, user.getIdToken()];
1505 case 1:
1506 idToken = _b.sent();
1507 return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
1508 case 2:
1509 response = _b.sent();
1510 _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* INTERNAL_ERROR */);
1511 coreAccount = response.users[0];
1512 user._notifyReloadListener(coreAccount);
1513 newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
1514 ? extractProviderData(coreAccount.providerUserInfo)
1515 : [];
1516 providerData = mergeProviderData(user.providerData, newProviderData);
1517 oldIsAnonymous = user.isAnonymous;
1518 newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
1519 isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
1520 updates = {
1521 uid: coreAccount.localId,
1522 displayName: coreAccount.displayName || null,
1523 photoURL: coreAccount.photoUrl || null,
1524 email: coreAccount.email || null,
1525 emailVerified: coreAccount.emailVerified || false,
1526 phoneNumber: coreAccount.phoneNumber || null,
1527 tenantId: coreAccount.tenantId || null,
1528 providerData: providerData,
1529 metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
1530 isAnonymous: isAnonymous
1531 };
1532 Object.assign(user, updates);
1533 return [2 /*return*/];
1534 }
1535 });
1536 });
1537}
1538/**
1539 * Reloads user account data, if signed in.
1540 *
1541 * @param user - The user.
1542 *
1543 * @public
1544 */
1545function reload(user) {
1546 return __awaiter(this, void 0, void 0, function () {
1547 var userInternal;
1548 return __generator(this, function (_a) {
1549 switch (_a.label) {
1550 case 0:
1551 userInternal = getModularInstance(user);
1552 return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
1553 case 1:
1554 _a.sent();
1555 // Even though the current user hasn't changed, update
1556 // current user will trigger a persistence update w/ the
1557 // new info.
1558 return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
1559 case 2:
1560 // Even though the current user hasn't changed, update
1561 // current user will trigger a persistence update w/ the
1562 // new info.
1563 _a.sent();
1564 userInternal.auth._notifyListenersIfCurrent(userInternal);
1565 return [2 /*return*/];
1566 }
1567 });
1568 });
1569}
1570function mergeProviderData(original, newData) {
1571 var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
1572 return __spreadArray(__spreadArray([], deduped), newData);
1573}
1574function extractProviderData(providers) {
1575 return providers.map(function (_a) {
1576 var providerId = _a.providerId, provider = __rest(_a, ["providerId"]);
1577 return {
1578 providerId: providerId,
1579 uid: provider.rawId || '',
1580 displayName: provider.displayName || null,
1581 email: provider.email || null,
1582 phoneNumber: provider.phoneNumber || null,
1583 photoURL: provider.photoUrl || null
1584 };
1585 });
1586}
1587
1588/**
1589 * @license
1590 * Copyright 2020 Google LLC
1591 *
1592 * Licensed under the Apache License, Version 2.0 (the "License");
1593 * you may not use this file except in compliance with the License.
1594 * You may obtain a copy of the License at
1595 *
1596 * http://www.apache.org/licenses/LICENSE-2.0
1597 *
1598 * Unless required by applicable law or agreed to in writing, software
1599 * distributed under the License is distributed on an "AS IS" BASIS,
1600 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1601 * See the License for the specific language governing permissions and
1602 * limitations under the License.
1603 */
1604function requestStsToken(auth, refreshToken) {
1605 return __awaiter(this, void 0, void 0, function () {
1606 var response;
1607 var _this = this;
1608 return __generator(this, function (_a) {
1609 switch (_a.label) {
1610 case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return __awaiter(_this, void 0, void 0, function () {
1611 var body, _a, tokenApiHost, apiKey, url, headers;
1612 return __generator(this, function (_b) {
1613 switch (_b.label) {
1614 case 0:
1615 body = querystring({
1616 'grant_type': 'refresh_token',
1617 'refresh_token': refreshToken
1618 }).slice(1);
1619 _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
1620 url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* TOKEN */, "key=" + apiKey);
1621 return [4 /*yield*/, auth._getAdditionalHeaders()];
1622 case 1:
1623 headers = _b.sent();
1624 headers["Content-Type" /* CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
1625 return [2 /*return*/, FetchProvider.fetch()(url, {
1626 method: "POST" /* POST */,
1627 headers: headers,
1628 body: body
1629 })];
1630 }
1631 });
1632 }); })];
1633 case 1:
1634 response = _a.sent();
1635 // The response comes back in snake_case. Convert to camel:
1636 return [2 /*return*/, {
1637 accessToken: response.access_token,
1638 expiresIn: response.expires_in,
1639 refreshToken: response.refresh_token
1640 }];
1641 }
1642 });
1643 });
1644}
1645
1646/**
1647 * @license
1648 * Copyright 2020 Google LLC
1649 *
1650 * Licensed under the Apache License, Version 2.0 (the "License");
1651 * you may not use this file except in compliance with the License.
1652 * You may obtain a copy of the License at
1653 *
1654 * http://www.apache.org/licenses/LICENSE-2.0
1655 *
1656 * Unless required by applicable law or agreed to in writing, software
1657 * distributed under the License is distributed on an "AS IS" BASIS,
1658 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1659 * See the License for the specific language governing permissions and
1660 * limitations under the License.
1661 */
1662/**
1663 * We need to mark this class as internal explicitly to exclude it in the public typings, because
1664 * it references AuthInternal which has a circular dependency with UserInternal.
1665 *
1666 * @internal
1667 */
1668var StsTokenManager = /** @class */ (function () {
1669 function StsTokenManager() {
1670 this.refreshToken = null;
1671 this.accessToken = null;
1672 this.expirationTime = null;
1673 }
1674 Object.defineProperty(StsTokenManager.prototype, "isExpired", {
1675 get: function () {
1676 return (!this.expirationTime ||
1677 Date.now() > this.expirationTime - 30000 /* TOKEN_REFRESH */);
1678 },
1679 enumerable: false,
1680 configurable: true
1681 });
1682 StsTokenManager.prototype.updateFromServerResponse = function (response) {
1683 _assert(response.idToken, "internal-error" /* INTERNAL_ERROR */);
1684 _assert(typeof response.idToken !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1685 _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1686 var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
1687 ? Number(response.expiresIn)
1688 : _tokenExpiresIn(response.idToken);
1689 this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
1690 };
1691 StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
1692 if (forceRefresh === void 0) { forceRefresh = false; }
1693 return __awaiter(this, void 0, void 0, function () {
1694 return __generator(this, function (_a) {
1695 switch (_a.label) {
1696 case 0:
1697 _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* TOKEN_EXPIRED */);
1698 if (!forceRefresh && this.accessToken && !this.isExpired) {
1699 return [2 /*return*/, this.accessToken];
1700 }
1701 if (!this.refreshToken) return [3 /*break*/, 2];
1702 return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
1703 case 1:
1704 _a.sent();
1705 return [2 /*return*/, this.accessToken];
1706 case 2: return [2 /*return*/, null];
1707 }
1708 });
1709 });
1710 };
1711 StsTokenManager.prototype.clearRefreshToken = function () {
1712 this.refreshToken = null;
1713 };
1714 StsTokenManager.prototype.refresh = function (auth, oldToken) {
1715 return __awaiter(this, void 0, void 0, function () {
1716 var _a, accessToken, refreshToken, expiresIn;
1717 return __generator(this, function (_b) {
1718 switch (_b.label) {
1719 case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
1720 case 1:
1721 _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
1722 this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
1723 return [2 /*return*/];
1724 }
1725 });
1726 });
1727 };
1728 StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
1729 this.refreshToken = refreshToken || null;
1730 this.accessToken = accessToken || null;
1731 this.expirationTime = Date.now() + expiresInSec * 1000;
1732 };
1733 StsTokenManager.fromJSON = function (appName, object) {
1734 var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
1735 var manager = new StsTokenManager();
1736 if (refreshToken) {
1737 _assert(typeof refreshToken === 'string', "internal-error" /* INTERNAL_ERROR */, {
1738 appName: appName
1739 });
1740 manager.refreshToken = refreshToken;
1741 }
1742 if (accessToken) {
1743 _assert(typeof accessToken === 'string', "internal-error" /* INTERNAL_ERROR */, {
1744 appName: appName
1745 });
1746 manager.accessToken = accessToken;
1747 }
1748 if (expirationTime) {
1749 _assert(typeof expirationTime === 'number', "internal-error" /* INTERNAL_ERROR */, {
1750 appName: appName
1751 });
1752 manager.expirationTime = expirationTime;
1753 }
1754 return manager;
1755 };
1756 StsTokenManager.prototype.toJSON = function () {
1757 return {
1758 refreshToken: this.refreshToken,
1759 accessToken: this.accessToken,
1760 expirationTime: this.expirationTime
1761 };
1762 };
1763 StsTokenManager.prototype._assign = function (stsTokenManager) {
1764 this.accessToken = stsTokenManager.accessToken;
1765 this.refreshToken = stsTokenManager.refreshToken;
1766 this.expirationTime = stsTokenManager.expirationTime;
1767 };
1768 StsTokenManager.prototype._clone = function () {
1769 return Object.assign(new StsTokenManager(), this.toJSON());
1770 };
1771 StsTokenManager.prototype._performRefresh = function () {
1772 return debugFail('not implemented');
1773 };
1774 return StsTokenManager;
1775}());
1776
1777/**
1778 * @license
1779 * Copyright 2020 Google LLC
1780 *
1781 * Licensed under the Apache License, Version 2.0 (the "License");
1782 * you may not use this file except in compliance with the License.
1783 * You may obtain a copy of the License at
1784 *
1785 * http://www.apache.org/licenses/LICENSE-2.0
1786 *
1787 * Unless required by applicable law or agreed to in writing, software
1788 * distributed under the License is distributed on an "AS IS" BASIS,
1789 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1790 * See the License for the specific language governing permissions and
1791 * limitations under the License.
1792 */
1793function assertStringOrUndefined(assertion, appName) {
1794 _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* INTERNAL_ERROR */, { appName: appName });
1795}
1796var UserImpl = /** @class */ (function () {
1797 function UserImpl(_a) {
1798 var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
1799 // For the user object, provider is always Firebase.
1800 this.providerId = "firebase" /* FIREBASE */;
1801 this.proactiveRefresh = new ProactiveRefresh(this);
1802 this.reloadUserInfo = null;
1803 this.reloadListener = null;
1804 this.uid = uid;
1805 this.auth = auth;
1806 this.stsTokenManager = stsTokenManager;
1807 this.accessToken = stsTokenManager.accessToken;
1808 this.displayName = opt.displayName || null;
1809 this.email = opt.email || null;
1810 this.emailVerified = opt.emailVerified || false;
1811 this.phoneNumber = opt.phoneNumber || null;
1812 this.photoURL = opt.photoURL || null;
1813 this.isAnonymous = opt.isAnonymous || false;
1814 this.tenantId = opt.tenantId || null;
1815 this.providerData = opt.providerData ? __spreadArray([], opt.providerData) : [];
1816 this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
1817 }
1818 UserImpl.prototype.getIdToken = function (forceRefresh) {
1819 return __awaiter(this, void 0, void 0, function () {
1820 var accessToken;
1821 return __generator(this, function (_a) {
1822 switch (_a.label) {
1823 case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
1824 case 1:
1825 accessToken = _a.sent();
1826 _assert(accessToken, this.auth, "internal-error" /* INTERNAL_ERROR */);
1827 if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
1828 this.accessToken = accessToken;
1829 return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
1830 case 2:
1831 _a.sent();
1832 this.auth._notifyListenersIfCurrent(this);
1833 _a.label = 3;
1834 case 3: return [2 /*return*/, accessToken];
1835 }
1836 });
1837 });
1838 };
1839 UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
1840 return getIdTokenResult(this, forceRefresh);
1841 };
1842 UserImpl.prototype.reload = function () {
1843 return reload(this);
1844 };
1845 UserImpl.prototype._assign = function (user) {
1846 if (this === user) {
1847 return;
1848 }
1849 _assert(this.uid === user.uid, this.auth, "internal-error" /* INTERNAL_ERROR */);
1850 this.displayName = user.displayName;
1851 this.photoURL = user.photoURL;
1852 this.email = user.email;
1853 this.emailVerified = user.emailVerified;
1854 this.phoneNumber = user.phoneNumber;
1855 this.isAnonymous = user.isAnonymous;
1856 this.tenantId = user.tenantId;
1857 this.providerData = user.providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
1858 this.metadata._copy(user.metadata);
1859 this.stsTokenManager._assign(user.stsTokenManager);
1860 };
1861 UserImpl.prototype._clone = function (auth) {
1862 return new UserImpl(__assign(__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
1863 };
1864 UserImpl.prototype._onReload = function (callback) {
1865 // There should only ever be one listener, and that is a single instance of MultiFactorUser
1866 _assert(!this.reloadListener, this.auth, "internal-error" /* INTERNAL_ERROR */);
1867 this.reloadListener = callback;
1868 if (this.reloadUserInfo) {
1869 this._notifyReloadListener(this.reloadUserInfo);
1870 this.reloadUserInfo = null;
1871 }
1872 };
1873 UserImpl.prototype._notifyReloadListener = function (userInfo) {
1874 if (this.reloadListener) {
1875 this.reloadListener(userInfo);
1876 }
1877 else {
1878 // If no listener is subscribed yet, save the result so it's available when they do subscribe
1879 this.reloadUserInfo = userInfo;
1880 }
1881 };
1882 UserImpl.prototype._startProactiveRefresh = function () {
1883 this.proactiveRefresh._start();
1884 };
1885 UserImpl.prototype._stopProactiveRefresh = function () {
1886 this.proactiveRefresh._stop();
1887 };
1888 UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
1889 if (reload === void 0) { reload = false; }
1890 return __awaiter(this, void 0, void 0, function () {
1891 var tokensRefreshed;
1892 return __generator(this, function (_a) {
1893 switch (_a.label) {
1894 case 0:
1895 tokensRefreshed = false;
1896 if (response.idToken &&
1897 response.idToken !== this.stsTokenManager.accessToken) {
1898 this.stsTokenManager.updateFromServerResponse(response);
1899 tokensRefreshed = true;
1900 }
1901 if (!reload) return [3 /*break*/, 2];
1902 return [4 /*yield*/, _reloadWithoutSaving(this)];
1903 case 1:
1904 _a.sent();
1905 _a.label = 2;
1906 case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
1907 case 3:
1908 _a.sent();
1909 if (tokensRefreshed) {
1910 this.auth._notifyListenersIfCurrent(this);
1911 }
1912 return [2 /*return*/];
1913 }
1914 });
1915 });
1916 };
1917 UserImpl.prototype.delete = function () {
1918 return __awaiter(this, void 0, void 0, function () {
1919 var idToken;
1920 return __generator(this, function (_a) {
1921 switch (_a.label) {
1922 case 0: return [4 /*yield*/, this.getIdToken()];
1923 case 1:
1924 idToken = _a.sent();
1925 return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
1926 case 2:
1927 _a.sent();
1928 this.stsTokenManager.clearRefreshToken();
1929 // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
1930 // cancels pending actions...
1931 return [2 /*return*/, this.auth.signOut()];
1932 }
1933 });
1934 });
1935 };
1936 UserImpl.prototype.toJSON = function () {
1937 return __assign(__assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(function (userInfo) { return (__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
1938 // Redirect event ID must be maintained in case there is a pending
1939 // redirect event.
1940 _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
1941 // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
1942 apiKey: this.auth.config.apiKey, appName: this.auth.name });
1943 };
1944 Object.defineProperty(UserImpl.prototype, "refreshToken", {
1945 get: function () {
1946 return this.stsTokenManager.refreshToken || '';
1947 },
1948 enumerable: false,
1949 configurable: true
1950 });
1951 UserImpl._fromJSON = function (auth, object) {
1952 var _a, _b, _c, _d, _e, _f, _g, _h;
1953 var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
1954 var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
1955 var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
1956 var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
1957 var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
1958 var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
1959 var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
1960 var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
1961 var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
1962 _assert(uid && plainObjectTokenManager, auth, "internal-error" /* INTERNAL_ERROR */);
1963 var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
1964 _assert(typeof uid === 'string', auth, "internal-error" /* INTERNAL_ERROR */);
1965 assertStringOrUndefined(displayName, auth.name);
1966 assertStringOrUndefined(email, auth.name);
1967 _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* INTERNAL_ERROR */);
1968 _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* INTERNAL_ERROR */);
1969 assertStringOrUndefined(phoneNumber, auth.name);
1970 assertStringOrUndefined(photoURL, auth.name);
1971 assertStringOrUndefined(tenantId, auth.name);
1972 assertStringOrUndefined(_redirectEventId, auth.name);
1973 assertStringOrUndefined(createdAt, auth.name);
1974 assertStringOrUndefined(lastLoginAt, auth.name);
1975 var user = new UserImpl({
1976 uid: uid,
1977 auth: auth,
1978 email: email,
1979 emailVerified: emailVerified,
1980 displayName: displayName,
1981 isAnonymous: isAnonymous,
1982 photoURL: photoURL,
1983 phoneNumber: phoneNumber,
1984 tenantId: tenantId,
1985 stsTokenManager: stsTokenManager,
1986 createdAt: createdAt,
1987 lastLoginAt: lastLoginAt
1988 });
1989 if (providerData && Array.isArray(providerData)) {
1990 user.providerData = providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
1991 }
1992 if (_redirectEventId) {
1993 user._redirectEventId = _redirectEventId;
1994 }
1995 return user;
1996 };
1997 /**
1998 * Initialize a User from an idToken server response
1999 * @param auth
2000 * @param idTokenResponse
2001 */
2002 UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
2003 if (isAnonymous === void 0) { isAnonymous = false; }
2004 return __awaiter(this, void 0, void 0, function () {
2005 var stsTokenManager, user;
2006 return __generator(this, function (_a) {
2007 switch (_a.label) {
2008 case 0:
2009 stsTokenManager = new StsTokenManager();
2010 stsTokenManager.updateFromServerResponse(idTokenResponse);
2011 user = new UserImpl({
2012 uid: idTokenResponse.localId,
2013 auth: auth,
2014 stsTokenManager: stsTokenManager,
2015 isAnonymous: isAnonymous
2016 });
2017 // Updates the user info and data and resolves with a user instance.
2018 return [4 /*yield*/, _reloadWithoutSaving(user)];
2019 case 1:
2020 // Updates the user info and data and resolves with a user instance.
2021 _a.sent();
2022 return [2 /*return*/, user];
2023 }
2024 });
2025 });
2026 };
2027 return UserImpl;
2028}());
2029
2030/**
2031 * @license
2032 * Copyright 2019 Google LLC
2033 *
2034 * Licensed under the Apache License, Version 2.0 (the "License");
2035 * you may not use this file except in compliance with the License.
2036 * You may obtain a copy of the License at
2037 *
2038 * http://www.apache.org/licenses/LICENSE-2.0
2039 *
2040 * Unless required by applicable law or agreed to in writing, software
2041 * distributed under the License is distributed on an "AS IS" BASIS,
2042 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2043 * See the License for the specific language governing permissions and
2044 * limitations under the License.
2045 */
2046var InMemoryPersistence = /** @class */ (function () {
2047 function InMemoryPersistence() {
2048 this.type = "NONE" /* NONE */;
2049 this.storage = {};
2050 }
2051 InMemoryPersistence.prototype._isAvailable = function () {
2052 return __awaiter(this, void 0, void 0, function () {
2053 return __generator(this, function (_a) {
2054 return [2 /*return*/, true];
2055 });
2056 });
2057 };
2058 InMemoryPersistence.prototype._set = function (key, value) {
2059 return __awaiter(this, void 0, void 0, function () {
2060 return __generator(this, function (_a) {
2061 this.storage[key] = value;
2062 return [2 /*return*/];
2063 });
2064 });
2065 };
2066 InMemoryPersistence.prototype._get = function (key) {
2067 return __awaiter(this, void 0, void 0, function () {
2068 var value;
2069 return __generator(this, function (_a) {
2070 value = this.storage[key];
2071 return [2 /*return*/, value === undefined ? null : value];
2072 });
2073 });
2074 };
2075 InMemoryPersistence.prototype._remove = function (key) {
2076 return __awaiter(this, void 0, void 0, function () {
2077 return __generator(this, function (_a) {
2078 delete this.storage[key];
2079 return [2 /*return*/];
2080 });
2081 });
2082 };
2083 InMemoryPersistence.prototype._addListener = function (_key, _listener) {
2084 // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
2085 return;
2086 };
2087 InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
2088 // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
2089 return;
2090 };
2091 InMemoryPersistence.type = 'NONE';
2092 return InMemoryPersistence;
2093}());
2094/**
2095 * An implementation of {@link Persistence} of type 'NONE'.
2096 *
2097 * @public
2098 */
2099var inMemoryPersistence = InMemoryPersistence;
2100
2101/**
2102 * @license
2103 * Copyright 2019 Google LLC
2104 *
2105 * Licensed under the Apache License, Version 2.0 (the "License");
2106 * you may not use this file except in compliance with the License.
2107 * You may obtain a copy of the License at
2108 *
2109 * http://www.apache.org/licenses/LICENSE-2.0
2110 *
2111 * Unless required by applicable law or agreed to in writing, software
2112 * distributed under the License is distributed on an "AS IS" BASIS,
2113 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2114 * See the License for the specific language governing permissions and
2115 * limitations under the License.
2116 */
2117function _persistenceKeyName(key, apiKey, appName) {
2118 return "firebase" /* PERSISTENCE */ + ":" + key + ":" + apiKey + ":" + appName;
2119}
2120var PersistenceUserManager = /** @class */ (function () {
2121 function PersistenceUserManager(persistence, auth, userKey) {
2122 this.persistence = persistence;
2123 this.auth = auth;
2124 this.userKey = userKey;
2125 var _a = this.auth, config = _a.config, name = _a.name;
2126 this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
2127 this.fullPersistenceKey = _persistenceKeyName("persistence" /* PERSISTENCE_USER */, config.apiKey, name);
2128 this.boundEventHandler = auth._onStorageEvent.bind(auth);
2129 this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
2130 }
2131 PersistenceUserManager.prototype.setCurrentUser = function (user) {
2132 return this.persistence._set(this.fullUserKey, user.toJSON());
2133 };
2134 PersistenceUserManager.prototype.getCurrentUser = function () {
2135 return __awaiter(this, void 0, void 0, function () {
2136 var blob;
2137 return __generator(this, function (_a) {
2138 switch (_a.label) {
2139 case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
2140 case 1:
2141 blob = _a.sent();
2142 return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
2143 }
2144 });
2145 });
2146 };
2147 PersistenceUserManager.prototype.removeCurrentUser = function () {
2148 return this.persistence._remove(this.fullUserKey);
2149 };
2150 PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
2151 return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
2152 };
2153 PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
2154 return __awaiter(this, void 0, void 0, function () {
2155 var currentUser;
2156 return __generator(this, function (_a) {
2157 switch (_a.label) {
2158 case 0:
2159 if (this.persistence === newPersistence) {
2160 return [2 /*return*/];
2161 }
2162 return [4 /*yield*/, this.getCurrentUser()];
2163 case 1:
2164 currentUser = _a.sent();
2165 return [4 /*yield*/, this.removeCurrentUser()];
2166 case 2:
2167 _a.sent();
2168 this.persistence = newPersistence;
2169 if (currentUser) {
2170 return [2 /*return*/, this.setCurrentUser(currentUser)];
2171 }
2172 return [2 /*return*/];
2173 }
2174 });
2175 });
2176 };
2177 PersistenceUserManager.prototype.delete = function () {
2178 this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
2179 };
2180 PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
2181 if (userKey === void 0) { userKey = "authUser" /* AUTH_USER */; }
2182 return __awaiter(this, void 0, void 0, function () {
2183 var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
2184 var _this = this;
2185 return __generator(this, function (_b) {
2186 switch (_b.label) {
2187 case 0:
2188 if (!persistenceHierarchy.length) {
2189 return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
2190 }
2191 return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
2192 return __generator(this, function (_a) {
2193 switch (_a.label) {
2194 case 0: return [4 /*yield*/, persistence._isAvailable()];
2195 case 1:
2196 if (_a.sent()) {
2197 return [2 /*return*/, persistence];
2198 }
2199 return [2 /*return*/, undefined];
2200 }
2201 });
2202 }); }))];
2203 case 1:
2204 availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
2205 selectedPersistence = availablePersistences[0] ||
2206 _getInstance(inMemoryPersistence);
2207 key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
2208 userToMigrate = null;
2209 _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
2210 _b.label = 2;
2211 case 2:
2212 if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
2213 persistence = persistenceHierarchy_1[_i];
2214 _b.label = 3;
2215 case 3:
2216 _b.trys.push([3, 5, , 6]);
2217 return [4 /*yield*/, persistence._get(key)];
2218 case 4:
2219 blob = _b.sent();
2220 if (blob) {
2221 user = UserImpl._fromJSON(auth, blob);
2222 if (persistence !== selectedPersistence) {
2223 userToMigrate = user;
2224 }
2225 selectedPersistence = persistence;
2226 return [3 /*break*/, 7];
2227 }
2228 return [3 /*break*/, 6];
2229 case 5:
2230 _b.sent();
2231 return [3 /*break*/, 6];
2232 case 6:
2233 _i++;
2234 return [3 /*break*/, 2];
2235 case 7:
2236 migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
2237 // If the persistence does _not_ allow migration, just finish off here
2238 if (!selectedPersistence._shouldAllowMigration ||
2239 !migrationHierarchy.length) {
2240 return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
2241 }
2242 selectedPersistence = migrationHierarchy[0];
2243 if (!userToMigrate) return [3 /*break*/, 9];
2244 // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
2245 // we'll just let it bubble to surface the error.
2246 return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
2247 case 8:
2248 // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
2249 // we'll just let it bubble to surface the error.
2250 _b.sent();
2251 _b.label = 9;
2252 case 9:
2253 // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
2254 // such as users getting stuck with a previous account after signing out and refreshing the tab.
2255 return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
2256 return __generator(this, function (_b) {
2257 switch (_b.label) {
2258 case 0:
2259 if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
2260 _b.label = 1;
2261 case 1:
2262 _b.trys.push([1, 3, , 4]);
2263 return [4 /*yield*/, persistence._remove(key)];
2264 case 2:
2265 _b.sent();
2266 return [3 /*break*/, 4];
2267 case 3:
2268 _b.sent();
2269 return [3 /*break*/, 4];
2270 case 4: return [2 /*return*/];
2271 }
2272 });
2273 }); }))];
2274 case 10:
2275 // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
2276 // such as users getting stuck with a previous account after signing out and refreshing the tab.
2277 _b.sent();
2278 return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
2279 }
2280 });
2281 });
2282 };
2283 return PersistenceUserManager;
2284}());
2285
2286/**
2287 * @license
2288 * Copyright 2020 Google LLC
2289 *
2290 * Licensed under the Apache License, Version 2.0 (the "License");
2291 * you may not use this file except in compliance with the License.
2292 * You may obtain a copy of the License at
2293 *
2294 * http://www.apache.org/licenses/LICENSE-2.0
2295 *
2296 * Unless required by applicable law or agreed to in writing, software
2297 * distributed under the License is distributed on an "AS IS" BASIS,
2298 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2299 * See the License for the specific language governing permissions and
2300 * limitations under the License.
2301 */
2302/**
2303 * Determine the browser for the purposes of reporting usage to the API
2304 */
2305function _getBrowserName(userAgent) {
2306 var ua = userAgent.toLowerCase();
2307 if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
2308 return "Opera" /* OPERA */;
2309 }
2310 else if (_isIEMobile(ua)) {
2311 // Windows phone IEMobile browser.
2312 return "IEMobile" /* IEMOBILE */;
2313 }
2314 else if (ua.includes('msie') || ua.includes('trident/')) {
2315 return "IE" /* IE */;
2316 }
2317 else if (ua.includes('edge/')) {
2318 return "Edge" /* EDGE */;
2319 }
2320 else if (_isFirefox(ua)) {
2321 return "Firefox" /* FIREFOX */;
2322 }
2323 else if (ua.includes('silk/')) {
2324 return "Silk" /* SILK */;
2325 }
2326 else if (_isBlackBerry(ua)) {
2327 // Blackberry browser.
2328 return "Blackberry" /* BLACKBERRY */;
2329 }
2330 else if (_isWebOS(ua)) {
2331 // WebOS default browser.
2332 return "Webos" /* WEBOS */;
2333 }
2334 else if (_isSafari(ua)) {
2335 return "Safari" /* SAFARI */;
2336 }
2337 else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
2338 !ua.includes('edge/')) {
2339 return "Chrome" /* CHROME */;
2340 }
2341 else if (_isAndroid(ua)) {
2342 // Android stock browser.
2343 return "Android" /* ANDROID */;
2344 }
2345 else {
2346 // Most modern browsers have name/version at end of user agent string.
2347 var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
2348 var matches = userAgent.match(re);
2349 if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
2350 return matches[1];
2351 }
2352 }
2353 return "Other" /* OTHER */;
2354}
2355function _isFirefox(ua) {
2356 if (ua === void 0) { ua = getUA(); }
2357 return /firefox\//i.test(ua);
2358}
2359function _isSafari(userAgent) {
2360 if (userAgent === void 0) { userAgent = getUA(); }
2361 var ua = userAgent.toLowerCase();
2362 return (ua.includes('safari/') &&
2363 !ua.includes('chrome/') &&
2364 !ua.includes('crios/') &&
2365 !ua.includes('android'));
2366}
2367function _isChromeIOS(ua) {
2368 if (ua === void 0) { ua = getUA(); }
2369 return /crios\//i.test(ua);
2370}
2371function _isIEMobile(ua) {
2372 if (ua === void 0) { ua = getUA(); }
2373 return /iemobile/i.test(ua);
2374}
2375function _isAndroid(ua) {
2376 if (ua === void 0) { ua = getUA(); }
2377 return /android/i.test(ua);
2378}
2379function _isBlackBerry(ua) {
2380 if (ua === void 0) { ua = getUA(); }
2381 return /blackberry/i.test(ua);
2382}
2383function _isWebOS(ua) {
2384 if (ua === void 0) { ua = getUA(); }
2385 return /webos/i.test(ua);
2386}
2387function _isIOS(ua) {
2388 if (ua === void 0) { ua = getUA(); }
2389 return /iphone|ipad|ipod/i.test(ua);
2390}
2391function _isIOS7Or8(ua) {
2392 if (ua === void 0) { ua = getUA(); }
2393 return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
2394 /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
2395}
2396function _isIOSStandalone(ua) {
2397 var _a;
2398 if (ua === void 0) { ua = getUA(); }
2399 return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
2400}
2401function _isIE10() {
2402 return isIE() && document.documentMode === 10;
2403}
2404function _isMobileBrowser(ua) {
2405 if (ua === void 0) { ua = getUA(); }
2406 // TODO: implement getBrowserName equivalent for OS.
2407 return (_isIOS(ua) ||
2408 _isAndroid(ua) ||
2409 _isWebOS(ua) ||
2410 _isBlackBerry(ua) ||
2411 /windows phone/i.test(ua) ||
2412 _isIEMobile(ua));
2413}
2414function _isIframe() {
2415 try {
2416 // Check that the current window is not the top window.
2417 // If so, return true.
2418 return !!(window && window !== window.top);
2419 }
2420 catch (e) {
2421 return false;
2422 }
2423}
2424
2425/**
2426 * @license
2427 * Copyright 2020 Google LLC
2428 *
2429 * Licensed under the Apache License, Version 2.0 (the "License");
2430 * you may not use this file except in compliance with the License.
2431 * You may obtain a copy of the License at
2432 *
2433 * http://www.apache.org/licenses/LICENSE-2.0
2434 *
2435 * Unless required by applicable law or agreed to in writing, software
2436 * distributed under the License is distributed on an "AS IS" BASIS,
2437 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2438 * See the License for the specific language governing permissions and
2439 * limitations under the License.
2440 */
2441/*
2442 * Determine the SDK version string
2443 */
2444function _getClientVersion(clientPlatform, frameworks) {
2445 if (frameworks === void 0) { frameworks = []; }
2446 var reportedPlatform;
2447 switch (clientPlatform) {
2448 case "Browser" /* BROWSER */:
2449 // In a browser environment, report the browser name.
2450 reportedPlatform = _getBrowserName(getUA());
2451 break;
2452 case "Worker" /* WORKER */:
2453 // Technically a worker runs from a browser but we need to differentiate a
2454 // worker from a browser.
2455 // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
2456 reportedPlatform = _getBrowserName(getUA()) + "-" + clientPlatform;
2457 break;
2458 default:
2459 reportedPlatform = clientPlatform;
2460 }
2461 var reportedFrameworks = frameworks.length
2462 ? frameworks.join(',')
2463 : 'FirebaseCore-web'; /* default value if no other framework is used */
2464 return reportedPlatform + "/" + "JsCore" /* CORE */ + "/" + SDK_VERSION + "/" + reportedFrameworks;
2465}
2466
2467/**
2468 * @license
2469 * Copyright 2022 Google LLC
2470 *
2471 * Licensed under the Apache License, Version 2.0 (the "License");
2472 * you may not use this file except in compliance with the License.
2473 * You may obtain a copy of the License at
2474 *
2475 * http://www.apache.org/licenses/LICENSE-2.0
2476 *
2477 * Unless required by applicable law or agreed to in writing, software
2478 * distributed under the License is distributed on an "AS IS" BASIS,
2479 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2480 * See the License for the specific language governing permissions and
2481 * limitations under the License.
2482 */
2483var AuthMiddlewareQueue = /** @class */ (function () {
2484 function AuthMiddlewareQueue(auth) {
2485 this.auth = auth;
2486 this.queue = [];
2487 }
2488 AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
2489 var _this = this;
2490 // The callback could be sync or async. Wrap it into a
2491 // function that is always async.
2492 var wrappedCallback = function (user) { return new Promise(function (resolve, reject) {
2493 try {
2494 var result = callback(user);
2495 // Either resolve with existing promise or wrap a non-promise
2496 // return value into a promise.
2497 resolve(result);
2498 }
2499 catch (e) {
2500 // Sync callback throws.
2501 reject(e);
2502 }
2503 }); };
2504 // Attach the onAbort if present
2505 wrappedCallback.onAbort = onAbort;
2506 this.queue.push(wrappedCallback);
2507 var index = this.queue.length - 1;
2508 return function () {
2509 // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
2510 // indexing of other elements.
2511 _this.queue[index] = function () { return Promise.resolve(); };
2512 };
2513 };
2514 AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
2515 return __awaiter(this, void 0, void 0, function () {
2516 var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
2517 return __generator(this, function (_c) {
2518 switch (_c.label) {
2519 case 0:
2520 if (this.auth.currentUser === nextUser) {
2521 return [2 /*return*/];
2522 }
2523 onAbortStack = [];
2524 _c.label = 1;
2525 case 1:
2526 _c.trys.push([1, 6, , 7]);
2527 _i = 0, _a = this.queue;
2528 _c.label = 2;
2529 case 2:
2530 if (!(_i < _a.length)) return [3 /*break*/, 5];
2531 beforeStateCallback = _a[_i];
2532 return [4 /*yield*/, beforeStateCallback(nextUser)];
2533 case 3:
2534 _c.sent();
2535 // Only push the onAbort if the callback succeeds
2536 if (beforeStateCallback.onAbort) {
2537 onAbortStack.push(beforeStateCallback.onAbort);
2538 }
2539 _c.label = 4;
2540 case 4:
2541 _i++;
2542 return [3 /*break*/, 2];
2543 case 5: return [3 /*break*/, 7];
2544 case 6:
2545 e_1 = _c.sent();
2546 // Run all onAbort, with separate try/catch to ignore any errors and
2547 // continue
2548 onAbortStack.reverse();
2549 for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
2550 onAbort = onAbortStack_1[_b];
2551 try {
2552 onAbort();
2553 }
2554 catch (_) { /* swallow error */ }
2555 }
2556 throw this.auth._errorFactory.create("login-blocked" /* LOGIN_BLOCKED */, { originalMessage: e_1.message });
2557 case 7: return [2 /*return*/];
2558 }
2559 });
2560 });
2561 };
2562 return AuthMiddlewareQueue;
2563}());
2564
2565/**
2566 * @license
2567 * Copyright 2020 Google LLC
2568 *
2569 * Licensed under the Apache License, Version 2.0 (the "License");
2570 * you may not use this file except in compliance with the License.
2571 * You may obtain a copy of the License at
2572 *
2573 * http://www.apache.org/licenses/LICENSE-2.0
2574 *
2575 * Unless required by applicable law or agreed to in writing, software
2576 * distributed under the License is distributed on an "AS IS" BASIS,
2577 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2578 * See the License for the specific language governing permissions and
2579 * limitations under the License.
2580 */
2581var AuthImpl = /** @class */ (function () {
2582 function AuthImpl(app, heartbeatServiceProvider, config) {
2583 this.app = app;
2584 this.heartbeatServiceProvider = heartbeatServiceProvider;
2585 this.config = config;
2586 this.currentUser = null;
2587 this.emulatorConfig = null;
2588 this.operations = Promise.resolve();
2589 this.authStateSubscription = new Subscription(this);
2590 this.idTokenSubscription = new Subscription(this);
2591 this.beforeStateQueue = new AuthMiddlewareQueue(this);
2592 this.redirectUser = null;
2593 this.isProactiveRefreshEnabled = false;
2594 // Any network calls will set this to true and prevent subsequent emulator
2595 // initialization
2596 this._canInitEmulator = true;
2597 this._isInitialized = false;
2598 this._deleted = false;
2599 this._initializationPromise = null;
2600 this._popupRedirectResolver = null;
2601 this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
2602 // Tracks the last notified UID for state change listeners to prevent
2603 // repeated calls to the callbacks. Undefined means it's never been
2604 // called, whereas null means it's been called with a signed out user
2605 this.lastNotifiedUid = undefined;
2606 this.languageCode = null;
2607 this.tenantId = null;
2608 this.settings = { appVerificationDisabledForTesting: false };
2609 this.frameworks = [];
2610 this.name = app.name;
2611 this.clientVersion = config.sdkClientVersion;
2612 }
2613 AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
2614 var _this = this;
2615 if (popupRedirectResolver) {
2616 this._popupRedirectResolver = _getInstance(popupRedirectResolver);
2617 }
2618 // Have to check for app deletion throughout initialization (after each
2619 // promise resolution)
2620 this._initializationPromise = this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
2621 var _a;
2622 var _b, _c;
2623 return __generator(this, function (_d) {
2624 switch (_d.label) {
2625 case 0:
2626 if (this._deleted) {
2627 return [2 /*return*/];
2628 }
2629 _a = this;
2630 return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
2631 case 1:
2632 _a.persistenceManager = _d.sent();
2633 if (this._deleted) {
2634 return [2 /*return*/];
2635 }
2636 if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
2637 _d.label = 2;
2638 case 2:
2639 _d.trys.push([2, 4, , 5]);
2640 return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
2641 case 3:
2642 _d.sent();
2643 return [3 /*break*/, 5];
2644 case 4:
2645 _d.sent();
2646 return [3 /*break*/, 5];
2647 case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
2648 case 6:
2649 _d.sent();
2650 this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
2651 if (this._deleted) {
2652 return [2 /*return*/];
2653 }
2654 this._isInitialized = true;
2655 return [2 /*return*/];
2656 }
2657 });
2658 }); });
2659 return this._initializationPromise;
2660 };
2661 /**
2662 * If the persistence is changed in another window, the user manager will let us know
2663 */
2664 AuthImpl.prototype._onStorageEvent = function () {
2665 return __awaiter(this, void 0, void 0, function () {
2666 var user;
2667 return __generator(this, function (_a) {
2668 switch (_a.label) {
2669 case 0:
2670 if (this._deleted) {
2671 return [2 /*return*/];
2672 }
2673 return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
2674 case 1:
2675 user = _a.sent();
2676 if (!this.currentUser && !user) {
2677 // No change, do nothing (was signed out and remained signed out).
2678 return [2 /*return*/];
2679 }
2680 if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
2681 // Data update, simply copy data changes.
2682 this._currentUser._assign(user);
2683 // If tokens changed from previous user tokens, this will trigger
2684 // notifyAuthListeners_.
2685 return [4 /*yield*/, this.currentUser.getIdToken()];
2686 case 2:
2687 // If tokens changed from previous user tokens, this will trigger
2688 // notifyAuthListeners_.
2689 _a.sent();
2690 return [2 /*return*/];
2691 case 3:
2692 // Update current Auth state. Either a new login or logout.
2693 // Skip blocking callbacks, they should not apply to a change in another tab.
2694 return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
2695 case 4:
2696 // Update current Auth state. Either a new login or logout.
2697 // Skip blocking callbacks, they should not apply to a change in another tab.
2698 _a.sent();
2699 return [2 /*return*/];
2700 }
2701 });
2702 });
2703 };
2704 AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
2705 var _a;
2706 return __awaiter(this, void 0, void 0, function () {
2707 var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
2708 return __generator(this, function (_b) {
2709 switch (_b.label) {
2710 case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
2711 case 1:
2712 previouslyStoredUser = (_b.sent());
2713 futureCurrentUser = previouslyStoredUser;
2714 needsTocheckMiddleware = false;
2715 if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
2716 return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
2717 case 2:
2718 _b.sent();
2719 redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
2720 storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
2721 return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
2722 case 3:
2723 result = _b.sent();
2724 // If the stored user (i.e. the old "currentUser") has a redirectId that
2725 // matches the redirect user, then we want to initially sign in with the
2726 // new user object from result.
2727 // TODO(samgho): More thoroughly test all of this
2728 if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
2729 (result === null || result === void 0 ? void 0 : result.user)) {
2730 futureCurrentUser = result.user;
2731 needsTocheckMiddleware = true;
2732 }
2733 _b.label = 4;
2734 case 4:
2735 // If no user in persistence, there is no current user. Set to null.
2736 if (!futureCurrentUser) {
2737 return [2 /*return*/, this.directlySetCurrentUser(null)];
2738 }
2739 if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
2740 if (!needsTocheckMiddleware) return [3 /*break*/, 8];
2741 _b.label = 5;
2742 case 5:
2743 _b.trys.push([5, 7, , 8]);
2744 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
2745 case 6:
2746 _b.sent();
2747 return [3 /*break*/, 8];
2748 case 7:
2749 e_2 = _b.sent();
2750 futureCurrentUser = previouslyStoredUser;
2751 // We know this is available since the bit is only set when the
2752 // resolver is available
2753 this._popupRedirectResolver._overrideRedirectResult(this, function () { return Promise.reject(e_2); });
2754 return [3 /*break*/, 8];
2755 case 8:
2756 if (futureCurrentUser) {
2757 return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
2758 }
2759 else {
2760 return [2 /*return*/, this.directlySetCurrentUser(null)];
2761 }
2762 case 9:
2763 _assert(this._popupRedirectResolver, this, "argument-error" /* ARGUMENT_ERROR */);
2764 return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
2765 case 10:
2766 _b.sent();
2767 // If the redirect user's event ID matches the current user's event ID,
2768 // DO NOT reload the current user, otherwise they'll be cleared from storage.
2769 // This is important for the reauthenticateWithRedirect() flow.
2770 if (this.redirectUser &&
2771 this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
2772 return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
2773 }
2774 return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
2775 }
2776 });
2777 });
2778 };
2779 AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
2780 return __awaiter(this, void 0, void 0, function () {
2781 var result;
2782 return __generator(this, function (_a) {
2783 switch (_a.label) {
2784 case 0:
2785 result = null;
2786 _a.label = 1;
2787 case 1:
2788 _a.trys.push([1, 3, , 5]);
2789 return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
2790 case 2:
2791 // We know this._popupRedirectResolver is set since redirectResolver
2792 // is passed in. The _completeRedirectFn expects the unwrapped extern.
2793 result = _a.sent();
2794 return [3 /*break*/, 5];
2795 case 3:
2796 _a.sent();
2797 // Swallow any errors here; the code can retrieve them in
2798 // getRedirectResult().
2799 return [4 /*yield*/, this._setRedirectUser(null)];
2800 case 4:
2801 // Swallow any errors here; the code can retrieve them in
2802 // getRedirectResult().
2803 _a.sent();
2804 return [3 /*break*/, 5];
2805 case 5: return [2 /*return*/, result];
2806 }
2807 });
2808 });
2809 };
2810 AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
2811 return __awaiter(this, void 0, void 0, function () {
2812 var e_4;
2813 return __generator(this, function (_a) {
2814 switch (_a.label) {
2815 case 0:
2816 _a.trys.push([0, 2, , 3]);
2817 return [4 /*yield*/, _reloadWithoutSaving(user)];
2818 case 1:
2819 _a.sent();
2820 return [3 /*break*/, 3];
2821 case 2:
2822 e_4 = _a.sent();
2823 if (e_4.code !== "auth/" + "network-request-failed" /* NETWORK_REQUEST_FAILED */) {
2824 // Something's wrong with the user's token. Log them out and remove
2825 // them from storage
2826 return [2 /*return*/, this.directlySetCurrentUser(null)];
2827 }
2828 return [3 /*break*/, 3];
2829 case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
2830 }
2831 });
2832 });
2833 };
2834 AuthImpl.prototype.useDeviceLanguage = function () {
2835 this.languageCode = _getUserLanguage();
2836 };
2837 AuthImpl.prototype._delete = function () {
2838 return __awaiter(this, void 0, void 0, function () {
2839 return __generator(this, function (_a) {
2840 this._deleted = true;
2841 return [2 /*return*/];
2842 });
2843 });
2844 };
2845 AuthImpl.prototype.updateCurrentUser = function (userExtern) {
2846 return __awaiter(this, void 0, void 0, function () {
2847 var user;
2848 return __generator(this, function (_a) {
2849 user = userExtern
2850 ? getModularInstance(userExtern)
2851 : null;
2852 if (user) {
2853 _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* INVALID_AUTH */);
2854 }
2855 return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
2856 });
2857 });
2858 };
2859 AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
2860 if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
2861 return __awaiter(this, void 0, void 0, function () {
2862 var _this = this;
2863 return __generator(this, function (_a) {
2864 switch (_a.label) {
2865 case 0:
2866 if (this._deleted) {
2867 return [2 /*return*/];
2868 }
2869 if (user) {
2870 _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* TENANT_ID_MISMATCH */);
2871 }
2872 if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
2873 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
2874 case 1:
2875 _a.sent();
2876 _a.label = 2;
2877 case 2: return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
2878 return __generator(this, function (_a) {
2879 switch (_a.label) {
2880 case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
2881 case 1:
2882 _a.sent();
2883 this.notifyAuthListeners();
2884 return [2 /*return*/];
2885 }
2886 });
2887 }); })];
2888 }
2889 });
2890 });
2891 };
2892 AuthImpl.prototype.signOut = function () {
2893 return __awaiter(this, void 0, void 0, function () {
2894 return __generator(this, function (_a) {
2895 switch (_a.label) {
2896 case 0:
2897 // Run first, to block _setRedirectUser() if any callbacks fail.
2898 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
2899 case 1:
2900 // Run first, to block _setRedirectUser() if any callbacks fail.
2901 _a.sent();
2902 if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
2903 return [4 /*yield*/, this._setRedirectUser(null)];
2904 case 2:
2905 _a.sent();
2906 _a.label = 3;
2907 case 3:
2908 // Prevent callbacks from being called again in _updateCurrentUser, as
2909 // they were already called in the first line.
2910 return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
2911 }
2912 });
2913 });
2914 };
2915 AuthImpl.prototype.setPersistence = function (persistence) {
2916 var _this = this;
2917 return this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
2918 return __generator(this, function (_a) {
2919 switch (_a.label) {
2920 case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
2921 case 1:
2922 _a.sent();
2923 return [2 /*return*/];
2924 }
2925 });
2926 }); });
2927 };
2928 AuthImpl.prototype._getPersistence = function () {
2929 return this.assertedPersistence.persistence.type;
2930 };
2931 AuthImpl.prototype._updateErrorMap = function (errorMap) {
2932 this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
2933 };
2934 AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
2935 return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
2936 };
2937 AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
2938 return this.beforeStateQueue.pushCallback(callback, onAbort);
2939 };
2940 AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
2941 return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
2942 };
2943 AuthImpl.prototype.toJSON = function () {
2944 var _a;
2945 return {
2946 apiKey: this.config.apiKey,
2947 authDomain: this.config.authDomain,
2948 appName: this.name,
2949 currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
2950 };
2951 };
2952 AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
2953 return __awaiter(this, void 0, void 0, function () {
2954 var redirectManager;
2955 return __generator(this, function (_a) {
2956 switch (_a.label) {
2957 case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
2958 case 1:
2959 redirectManager = _a.sent();
2960 return [2 /*return*/, user === null
2961 ? redirectManager.removeCurrentUser()
2962 : redirectManager.setCurrentUser(user)];
2963 }
2964 });
2965 });
2966 };
2967 AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
2968 return __awaiter(this, void 0, void 0, function () {
2969 var resolver, _a, _b;
2970 return __generator(this, function (_c) {
2971 switch (_c.label) {
2972 case 0:
2973 if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
2974 resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
2975 this._popupRedirectResolver;
2976 _assert(resolver, this, "argument-error" /* ARGUMENT_ERROR */);
2977 _a = this;
2978 return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* REDIRECT_USER */)];
2979 case 1:
2980 _a.redirectPersistenceManager = _c.sent();
2981 _b = this;
2982 return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
2983 case 2:
2984 _b.redirectUser =
2985 _c.sent();
2986 _c.label = 3;
2987 case 3: return [2 /*return*/, this.redirectPersistenceManager];
2988 }
2989 });
2990 });
2991 };
2992 AuthImpl.prototype._redirectUserForId = function (id) {
2993 var _a, _b;
2994 return __awaiter(this, void 0, void 0, function () {
2995 var _this = this;
2996 return __generator(this, function (_c) {
2997 switch (_c.label) {
2998 case 0:
2999 if (!this._isInitialized) return [3 /*break*/, 2];
3000 return [4 /*yield*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
3001 return [2 /*return*/];
3002 }); }); })];
3003 case 1:
3004 _c.sent();
3005 _c.label = 2;
3006 case 2:
3007 if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
3008 return [2 /*return*/, this._currentUser];
3009 }
3010 if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
3011 return [2 /*return*/, this.redirectUser];
3012 }
3013 return [2 /*return*/, null];
3014 }
3015 });
3016 });
3017 };
3018 AuthImpl.prototype._persistUserIfCurrent = function (user) {
3019 return __awaiter(this, void 0, void 0, function () {
3020 var _this = this;
3021 return __generator(this, function (_a) {
3022 if (user === this.currentUser) {
3023 return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
3024 return [2 /*return*/, this.directlySetCurrentUser(user)];
3025 }); }); })];
3026 }
3027 return [2 /*return*/];
3028 });
3029 });
3030 };
3031 /** Notifies listeners only if the user is current */
3032 AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
3033 if (user === this.currentUser) {
3034 this.notifyAuthListeners();
3035 }
3036 };
3037 AuthImpl.prototype._key = function () {
3038 return this.config.authDomain + ":" + this.config.apiKey + ":" + this.name;
3039 };
3040 AuthImpl.prototype._startProactiveRefresh = function () {
3041 this.isProactiveRefreshEnabled = true;
3042 if (this.currentUser) {
3043 this._currentUser._startProactiveRefresh();
3044 }
3045 };
3046 AuthImpl.prototype._stopProactiveRefresh = function () {
3047 this.isProactiveRefreshEnabled = false;
3048 if (this.currentUser) {
3049 this._currentUser._stopProactiveRefresh();
3050 }
3051 };
3052 Object.defineProperty(AuthImpl.prototype, "_currentUser", {
3053 /** Returns the current user cast as the internal type */
3054 get: function () {
3055 return this.currentUser;
3056 },
3057 enumerable: false,
3058 configurable: true
3059 });
3060 AuthImpl.prototype.notifyAuthListeners = function () {
3061 var _a, _b;
3062 if (!this._isInitialized) {
3063 return;
3064 }
3065 this.idTokenSubscription.next(this.currentUser);
3066 var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
3067 if (this.lastNotifiedUid !== currentUid) {
3068 this.lastNotifiedUid = currentUid;
3069 this.authStateSubscription.next(this.currentUser);
3070 }
3071 };
3072 AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
3073 var _this = this;
3074 if (this._deleted) {
3075 return function () { };
3076 }
3077 var cb = typeof nextOrObserver === 'function'
3078 ? nextOrObserver
3079 : nextOrObserver.next.bind(nextOrObserver);
3080 var promise = this._isInitialized
3081 ? Promise.resolve()
3082 : this._initializationPromise;
3083 _assert(promise, this, "internal-error" /* INTERNAL_ERROR */);
3084 // The callback needs to be called asynchronously per the spec.
3085 // eslint-disable-next-line @typescript-eslint/no-floating-promises
3086 promise.then(function () { return cb(_this.currentUser); });
3087 if (typeof nextOrObserver === 'function') {
3088 return subscription.addObserver(nextOrObserver, error, completed);
3089 }
3090 else {
3091 return subscription.addObserver(nextOrObserver);
3092 }
3093 };
3094 /**
3095 * Unprotected (from race conditions) method to set the current user. This
3096 * should only be called from within a queued callback. This is necessary
3097 * because the queue shouldn't rely on another queued callback.
3098 */
3099 AuthImpl.prototype.directlySetCurrentUser = function (user) {
3100 return __awaiter(this, void 0, void 0, function () {
3101 return __generator(this, function (_a) {
3102 switch (_a.label) {
3103 case 0:
3104 if (this.currentUser && this.currentUser !== user) {
3105 this._currentUser._stopProactiveRefresh();
3106 if (user && this.isProactiveRefreshEnabled) {
3107 user._startProactiveRefresh();
3108 }
3109 }
3110 this.currentUser = user;
3111 if (!user) return [3 /*break*/, 2];
3112 return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
3113 case 1:
3114 _a.sent();
3115 return [3 /*break*/, 4];
3116 case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
3117 case 3:
3118 _a.sent();
3119 _a.label = 4;
3120 case 4: return [2 /*return*/];
3121 }
3122 });
3123 });
3124 };
3125 AuthImpl.prototype.queue = function (action) {
3126 // In case something errors, the callback still should be called in order
3127 // to keep the promise chain alive
3128 this.operations = this.operations.then(action, action);
3129 return this.operations;
3130 };
3131 Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
3132 get: function () {
3133 _assert(this.persistenceManager, this, "internal-error" /* INTERNAL_ERROR */);
3134 return this.persistenceManager;
3135 },
3136 enumerable: false,
3137 configurable: true
3138 });
3139 AuthImpl.prototype._logFramework = function (framework) {
3140 if (!framework || this.frameworks.includes(framework)) {
3141 return;
3142 }
3143 this.frameworks.push(framework);
3144 // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
3145 // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
3146 this.frameworks.sort();
3147 this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
3148 };
3149 AuthImpl.prototype._getFrameworks = function () {
3150 return this.frameworks;
3151 };
3152 AuthImpl.prototype._getAdditionalHeaders = function () {
3153 var _a;
3154 return __awaiter(this, void 0, void 0, function () {
3155 var headers, heartbeatsHeader;
3156 var _b;
3157 return __generator(this, function (_c) {
3158 switch (_c.label) {
3159 case 0:
3160 headers = (_b = {},
3161 _b["X-Client-Version" /* X_CLIENT_VERSION */] = this.clientVersion,
3162 _b);
3163 if (this.app.options.appId) {
3164 headers["X-Firebase-gmpid" /* X_FIREBASE_GMPID */] = this.app.options.appId;
3165 }
3166 return [4 /*yield*/, ((_a = this.heartbeatServiceProvider.getImmediate({
3167 optional: true,
3168 })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
3169 case 1:
3170 heartbeatsHeader = _c.sent();
3171 if (heartbeatsHeader) {
3172 headers["X-Firebase-Client" /* X_FIREBASE_CLIENT */] = heartbeatsHeader;
3173 }
3174 return [2 /*return*/, headers];
3175 }
3176 });
3177 });
3178 };
3179 return AuthImpl;
3180}());
3181/**
3182 * Method to be used to cast down to our private implmentation of Auth.
3183 * It will also handle unwrapping from the compat type if necessary
3184 *
3185 * @param auth Auth object passed in from developer
3186 */
3187function _castAuth(auth) {
3188 return getModularInstance(auth);
3189}
3190/** Helper class to wrap subscriber logic */
3191var Subscription = /** @class */ (function () {
3192 function Subscription(auth) {
3193 var _this = this;
3194 this.auth = auth;
3195 this.observer = null;
3196 this.addObserver = createSubscribe(function (observer) { return (_this.observer = observer); });
3197 }
3198 Object.defineProperty(Subscription.prototype, "next", {
3199 get: function () {
3200 _assert(this.observer, this.auth, "internal-error" /* INTERNAL_ERROR */);
3201 return this.observer.next.bind(this.observer);
3202 },
3203 enumerable: false,
3204 configurable: true
3205 });
3206 return Subscription;
3207}());
3208
3209/**
3210 * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
3211 * Firebase Auth services.
3212 *
3213 * @remarks
3214 * This must be called synchronously immediately following the first call to
3215 * {@link initializeAuth}. Do not use with production credentials as emulator
3216 * traffic is not encrypted.
3217 *
3218 *
3219 * @example
3220 * ```javascript
3221 * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
3222 * ```
3223 *
3224 * @param auth - The {@link Auth} instance.
3225 * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
3226 * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
3227 * `true` to disable the warning banner attached to the DOM.
3228 *
3229 * @public
3230 */
3231function connectAuthEmulator(auth, url, options) {
3232 var authInternal = _castAuth(auth);
3233 _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* EMULATOR_CONFIG_FAILED */);
3234 _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* INVALID_EMULATOR_SCHEME */);
3235 var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
3236 var protocol = extractProtocol(url);
3237 var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
3238 var portStr = port === null ? '' : ":" + port;
3239 // Always replace path with "/" (even if input url had no path at all, or had a different one).
3240 authInternal.config.emulator = { url: protocol + "//" + host + portStr + "/" };
3241 authInternal.settings.appVerificationDisabledForTesting = true;
3242 authInternal.emulatorConfig = Object.freeze({
3243 host: host,
3244 port: port,
3245 protocol: protocol.replace(':', ''),
3246 options: Object.freeze({ disableWarnings: disableWarnings })
3247 });
3248 if (!disableWarnings) {
3249 emitEmulatorWarning();
3250 }
3251}
3252function extractProtocol(url) {
3253 var protocolEnd = url.indexOf(':');
3254 return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
3255}
3256function extractHostAndPort(url) {
3257 var protocol = extractProtocol(url);
3258 var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
3259 if (!authority) {
3260 return { host: '', port: null };
3261 }
3262 var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
3263 var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
3264 if (bracketedIPv6) {
3265 var host = bracketedIPv6[1];
3266 return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
3267 }
3268 else {
3269 var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
3270 return { host: host, port: parsePort(port) };
3271 }
3272}
3273function parsePort(portStr) {
3274 if (!portStr) {
3275 return null;
3276 }
3277 var port = Number(portStr);
3278 if (isNaN(port)) {
3279 return null;
3280 }
3281 return port;
3282}
3283function emitEmulatorWarning() {
3284 function attachBanner() {
3285 var el = document.createElement('p');
3286 var sty = el.style;
3287 el.innerText =
3288 'Running in emulator mode. Do not use with production credentials.';
3289 sty.position = 'fixed';
3290 sty.width = '100%';
3291 sty.backgroundColor = '#ffffff';
3292 sty.border = '.1em solid #000000';
3293 sty.color = '#b50000';
3294 sty.bottom = '0px';
3295 sty.left = '0px';
3296 sty.margin = '0px';
3297 sty.zIndex = '10000';
3298 sty.textAlign = 'center';
3299 el.classList.add('firebase-emulator-warning');
3300 document.body.appendChild(el);
3301 }
3302 if (typeof console !== 'undefined' && typeof console.info === 'function') {
3303 console.info('WARNING: You are using the Auth Emulator,' +
3304 ' which is intended for local testing only. Do not use with' +
3305 ' production credentials.');
3306 }
3307 if (typeof window !== 'undefined' &&
3308 typeof document !== 'undefined') {
3309 if (document.readyState === 'loading') {
3310 window.addEventListener('DOMContentLoaded', attachBanner);
3311 }
3312 else {
3313 attachBanner();
3314 }
3315 }
3316}
3317
3318/**
3319 * @license
3320 * Copyright 2020 Google LLC
3321 *
3322 * Licensed under the Apache License, Version 2.0 (the "License");
3323 * you may not use this file except in compliance with the License.
3324 * You may obtain a copy of the License at
3325 *
3326 * http://www.apache.org/licenses/LICENSE-2.0
3327 *
3328 * Unless required by applicable law or agreed to in writing, software
3329 * distributed under the License is distributed on an "AS IS" BASIS,
3330 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3331 * See the License for the specific language governing permissions and
3332 * limitations under the License.
3333 */
3334/**
3335 * Interface that represents the credentials returned by an {@link AuthProvider}.
3336 *
3337 * @remarks
3338 * Implementations specify the details about each auth provider's credential requirements.
3339 *
3340 * @public
3341 */
3342var AuthCredential = /** @class */ (function () {
3343 /** @internal */
3344 function AuthCredential(
3345 /**
3346 * The authentication provider ID for the credential.
3347 *
3348 * @remarks
3349 * For example, 'facebook.com', or 'google.com'.
3350 */
3351 providerId,
3352 /**
3353 * The authentication sign in method for the credential.
3354 *
3355 * @remarks
3356 * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
3357 * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
3358 * identifier as returned in {@link fetchSignInMethodsForEmail}.
3359 */
3360 signInMethod) {
3361 this.providerId = providerId;
3362 this.signInMethod = signInMethod;
3363 }
3364 /**
3365 * Returns a JSON-serializable representation of this object.
3366 *
3367 * @returns a JSON-serializable representation of this object.
3368 */
3369 AuthCredential.prototype.toJSON = function () {
3370 return debugFail('not implemented');
3371 };
3372 /** @internal */
3373 AuthCredential.prototype._getIdTokenResponse = function (_auth) {
3374 return debugFail('not implemented');
3375 };
3376 /** @internal */
3377 AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
3378 return debugFail('not implemented');
3379 };
3380 /** @internal */
3381 AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
3382 return debugFail('not implemented');
3383 };
3384 return AuthCredential;
3385}());
3386
3387/**
3388 * @license
3389 * Copyright 2020 Google LLC
3390 *
3391 * Licensed under the Apache License, Version 2.0 (the "License");
3392 * you may not use this file except in compliance with the License.
3393 * You may obtain a copy of the License at
3394 *
3395 * http://www.apache.org/licenses/LICENSE-2.0
3396 *
3397 * Unless required by applicable law or agreed to in writing, software
3398 * distributed under the License is distributed on an "AS IS" BASIS,
3399 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3400 * See the License for the specific language governing permissions and
3401 * limitations under the License.
3402 */
3403function resetPassword(auth, request) {
3404 return __awaiter(this, void 0, void 0, function () {
3405 return __generator(this, function (_a) {
3406 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:resetPassword" /* RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
3407 });
3408 });
3409}
3410function updateEmailPassword(auth, request) {
3411 return __awaiter(this, void 0, void 0, function () {
3412 return __generator(this, function (_a) {
3413 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
3414 });
3415 });
3416}
3417function applyActionCode$1(auth, request) {
3418 return __awaiter(this, void 0, void 0, function () {
3419 return __generator(this, function (_a) {
3420 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
3421 });
3422 });
3423}
3424
3425/**
3426 * @license
3427 * Copyright 2020 Google LLC
3428 *
3429 * Licensed under the Apache License, Version 2.0 (the "License");
3430 * you may not use this file except in compliance with the License.
3431 * You may obtain a copy of the License at
3432 *
3433 * http://www.apache.org/licenses/LICENSE-2.0
3434 *
3435 * Unless required by applicable law or agreed to in writing, software
3436 * distributed under the License is distributed on an "AS IS" BASIS,
3437 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3438 * See the License for the specific language governing permissions and
3439 * limitations under the License.
3440 */
3441function signInWithPassword(auth, request) {
3442 return __awaiter(this, void 0, void 0, function () {
3443 return __generator(this, function (_a) {
3444 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPassword" /* SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
3445 });
3446 });
3447}
3448function sendOobCode(auth, request) {
3449 return __awaiter(this, void 0, void 0, function () {
3450 return __generator(this, function (_a) {
3451 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:sendOobCode" /* SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
3452 });
3453 });
3454}
3455function sendEmailVerification$1(auth, request) {
3456 return __awaiter(this, void 0, void 0, function () {
3457 return __generator(this, function (_a) {
3458 return [2 /*return*/, sendOobCode(auth, request)];
3459 });
3460 });
3461}
3462function sendPasswordResetEmail$1(auth, request) {
3463 return __awaiter(this, void 0, void 0, function () {
3464 return __generator(this, function (_a) {
3465 return [2 /*return*/, sendOobCode(auth, request)];
3466 });
3467 });
3468}
3469function sendSignInLinkToEmail$1(auth, request) {
3470 return __awaiter(this, void 0, void 0, function () {
3471 return __generator(this, function (_a) {
3472 return [2 /*return*/, sendOobCode(auth, request)];
3473 });
3474 });
3475}
3476function verifyAndChangeEmail(auth, request) {
3477 return __awaiter(this, void 0, void 0, function () {
3478 return __generator(this, function (_a) {
3479 return [2 /*return*/, sendOobCode(auth, request)];
3480 });
3481 });
3482}
3483
3484/**
3485 * @license
3486 * Copyright 2020 Google LLC
3487 *
3488 * Licensed under the Apache License, Version 2.0 (the "License");
3489 * you may not use this file except in compliance with the License.
3490 * You may obtain a copy of the License at
3491 *
3492 * http://www.apache.org/licenses/LICENSE-2.0
3493 *
3494 * Unless required by applicable law or agreed to in writing, software
3495 * distributed under the License is distributed on an "AS IS" BASIS,
3496 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3497 * See the License for the specific language governing permissions and
3498 * limitations under the License.
3499 */
3500function signInWithEmailLink$1(auth, request) {
3501 return __awaiter(this, void 0, void 0, function () {
3502 return __generator(this, function (_a) {
3503 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithEmailLink" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
3504 });
3505 });
3506}
3507function signInWithEmailLinkForLinking(auth, request) {
3508 return __awaiter(this, void 0, void 0, function () {
3509 return __generator(this, function (_a) {
3510 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithEmailLink" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
3511 });
3512 });
3513}
3514
3515/**
3516 * @license
3517 * Copyright 2020 Google LLC
3518 *
3519 * Licensed under the Apache License, Version 2.0 (the "License");
3520 * you may not use this file except in compliance with the License.
3521 * You may obtain a copy of the License at
3522 *
3523 * http://www.apache.org/licenses/LICENSE-2.0
3524 *
3525 * Unless required by applicable law or agreed to in writing, software
3526 * distributed under the License is distributed on an "AS IS" BASIS,
3527 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3528 * See the License for the specific language governing permissions and
3529 * limitations under the License.
3530 */
3531/**
3532 * Interface that represents the credentials returned by {@link EmailAuthProvider} for
3533 * {@link ProviderId}.PASSWORD
3534 *
3535 * @remarks
3536 * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
3537 * {@link SignInMethod}.EMAIL_LINK.
3538 *
3539 * @public
3540 */
3541var EmailAuthCredential = /** @class */ (function (_super) {
3542 __extends(EmailAuthCredential, _super);
3543 /** @internal */
3544 function EmailAuthCredential(
3545 /** @internal */
3546 _email,
3547 /** @internal */
3548 _password, signInMethod,
3549 /** @internal */
3550 _tenantId) {
3551 if (_tenantId === void 0) { _tenantId = null; }
3552 var _this = _super.call(this, "password" /* PASSWORD */, signInMethod) || this;
3553 _this._email = _email;
3554 _this._password = _password;
3555 _this._tenantId = _tenantId;
3556 return _this;
3557 }
3558 /** @internal */
3559 EmailAuthCredential._fromEmailAndPassword = function (email, password) {
3560 return new EmailAuthCredential(email, password, "password" /* EMAIL_PASSWORD */);
3561 };
3562 /** @internal */
3563 EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
3564 if (tenantId === void 0) { tenantId = null; }
3565 return new EmailAuthCredential(email, oobCode, "emailLink" /* EMAIL_LINK */, tenantId);
3566 };
3567 /** {@inheritdoc AuthCredential.toJSON} */
3568 EmailAuthCredential.prototype.toJSON = function () {
3569 return {
3570 email: this._email,
3571 password: this._password,
3572 signInMethod: this.signInMethod,
3573 tenantId: this._tenantId
3574 };
3575 };
3576 /**
3577 * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
3578 *
3579 * @param json - Either `object` or the stringified representation of the object. When string is
3580 * provided, `JSON.parse` would be called first.
3581 *
3582 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
3583 */
3584 EmailAuthCredential.fromJSON = function (json) {
3585 var obj = typeof json === 'string' ? JSON.parse(json) : json;
3586 if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
3587 if (obj.signInMethod === "password" /* EMAIL_PASSWORD */) {
3588 return this._fromEmailAndPassword(obj.email, obj.password);
3589 }
3590 else if (obj.signInMethod === "emailLink" /* EMAIL_LINK */) {
3591 return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
3592 }
3593 }
3594 return null;
3595 };
3596 /** @internal */
3597 EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
3598 return __awaiter(this, void 0, void 0, function () {
3599 return __generator(this, function (_a) {
3600 switch (this.signInMethod) {
3601 case "password" /* EMAIL_PASSWORD */:
3602 return [2 /*return*/, signInWithPassword(auth, {
3603 returnSecureToken: true,
3604 email: this._email,
3605 password: this._password
3606 })];
3607 case "emailLink" /* EMAIL_LINK */:
3608 return [2 /*return*/, signInWithEmailLink$1(auth, {
3609 email: this._email,
3610 oobCode: this._password
3611 })];
3612 default:
3613 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
3614 }
3615 return [2 /*return*/];
3616 });
3617 });
3618 };
3619 /** @internal */
3620 EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
3621 return __awaiter(this, void 0, void 0, function () {
3622 return __generator(this, function (_a) {
3623 switch (this.signInMethod) {
3624 case "password" /* EMAIL_PASSWORD */:
3625 return [2 /*return*/, updateEmailPassword(auth, {
3626 idToken: idToken,
3627 returnSecureToken: true,
3628 email: this._email,
3629 password: this._password
3630 })];
3631 case "emailLink" /* EMAIL_LINK */:
3632 return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
3633 idToken: idToken,
3634 email: this._email,
3635 oobCode: this._password
3636 })];
3637 default:
3638 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
3639 }
3640 return [2 /*return*/];
3641 });
3642 });
3643 };
3644 /** @internal */
3645 EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
3646 return this._getIdTokenResponse(auth);
3647 };
3648 return EmailAuthCredential;
3649}(AuthCredential));
3650
3651/**
3652 * @license
3653 * Copyright 2020 Google LLC
3654 *
3655 * Licensed under the Apache License, Version 2.0 (the "License");
3656 * you may not use this file except in compliance with the License.
3657 * You may obtain a copy of the License at
3658 *
3659 * http://www.apache.org/licenses/LICENSE-2.0
3660 *
3661 * Unless required by applicable law or agreed to in writing, software
3662 * distributed under the License is distributed on an "AS IS" BASIS,
3663 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3664 * See the License for the specific language governing permissions and
3665 * limitations under the License.
3666 */
3667function signInWithIdp(auth, request) {
3668 return __awaiter(this, void 0, void 0, function () {
3669 return __generator(this, function (_a) {
3670 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithIdp" /* SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
3671 });
3672 });
3673}
3674
3675/**
3676 * @license
3677 * Copyright 2020 Google LLC
3678 *
3679 * Licensed under the Apache License, Version 2.0 (the "License");
3680 * you may not use this file except in compliance with the License.
3681 * You may obtain a copy of the License at
3682 *
3683 * http://www.apache.org/licenses/LICENSE-2.0
3684 *
3685 * Unless required by applicable law or agreed to in writing, software
3686 * distributed under the License is distributed on an "AS IS" BASIS,
3687 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3688 * See the License for the specific language governing permissions and
3689 * limitations under the License.
3690 */
3691var IDP_REQUEST_URI$1 = 'http://localhost';
3692/**
3693 * Represents the OAuth credentials returned by an {@link OAuthProvider}.
3694 *
3695 * @remarks
3696 * Implementations specify the details about each auth provider's credential requirements.
3697 *
3698 * @public
3699 */
3700var OAuthCredential = /** @class */ (function (_super) {
3701 __extends(OAuthCredential, _super);
3702 function OAuthCredential() {
3703 var _this = _super !== null && _super.apply(this, arguments) || this;
3704 _this.pendingToken = null;
3705 return _this;
3706 }
3707 /** @internal */
3708 OAuthCredential._fromParams = function (params) {
3709 var cred = new OAuthCredential(params.providerId, params.signInMethod);
3710 if (params.idToken || params.accessToken) {
3711 // OAuth 2 and either ID token or access token.
3712 if (params.idToken) {
3713 cred.idToken = params.idToken;
3714 }
3715 if (params.accessToken) {
3716 cred.accessToken = params.accessToken;
3717 }
3718 // Add nonce if available and no pendingToken is present.
3719 if (params.nonce && !params.pendingToken) {
3720 cred.nonce = params.nonce;
3721 }
3722 if (params.pendingToken) {
3723 cred.pendingToken = params.pendingToken;
3724 }
3725 }
3726 else if (params.oauthToken && params.oauthTokenSecret) {
3727 // OAuth 1 and OAuth token with token secret
3728 cred.accessToken = params.oauthToken;
3729 cred.secret = params.oauthTokenSecret;
3730 }
3731 else {
3732 _fail("argument-error" /* ARGUMENT_ERROR */);
3733 }
3734 return cred;
3735 };
3736 /** {@inheritdoc AuthCredential.toJSON} */
3737 OAuthCredential.prototype.toJSON = function () {
3738 return {
3739 idToken: this.idToken,
3740 accessToken: this.accessToken,
3741 secret: this.secret,
3742 nonce: this.nonce,
3743 pendingToken: this.pendingToken,
3744 providerId: this.providerId,
3745 signInMethod: this.signInMethod
3746 };
3747 };
3748 /**
3749 * Static method to deserialize a JSON representation of an object into an
3750 * {@link AuthCredential}.
3751 *
3752 * @param json - Input can be either Object or the stringified representation of the object.
3753 * When string is provided, JSON.parse would be called first.
3754 *
3755 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
3756 */
3757 OAuthCredential.fromJSON = function (json) {
3758 var obj = typeof json === 'string' ? JSON.parse(json) : json;
3759 var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = __rest(obj, ["providerId", "signInMethod"]);
3760 if (!providerId || !signInMethod) {
3761 return null;
3762 }
3763 var cred = new OAuthCredential(providerId, signInMethod);
3764 cred.idToken = rest.idToken || undefined;
3765 cred.accessToken = rest.accessToken || undefined;
3766 cred.secret = rest.secret;
3767 cred.nonce = rest.nonce;
3768 cred.pendingToken = rest.pendingToken || null;
3769 return cred;
3770 };
3771 /** @internal */
3772 OAuthCredential.prototype._getIdTokenResponse = function (auth) {
3773 var request = this.buildRequest();
3774 return signInWithIdp(auth, request);
3775 };
3776 /** @internal */
3777 OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
3778 var request = this.buildRequest();
3779 request.idToken = idToken;
3780 return signInWithIdp(auth, request);
3781 };
3782 /** @internal */
3783 OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
3784 var request = this.buildRequest();
3785 request.autoCreate = false;
3786 return signInWithIdp(auth, request);
3787 };
3788 OAuthCredential.prototype.buildRequest = function () {
3789 var request = {
3790 requestUri: IDP_REQUEST_URI$1,
3791 returnSecureToken: true
3792 };
3793 if (this.pendingToken) {
3794 request.pendingToken = this.pendingToken;
3795 }
3796 else {
3797 var postBody = {};
3798 if (this.idToken) {
3799 postBody['id_token'] = this.idToken;
3800 }
3801 if (this.accessToken) {
3802 postBody['access_token'] = this.accessToken;
3803 }
3804 if (this.secret) {
3805 postBody['oauth_token_secret'] = this.secret;
3806 }
3807 postBody['providerId'] = this.providerId;
3808 if (this.nonce && !this.pendingToken) {
3809 postBody['nonce'] = this.nonce;
3810 }
3811 request.postBody = querystring(postBody);
3812 }
3813 return request;
3814 };
3815 return OAuthCredential;
3816}(AuthCredential));
3817
3818/**
3819 * @license
3820 * Copyright 2020 Google LLC
3821 *
3822 * Licensed under the Apache License, Version 2.0 (the "License");
3823 * you may not use this file except in compliance with the License.
3824 * You may obtain a copy of the License at
3825 *
3826 * http://www.apache.org/licenses/LICENSE-2.0
3827 *
3828 * Unless required by applicable law or agreed to in writing, software
3829 * distributed under the License is distributed on an "AS IS" BASIS,
3830 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3831 * See the License for the specific language governing permissions and
3832 * limitations under the License.
3833 */
3834var _a;
3835function sendPhoneVerificationCode(auth, request) {
3836 return __awaiter(this, void 0, void 0, function () {
3837 return __generator(this, function (_a) {
3838 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:sendVerificationCode" /* SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request))];
3839 });
3840 });
3841}
3842function signInWithPhoneNumber$1(auth, request) {
3843 return __awaiter(this, void 0, void 0, function () {
3844 return __generator(this, function (_a) {
3845 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
3846 });
3847 });
3848}
3849function linkWithPhoneNumber$1(auth, request) {
3850 return __awaiter(this, void 0, void 0, function () {
3851 var response;
3852 return __generator(this, function (_a) {
3853 switch (_a.label) {
3854 case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
3855 case 1:
3856 response = _a.sent();
3857 if (response.temporaryProof) {
3858 throw _makeTaggedError(auth, "account-exists-with-different-credential" /* NEED_CONFIRMATION */, response);
3859 }
3860 return [2 /*return*/, response];
3861 }
3862 });
3863 });
3864}
3865var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
3866 _a["USER_NOT_FOUND" /* USER_NOT_FOUND */] = "user-not-found" /* USER_DELETED */,
3867 _a);
3868function verifyPhoneNumberForExisting(auth, request) {
3869 return __awaiter(this, void 0, void 0, function () {
3870 var apiRequest;
3871 return __generator(this, function (_a) {
3872 apiRequest = __assign(__assign({}, request), { operation: 'REAUTH' });
3873 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_)];
3874 });
3875 });
3876}
3877
3878/**
3879 * @license
3880 * Copyright 2020 Google LLC
3881 *
3882 * Licensed under the Apache License, Version 2.0 (the "License");
3883 * you may not use this file except in compliance with the License.
3884 * You may obtain a copy of the License at
3885 *
3886 * http://www.apache.org/licenses/LICENSE-2.0
3887 *
3888 * Unless required by applicable law or agreed to in writing, software
3889 * distributed under the License is distributed on an "AS IS" BASIS,
3890 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3891 * See the License for the specific language governing permissions and
3892 * limitations under the License.
3893 */
3894/**
3895 * Represents the credentials returned by {@link PhoneAuthProvider}.
3896 *
3897 * @public
3898 */
3899var PhoneAuthCredential = /** @class */ (function (_super) {
3900 __extends(PhoneAuthCredential, _super);
3901 function PhoneAuthCredential(params) {
3902 var _this = _super.call(this, "phone" /* PHONE */, "phone" /* PHONE */) || this;
3903 _this.params = params;
3904 return _this;
3905 }
3906 /** @internal */
3907 PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
3908 return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
3909 };
3910 /** @internal */
3911 PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
3912 return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
3913 };
3914 /** @internal */
3915 PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
3916 return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
3917 };
3918 /** @internal */
3919 PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
3920 return linkWithPhoneNumber$1(auth, __assign({ idToken: idToken }, this._makeVerificationRequest()));
3921 };
3922 /** @internal */
3923 PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
3924 return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
3925 };
3926 /** @internal */
3927 PhoneAuthCredential.prototype._makeVerificationRequest = function () {
3928 var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
3929 if (temporaryProof && phoneNumber) {
3930 return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
3931 }
3932 return {
3933 sessionInfo: verificationId,
3934 code: verificationCode
3935 };
3936 };
3937 /** {@inheritdoc AuthCredential.toJSON} */
3938 PhoneAuthCredential.prototype.toJSON = function () {
3939 var obj = {
3940 providerId: this.providerId
3941 };
3942 if (this.params.phoneNumber) {
3943 obj.phoneNumber = this.params.phoneNumber;
3944 }
3945 if (this.params.temporaryProof) {
3946 obj.temporaryProof = this.params.temporaryProof;
3947 }
3948 if (this.params.verificationCode) {
3949 obj.verificationCode = this.params.verificationCode;
3950 }
3951 if (this.params.verificationId) {
3952 obj.verificationId = this.params.verificationId;
3953 }
3954 return obj;
3955 };
3956 /** Generates a phone credential based on a plain object or a JSON string. */
3957 PhoneAuthCredential.fromJSON = function (json) {
3958 if (typeof json === 'string') {
3959 json = JSON.parse(json);
3960 }
3961 var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
3962 if (!verificationCode &&
3963 !verificationId &&
3964 !phoneNumber &&
3965 !temporaryProof) {
3966 return null;
3967 }
3968 return new PhoneAuthCredential({
3969 verificationId: verificationId,
3970 verificationCode: verificationCode,
3971 phoneNumber: phoneNumber,
3972 temporaryProof: temporaryProof
3973 });
3974 };
3975 return PhoneAuthCredential;
3976}(AuthCredential));
3977
3978/**
3979 * @license
3980 * Copyright 2020 Google LLC
3981 *
3982 * Licensed under the Apache License, Version 2.0 (the "License");
3983 * you may not use this file except in compliance with the License.
3984 * You may obtain a copy of the License at
3985 *
3986 * http://www.apache.org/licenses/LICENSE-2.0
3987 *
3988 * Unless required by applicable law or agreed to in writing, software
3989 * distributed under the License is distributed on an "AS IS" BASIS,
3990 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3991 * See the License for the specific language governing permissions and
3992 * limitations under the License.
3993 */
3994/**
3995 * Maps the mode string in action code URL to Action Code Info operation.
3996 *
3997 * @param mode
3998 */
3999function parseMode(mode) {
4000 switch (mode) {
4001 case 'recoverEmail':
4002 return "RECOVER_EMAIL" /* RECOVER_EMAIL */;
4003 case 'resetPassword':
4004 return "PASSWORD_RESET" /* PASSWORD_RESET */;
4005 case 'signIn':
4006 return "EMAIL_SIGNIN" /* EMAIL_SIGNIN */;
4007 case 'verifyEmail':
4008 return "VERIFY_EMAIL" /* VERIFY_EMAIL */;
4009 case 'verifyAndChangeEmail':
4010 return "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */;
4011 case 'revertSecondFactorAddition':
4012 return "REVERT_SECOND_FACTOR_ADDITION" /* REVERT_SECOND_FACTOR_ADDITION */;
4013 default:
4014 return null;
4015 }
4016}
4017/**
4018 * Helper to parse FDL links
4019 *
4020 * @param url
4021 */
4022function parseDeepLink(url) {
4023 var link = querystringDecode(extractQuerystring(url))['link'];
4024 // Double link case (automatic redirect).
4025 var doubleDeepLink = link
4026 ? querystringDecode(extractQuerystring(link))['deep_link_id']
4027 : null;
4028 // iOS custom scheme links.
4029 var iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
4030 var iOSDoubleDeepLink = iOSDeepLink
4031 ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
4032 : null;
4033 return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
4034}
4035/**
4036 * A utility class to parse email action URLs such as password reset, email verification,
4037 * email link sign in, etc.
4038 *
4039 * @public
4040 */
4041var ActionCodeURL = /** @class */ (function () {
4042 /**
4043 * @param actionLink - The link from which to extract the URL.
4044 * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
4045 *
4046 * @internal
4047 */
4048 function ActionCodeURL(actionLink) {
4049 var _a, _b, _c, _d, _e, _f;
4050 var searchParams = querystringDecode(extractQuerystring(actionLink));
4051 var apiKey = (_a = searchParams["apiKey" /* API_KEY */]) !== null && _a !== void 0 ? _a : null;
4052 var code = (_b = searchParams["oobCode" /* CODE */]) !== null && _b !== void 0 ? _b : null;
4053 var operation = parseMode((_c = searchParams["mode" /* MODE */]) !== null && _c !== void 0 ? _c : null);
4054 // Validate API key, code and mode.
4055 _assert(apiKey && code && operation, "argument-error" /* ARGUMENT_ERROR */);
4056 this.apiKey = apiKey;
4057 this.operation = operation;
4058 this.code = code;
4059 this.continueUrl = (_d = searchParams["continueUrl" /* CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
4060 this.languageCode = (_e = searchParams["languageCode" /* LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
4061 this.tenantId = (_f = searchParams["tenantId" /* TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
4062 }
4063 /**
4064 * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
4065 * otherwise returns null.
4066 *
4067 * @param link - The email action link string.
4068 * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
4069 *
4070 * @public
4071 */
4072 ActionCodeURL.parseLink = function (link) {
4073 var actionLink = parseDeepLink(link);
4074 try {
4075 return new ActionCodeURL(actionLink);
4076 }
4077 catch (_a) {
4078 return null;
4079 }
4080 };
4081 return ActionCodeURL;
4082}());
4083/**
4084 * Parses the email action link string and returns an {@link ActionCodeURL} if
4085 * the link is valid, otherwise returns null.
4086 *
4087 * @public
4088 */
4089function parseActionCodeURL(link) {
4090 return ActionCodeURL.parseLink(link);
4091}
4092
4093/**
4094 * @license
4095 * Copyright 2020 Google LLC
4096 *
4097 * Licensed under the Apache License, Version 2.0 (the "License");
4098 * you may not use this file except in compliance with the License.
4099 * You may obtain a copy of the License at
4100 *
4101 * http://www.apache.org/licenses/LICENSE-2.0
4102 *
4103 * Unless required by applicable law or agreed to in writing, software
4104 * distributed under the License is distributed on an "AS IS" BASIS,
4105 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4106 * See the License for the specific language governing permissions and
4107 * limitations under the License.
4108 */
4109/**
4110 * Provider for generating {@link EmailAuthCredential}.
4111 *
4112 * @public
4113 */
4114var EmailAuthProvider = /** @class */ (function () {
4115 function EmailAuthProvider() {
4116 /**
4117 * Always set to {@link ProviderId}.PASSWORD, even for email link.
4118 */
4119 this.providerId = EmailAuthProvider.PROVIDER_ID;
4120 }
4121 /**
4122 * Initialize an {@link AuthCredential} using an email and password.
4123 *
4124 * @example
4125 * ```javascript
4126 * const authCredential = EmailAuthProvider.credential(email, password);
4127 * const userCredential = await signInWithCredential(auth, authCredential);
4128 * ```
4129 *
4130 * @example
4131 * ```javascript
4132 * const userCredential = await signInWithEmailAndPassword(auth, email, password);
4133 * ```
4134 *
4135 * @param email - Email address.
4136 * @param password - User account password.
4137 * @returns The auth provider credential.
4138 */
4139 EmailAuthProvider.credential = function (email, password) {
4140 return EmailAuthCredential._fromEmailAndPassword(email, password);
4141 };
4142 /**
4143 * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
4144 * email link operation.
4145 *
4146 * @example
4147 * ```javascript
4148 * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
4149 * const userCredential = await signInWithCredential(auth, authCredential);
4150 * ```
4151 *
4152 * @example
4153 * ```javascript
4154 * await sendSignInLinkToEmail(auth, email);
4155 * // Obtain emailLink from user.
4156 * const userCredential = await signInWithEmailLink(auth, email, emailLink);
4157 * ```
4158 *
4159 * @param auth - The {@link Auth} instance used to verify the link.
4160 * @param email - Email address.
4161 * @param emailLink - Sign-in email link.
4162 * @returns - The auth provider credential.
4163 */
4164 EmailAuthProvider.credentialWithLink = function (email, emailLink) {
4165 var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
4166 _assert(actionCodeUrl, "argument-error" /* ARGUMENT_ERROR */);
4167 return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
4168 };
4169 /**
4170 * Always set to {@link ProviderId}.PASSWORD, even for email link.
4171 */
4172 EmailAuthProvider.PROVIDER_ID = "password" /* PASSWORD */;
4173 /**
4174 * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
4175 */
4176 EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* EMAIL_PASSWORD */;
4177 /**
4178 * Always set to {@link SignInMethod}.EMAIL_LINK.
4179 */
4180 EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* EMAIL_LINK */;
4181 return EmailAuthProvider;
4182}());
4183
4184/**
4185 * @license
4186 * Copyright 2020 Google LLC
4187 *
4188 * Licensed under the Apache License, Version 2.0 (the "License");
4189 * you may not use this file except in compliance with the License.
4190 * You may obtain a copy of the License at
4191 *
4192 * http://www.apache.org/licenses/LICENSE-2.0
4193 *
4194 * Unless required by applicable law or agreed to in writing, software
4195 * distributed under the License is distributed on an "AS IS" BASIS,
4196 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4197 * See the License for the specific language governing permissions and
4198 * limitations under the License.
4199 */
4200/**
4201 * The base class for all Federated providers (OAuth (including OIDC), SAML).
4202 *
4203 * This class is not meant to be instantiated directly.
4204 *
4205 * @public
4206 */
4207var FederatedAuthProvider = /** @class */ (function () {
4208 /**
4209 * Constructor for generic OAuth providers.
4210 *
4211 * @param providerId - Provider for which credentials should be generated.
4212 */
4213 function FederatedAuthProvider(providerId) {
4214 this.providerId = providerId;
4215 /** @internal */
4216 this.defaultLanguageCode = null;
4217 /** @internal */
4218 this.customParameters = {};
4219 }
4220 /**
4221 * Set the language gode.
4222 *
4223 * @param languageCode - language code
4224 */
4225 FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
4226 this.defaultLanguageCode = languageCode;
4227 };
4228 /**
4229 * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
4230 * operations.
4231 *
4232 * @remarks
4233 * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
4234 * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
4235 *
4236 * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
4237 */
4238 FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
4239 this.customParameters = customOAuthParameters;
4240 return this;
4241 };
4242 /**
4243 * Retrieve the current list of {@link CustomParameters}.
4244 */
4245 FederatedAuthProvider.prototype.getCustomParameters = function () {
4246 return this.customParameters;
4247 };
4248 return FederatedAuthProvider;
4249}());
4250
4251/**
4252 * @license
4253 * Copyright 2019 Google LLC
4254 *
4255 * Licensed under the Apache License, Version 2.0 (the "License");
4256 * you may not use this file except in compliance with the License.
4257 * You may obtain a copy of the License at
4258 *
4259 * http://www.apache.org/licenses/LICENSE-2.0
4260 *
4261 * Unless required by applicable law or agreed to in writing, software
4262 * distributed under the License is distributed on an "AS IS" BASIS,
4263 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4264 * See the License for the specific language governing permissions and
4265 * limitations under the License.
4266 */
4267/**
4268 * Common code to all OAuth providers. This is separate from the
4269 * {@link OAuthProvider} so that child providers (like
4270 * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
4271 * Instead, they rely on a static `credential` method.
4272 */
4273var BaseOAuthProvider = /** @class */ (function (_super) {
4274 __extends(BaseOAuthProvider, _super);
4275 function BaseOAuthProvider() {
4276 var _this = _super !== null && _super.apply(this, arguments) || this;
4277 /** @internal */
4278 _this.scopes = [];
4279 return _this;
4280 }
4281 /**
4282 * Add an OAuth scope to the credential.
4283 *
4284 * @param scope - Provider OAuth scope to add.
4285 */
4286 BaseOAuthProvider.prototype.addScope = function (scope) {
4287 // If not already added, add scope to list.
4288 if (!this.scopes.includes(scope)) {
4289 this.scopes.push(scope);
4290 }
4291 return this;
4292 };
4293 /**
4294 * Retrieve the current list of OAuth scopes.
4295 */
4296 BaseOAuthProvider.prototype.getScopes = function () {
4297 return __spreadArray([], this.scopes);
4298 };
4299 return BaseOAuthProvider;
4300}(FederatedAuthProvider));
4301/**
4302 * Provider for generating generic {@link OAuthCredential}.
4303 *
4304 * @example
4305 * ```javascript
4306 * // Sign in using a redirect.
4307 * const provider = new OAuthProvider('google.com');
4308 * // Start a sign in process for an unauthenticated user.
4309 * provider.addScope('profile');
4310 * provider.addScope('email');
4311 * await signInWithRedirect(auth, provider);
4312 * // This will trigger a full page redirect away from your app
4313 *
4314 * // After returning from the redirect when your app initializes you can obtain the result
4315 * const result = await getRedirectResult(auth);
4316 * if (result) {
4317 * // This is the signed-in user
4318 * const user = result.user;
4319 * // This gives you a OAuth Access Token for the provider.
4320 * const credential = provider.credentialFromResult(auth, result);
4321 * const token = credential.accessToken;
4322 * }
4323 * ```
4324 *
4325 * @example
4326 * ```javascript
4327 * // Sign in using a popup.
4328 * const provider = new OAuthProvider('google.com');
4329 * provider.addScope('profile');
4330 * provider.addScope('email');
4331 * const result = await signInWithPopup(auth, provider);
4332 *
4333 * // The signed-in user info.
4334 * const user = result.user;
4335 * // This gives you a OAuth Access Token for the provider.
4336 * const credential = provider.credentialFromResult(auth, result);
4337 * const token = credential.accessToken;
4338 * ```
4339 * @public
4340 */
4341var OAuthProvider = /** @class */ (function (_super) {
4342 __extends(OAuthProvider, _super);
4343 function OAuthProvider() {
4344 return _super !== null && _super.apply(this, arguments) || this;
4345 }
4346 /**
4347 * Creates an {@link OAuthCredential} from a JSON string or a plain object.
4348 * @param json - A plain object or a JSON string
4349 */
4350 OAuthProvider.credentialFromJSON = function (json) {
4351 var obj = typeof json === 'string' ? JSON.parse(json) : json;
4352 _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* ARGUMENT_ERROR */);
4353 return OAuthCredential._fromParams(obj);
4354 };
4355 /**
4356 * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
4357 *
4358 * @remarks
4359 * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
4360 * the raw nonce must match the nonce field in the ID token.
4361 *
4362 * @example
4363 * ```javascript
4364 * // `googleUser` from the onsuccess Google Sign In callback.
4365 * // Initialize a generate OAuth provider with a `google.com` providerId.
4366 * const provider = new OAuthProvider('google.com');
4367 * const credential = provider.credential({
4368 * idToken: googleUser.getAuthResponse().id_token,
4369 * });
4370 * const result = await signInWithCredential(credential);
4371 * ```
4372 *
4373 * @param params - Either the options object containing the ID token, access token and raw nonce
4374 * or the ID token string.
4375 */
4376 OAuthProvider.prototype.credential = function (params) {
4377 return this._credential(__assign(__assign({}, params), { nonce: params.rawNonce }));
4378 };
4379 /** An internal credential method that accepts more permissive options */
4380 OAuthProvider.prototype._credential = function (params) {
4381 _assert(params.idToken || params.accessToken, "argument-error" /* ARGUMENT_ERROR */);
4382 // For OAuthCredential, sign in method is same as providerId.
4383 return OAuthCredential._fromParams(__assign(__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
4384 };
4385 /**
4386 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4387 *
4388 * @param userCredential - The user credential.
4389 */
4390 OAuthProvider.credentialFromResult = function (userCredential) {
4391 return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
4392 };
4393 /**
4394 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4395 * thrown during a sign-in, link, or reauthenticate operation.
4396 *
4397 * @param userCredential - The user credential.
4398 */
4399 OAuthProvider.credentialFromError = function (error) {
4400 return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
4401 };
4402 OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
4403 var tokenResponse = _a._tokenResponse;
4404 if (!tokenResponse) {
4405 return null;
4406 }
4407 var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
4408 if (!oauthAccessToken &&
4409 !oauthTokenSecret &&
4410 !oauthIdToken &&
4411 !pendingToken) {
4412 return null;
4413 }
4414 if (!providerId) {
4415 return null;
4416 }
4417 try {
4418 return new OAuthProvider(providerId)._credential({
4419 idToken: oauthIdToken,
4420 accessToken: oauthAccessToken,
4421 nonce: nonce,
4422 pendingToken: pendingToken
4423 });
4424 }
4425 catch (e) {
4426 return null;
4427 }
4428 };
4429 return OAuthProvider;
4430}(BaseOAuthProvider));
4431
4432/**
4433 * @license
4434 * Copyright 2020 Google LLC
4435 *
4436 * Licensed under the Apache License, Version 2.0 (the "License");
4437 * you may not use this file except in compliance with the License.
4438 * You may obtain a copy of the License at
4439 *
4440 * http://www.apache.org/licenses/LICENSE-2.0
4441 *
4442 * Unless required by applicable law or agreed to in writing, software
4443 * distributed under the License is distributed on an "AS IS" BASIS,
4444 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4445 * See the License for the specific language governing permissions and
4446 * limitations under the License.
4447 */
4448/**
4449 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
4450 *
4451 * @example
4452 * ```javascript
4453 * // Sign in using a redirect.
4454 * const provider = new FacebookAuthProvider();
4455 * // Start a sign in process for an unauthenticated user.
4456 * provider.addScope('user_birthday');
4457 * await signInWithRedirect(auth, provider);
4458 * // This will trigger a full page redirect away from your app
4459 *
4460 * // After returning from the redirect when your app initializes you can obtain the result
4461 * const result = await getRedirectResult(auth);
4462 * if (result) {
4463 * // This is the signed-in user
4464 * const user = result.user;
4465 * // This gives you a Facebook Access Token.
4466 * const credential = FacebookAuthProvider.credentialFromResult(result);
4467 * const token = credential.accessToken;
4468 * }
4469 * ```
4470 *
4471 * @example
4472 * ```javascript
4473 * // Sign in using a popup.
4474 * const provider = new FacebookAuthProvider();
4475 * provider.addScope('user_birthday');
4476 * const result = await signInWithPopup(auth, provider);
4477 *
4478 * // The signed-in user info.
4479 * const user = result.user;
4480 * // This gives you a Facebook Access Token.
4481 * const credential = FacebookAuthProvider.credentialFromResult(result);
4482 * const token = credential.accessToken;
4483 * ```
4484 *
4485 * @public
4486 */
4487var FacebookAuthProvider = /** @class */ (function (_super) {
4488 __extends(FacebookAuthProvider, _super);
4489 function FacebookAuthProvider() {
4490 return _super.call(this, "facebook.com" /* FACEBOOK */) || this;
4491 }
4492 /**
4493 * Creates a credential for Facebook.
4494 *
4495 * @example
4496 * ```javascript
4497 * // `event` from the Facebook auth.authResponseChange callback.
4498 * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
4499 * const result = await signInWithCredential(credential);
4500 * ```
4501 *
4502 * @param accessToken - Facebook access token.
4503 */
4504 FacebookAuthProvider.credential = function (accessToken) {
4505 return OAuthCredential._fromParams({
4506 providerId: FacebookAuthProvider.PROVIDER_ID,
4507 signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
4508 accessToken: accessToken
4509 });
4510 };
4511 /**
4512 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4513 *
4514 * @param userCredential - The user credential.
4515 */
4516 FacebookAuthProvider.credentialFromResult = function (userCredential) {
4517 return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
4518 };
4519 /**
4520 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4521 * thrown during a sign-in, link, or reauthenticate operation.
4522 *
4523 * @param userCredential - The user credential.
4524 */
4525 FacebookAuthProvider.credentialFromError = function (error) {
4526 return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
4527 };
4528 FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
4529 var tokenResponse = _a._tokenResponse;
4530 if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
4531 return null;
4532 }
4533 if (!tokenResponse.oauthAccessToken) {
4534 return null;
4535 }
4536 try {
4537 return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
4538 }
4539 catch (_b) {
4540 return null;
4541 }
4542 };
4543 /** Always set to {@link SignInMethod}.FACEBOOK. */
4544 FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* FACEBOOK */;
4545 /** Always set to {@link ProviderId}.FACEBOOK. */
4546 FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* FACEBOOK */;
4547 return FacebookAuthProvider;
4548}(BaseOAuthProvider));
4549
4550/**
4551 * @license
4552 * Copyright 2020 Google LLC
4553 *
4554 * Licensed under the Apache License, Version 2.0 (the "License");
4555 * you may not use this file except in compliance with the License.
4556 * You may obtain a copy of the License at
4557 *
4558 * http://www.apache.org/licenses/LICENSE-2.0
4559 *
4560 * Unless required by applicable law or agreed to in writing, software
4561 * distributed under the License is distributed on an "AS IS" BASIS,
4562 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4563 * See the License for the specific language governing permissions and
4564 * limitations under the License.
4565 */
4566/**
4567 * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
4568 *
4569 * @example
4570 * ```javascript
4571 * // Sign in using a redirect.
4572 * const provider = new GoogleAuthProvider();
4573 * // Start a sign in process for an unauthenticated user.
4574 * provider.addScope('profile');
4575 * provider.addScope('email');
4576 * await signInWithRedirect(auth, provider);
4577 * // This will trigger a full page redirect away from your app
4578 *
4579 * // After returning from the redirect when your app initializes you can obtain the result
4580 * const result = await getRedirectResult(auth);
4581 * if (result) {
4582 * // This is the signed-in user
4583 * const user = result.user;
4584 * // This gives you a Google Access Token.
4585 * const credential = GoogleAuthProvider.credentialFromResult(result);
4586 * const token = credential.accessToken;
4587 * }
4588 * ```
4589 *
4590 * @example
4591 * ```javascript
4592 * // Sign in using a popup.
4593 * const provider = new GoogleAuthProvider();
4594 * provider.addScope('profile');
4595 * provider.addScope('email');
4596 * const result = await signInWithPopup(auth, provider);
4597 *
4598 * // The signed-in user info.
4599 * const user = result.user;
4600 * // This gives you a Google Access Token.
4601 * const credential = GoogleAuthProvider.credentialFromResult(result);
4602 * const token = credential.accessToken;
4603 * ```
4604 *
4605 * @public
4606 */
4607var GoogleAuthProvider = /** @class */ (function (_super) {
4608 __extends(GoogleAuthProvider, _super);
4609 function GoogleAuthProvider() {
4610 var _this = _super.call(this, "google.com" /* GOOGLE */) || this;
4611 _this.addScope('profile');
4612 return _this;
4613 }
4614 /**
4615 * Creates a credential for Google. At least one of ID token and access token is required.
4616 *
4617 * @example
4618 * ```javascript
4619 * // \`googleUser\` from the onsuccess Google Sign In callback.
4620 * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
4621 * const result = await signInWithCredential(credential);
4622 * ```
4623 *
4624 * @param idToken - Google ID token.
4625 * @param accessToken - Google access token.
4626 */
4627 GoogleAuthProvider.credential = function (idToken, accessToken) {
4628 return OAuthCredential._fromParams({
4629 providerId: GoogleAuthProvider.PROVIDER_ID,
4630 signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
4631 idToken: idToken,
4632 accessToken: accessToken
4633 });
4634 };
4635 /**
4636 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4637 *
4638 * @param userCredential - The user credential.
4639 */
4640 GoogleAuthProvider.credentialFromResult = function (userCredential) {
4641 return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
4642 };
4643 /**
4644 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4645 * thrown during a sign-in, link, or reauthenticate operation.
4646 *
4647 * @param userCredential - The user credential.
4648 */
4649 GoogleAuthProvider.credentialFromError = function (error) {
4650 return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
4651 };
4652 GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
4653 var tokenResponse = _a._tokenResponse;
4654 if (!tokenResponse) {
4655 return null;
4656 }
4657 var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
4658 if (!oauthIdToken && !oauthAccessToken) {
4659 // This could be an oauth 1 credential or a phone credential
4660 return null;
4661 }
4662 try {
4663 return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
4664 }
4665 catch (_c) {
4666 return null;
4667 }
4668 };
4669 /** Always set to {@link SignInMethod}.GOOGLE. */
4670 GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* GOOGLE */;
4671 /** Always set to {@link ProviderId}.GOOGLE. */
4672 GoogleAuthProvider.PROVIDER_ID = "google.com" /* GOOGLE */;
4673 return GoogleAuthProvider;
4674}(BaseOAuthProvider));
4675
4676/**
4677 * @license
4678 * Copyright 2020 Google LLC
4679 *
4680 * Licensed under the Apache License, Version 2.0 (the "License");
4681 * you may not use this file except in compliance with the License.
4682 * You may obtain a copy of the License at
4683 *
4684 * http://www.apache.org/licenses/LICENSE-2.0
4685 *
4686 * Unless required by applicable law or agreed to in writing, software
4687 * distributed under the License is distributed on an "AS IS" BASIS,
4688 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4689 * See the License for the specific language governing permissions and
4690 * limitations under the License.
4691 */
4692/**
4693 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
4694 *
4695 * @remarks
4696 * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
4697 * the {@link signInWithPopup} handler:
4698 *
4699 * @example
4700 * ```javascript
4701 * // Sign in using a redirect.
4702 * const provider = new GithubAuthProvider();
4703 * // Start a sign in process for an unauthenticated user.
4704 * provider.addScope('repo');
4705 * await signInWithRedirect(auth, provider);
4706 * // This will trigger a full page redirect away from your app
4707 *
4708 * // After returning from the redirect when your app initializes you can obtain the result
4709 * const result = await getRedirectResult(auth);
4710 * if (result) {
4711 * // This is the signed-in user
4712 * const user = result.user;
4713 * // This gives you a Github Access Token.
4714 * const credential = GithubAuthProvider.credentialFromResult(result);
4715 * const token = credential.accessToken;
4716 * }
4717 * ```
4718 *
4719 * @example
4720 * ```javascript
4721 * // Sign in using a popup.
4722 * const provider = new GithubAuthProvider();
4723 * provider.addScope('repo');
4724 * const result = await signInWithPopup(auth, provider);
4725 *
4726 * // The signed-in user info.
4727 * const user = result.user;
4728 * // This gives you a Github Access Token.
4729 * const credential = GithubAuthProvider.credentialFromResult(result);
4730 * const token = credential.accessToken;
4731 * ```
4732 * @public
4733 */
4734var GithubAuthProvider = /** @class */ (function (_super) {
4735 __extends(GithubAuthProvider, _super);
4736 function GithubAuthProvider() {
4737 return _super.call(this, "github.com" /* GITHUB */) || this;
4738 }
4739 /**
4740 * Creates a credential for Github.
4741 *
4742 * @param accessToken - Github access token.
4743 */
4744 GithubAuthProvider.credential = function (accessToken) {
4745 return OAuthCredential._fromParams({
4746 providerId: GithubAuthProvider.PROVIDER_ID,
4747 signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
4748 accessToken: accessToken
4749 });
4750 };
4751 /**
4752 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4753 *
4754 * @param userCredential - The user credential.
4755 */
4756 GithubAuthProvider.credentialFromResult = function (userCredential) {
4757 return GithubAuthProvider.credentialFromTaggedObject(userCredential);
4758 };
4759 /**
4760 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4761 * thrown during a sign-in, link, or reauthenticate operation.
4762 *
4763 * @param userCredential - The user credential.
4764 */
4765 GithubAuthProvider.credentialFromError = function (error) {
4766 return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
4767 };
4768 GithubAuthProvider.credentialFromTaggedObject = function (_a) {
4769 var tokenResponse = _a._tokenResponse;
4770 if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
4771 return null;
4772 }
4773 if (!tokenResponse.oauthAccessToken) {
4774 return null;
4775 }
4776 try {
4777 return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
4778 }
4779 catch (_b) {
4780 return null;
4781 }
4782 };
4783 /** Always set to {@link SignInMethod}.GITHUB. */
4784 GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* GITHUB */;
4785 /** Always set to {@link ProviderId}.GITHUB. */
4786 GithubAuthProvider.PROVIDER_ID = "github.com" /* GITHUB */;
4787 return GithubAuthProvider;
4788}(BaseOAuthProvider));
4789
4790/**
4791 * @license
4792 * Copyright 2020 Google LLC
4793 *
4794 * Licensed under the Apache License, Version 2.0 (the "License");
4795 * you may not use this file except in compliance with the License.
4796 * You may obtain a copy of the License at
4797 *
4798 * http://www.apache.org/licenses/LICENSE-2.0
4799 *
4800 * Unless required by applicable law or agreed to in writing, software
4801 * distributed under the License is distributed on an "AS IS" BASIS,
4802 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4803 * See the License for the specific language governing permissions and
4804 * limitations under the License.
4805 */
4806var IDP_REQUEST_URI = 'http://localhost';
4807/**
4808 * @public
4809 */
4810var SAMLAuthCredential = /** @class */ (function (_super) {
4811 __extends(SAMLAuthCredential, _super);
4812 /** @internal */
4813 function SAMLAuthCredential(providerId, pendingToken) {
4814 var _this = _super.call(this, providerId, providerId) || this;
4815 _this.pendingToken = pendingToken;
4816 return _this;
4817 }
4818 /** @internal */
4819 SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
4820 var request = this.buildRequest();
4821 return signInWithIdp(auth, request);
4822 };
4823 /** @internal */
4824 SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
4825 var request = this.buildRequest();
4826 request.idToken = idToken;
4827 return signInWithIdp(auth, request);
4828 };
4829 /** @internal */
4830 SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
4831 var request = this.buildRequest();
4832 request.autoCreate = false;
4833 return signInWithIdp(auth, request);
4834 };
4835 /** {@inheritdoc AuthCredential.toJSON} */
4836 SAMLAuthCredential.prototype.toJSON = function () {
4837 return {
4838 signInMethod: this.signInMethod,
4839 providerId: this.providerId,
4840 pendingToken: this.pendingToken
4841 };
4842 };
4843 /**
4844 * Static method to deserialize a JSON representation of an object into an
4845 * {@link AuthCredential}.
4846 *
4847 * @param json - Input can be either Object or the stringified representation of the object.
4848 * When string is provided, JSON.parse would be called first.
4849 *
4850 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
4851 */
4852 SAMLAuthCredential.fromJSON = function (json) {
4853 var obj = typeof json === 'string' ? JSON.parse(json) : json;
4854 var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
4855 if (!providerId ||
4856 !signInMethod ||
4857 !pendingToken ||
4858 providerId !== signInMethod) {
4859 return null;
4860 }
4861 return new SAMLAuthCredential(providerId, pendingToken);
4862 };
4863 /**
4864 * Helper static method to avoid exposing the constructor to end users.
4865 *
4866 * @internal
4867 */
4868 SAMLAuthCredential._create = function (providerId, pendingToken) {
4869 return new SAMLAuthCredential(providerId, pendingToken);
4870 };
4871 SAMLAuthCredential.prototype.buildRequest = function () {
4872 return {
4873 requestUri: IDP_REQUEST_URI,
4874 returnSecureToken: true,
4875 pendingToken: this.pendingToken
4876 };
4877 };
4878 return SAMLAuthCredential;
4879}(AuthCredential));
4880
4881/**
4882 * @license
4883 * Copyright 2020 Google LLC
4884 *
4885 * Licensed under the Apache License, Version 2.0 (the "License");
4886 * you may not use this file except in compliance with the License.
4887 * You may obtain a copy of the License at
4888 *
4889 * http://www.apache.org/licenses/LICENSE-2.0
4890 *
4891 * Unless required by applicable law or agreed to in writing, software
4892 * distributed under the License is distributed on an "AS IS" BASIS,
4893 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4894 * See the License for the specific language governing permissions and
4895 * limitations under the License.
4896 */
4897var SAML_PROVIDER_PREFIX = 'saml.';
4898/**
4899 * An {@link AuthProvider} for SAML.
4900 *
4901 * @public
4902 */
4903var SAMLAuthProvider = /** @class */ (function (_super) {
4904 __extends(SAMLAuthProvider, _super);
4905 /**
4906 * Constructor. The providerId must start with "saml."
4907 * @param providerId - SAML provider ID.
4908 */
4909 function SAMLAuthProvider(providerId) {
4910 var _this = this;
4911 _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* ARGUMENT_ERROR */);
4912 _this = _super.call(this, providerId) || this;
4913 return _this;
4914 }
4915 /**
4916 * Generates an {@link AuthCredential} from a {@link UserCredential} after a
4917 * successful SAML flow completes.
4918 *
4919 * @remarks
4920 *
4921 * For example, to get an {@link AuthCredential}, you could write the
4922 * following code:
4923 *
4924 * ```js
4925 * const userCredential = await signInWithPopup(auth, samlProvider);
4926 * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
4927 * ```
4928 *
4929 * @param userCredential - The user credential.
4930 */
4931 SAMLAuthProvider.credentialFromResult = function (userCredential) {
4932 return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
4933 };
4934 /**
4935 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4936 * thrown during a sign-in, link, or reauthenticate operation.
4937 *
4938 * @param userCredential - The user credential.
4939 */
4940 SAMLAuthProvider.credentialFromError = function (error) {
4941 return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
4942 };
4943 /**
4944 * Creates an {@link AuthCredential} from a JSON string or a plain object.
4945 * @param json - A plain object or a JSON string
4946 */
4947 SAMLAuthProvider.credentialFromJSON = function (json) {
4948 var credential = SAMLAuthCredential.fromJSON(json);
4949 _assert(credential, "argument-error" /* ARGUMENT_ERROR */);
4950 return credential;
4951 };
4952 SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
4953 var tokenResponse = _a._tokenResponse;
4954 if (!tokenResponse) {
4955 return null;
4956 }
4957 var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
4958 if (!pendingToken || !providerId) {
4959 return null;
4960 }
4961 try {
4962 return SAMLAuthCredential._create(providerId, pendingToken);
4963 }
4964 catch (e) {
4965 return null;
4966 }
4967 };
4968 return SAMLAuthProvider;
4969}(FederatedAuthProvider));
4970
4971/**
4972 * @license
4973 * Copyright 2020 Google LLC
4974 *
4975 * Licensed under the Apache License, Version 2.0 (the "License");
4976 * you may not use this file except in compliance with the License.
4977 * You may obtain a copy of the License at
4978 *
4979 * http://www.apache.org/licenses/LICENSE-2.0
4980 *
4981 * Unless required by applicable law or agreed to in writing, software
4982 * distributed under the License is distributed on an "AS IS" BASIS,
4983 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4984 * See the License for the specific language governing permissions and
4985 * limitations under the License.
4986 */
4987/**
4988 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
4989 *
4990 * @example
4991 * ```javascript
4992 * // Sign in using a redirect.
4993 * const provider = new TwitterAuthProvider();
4994 * // Start a sign in process for an unauthenticated user.
4995 * await signInWithRedirect(auth, provider);
4996 * // This will trigger a full page redirect away from your app
4997 *
4998 * // After returning from the redirect when your app initializes you can obtain the result
4999 * const result = await getRedirectResult(auth);
5000 * if (result) {
5001 * // This is the signed-in user
5002 * const user = result.user;
5003 * // This gives you a Twitter Access Token and Secret.
5004 * const credential = TwitterAuthProvider.credentialFromResult(result);
5005 * const token = credential.accessToken;
5006 * const secret = credential.secret;
5007 * }
5008 * ```
5009 *
5010 * @example
5011 * ```javascript
5012 * // Sign in using a popup.
5013 * const provider = new TwitterAuthProvider();
5014 * const result = await signInWithPopup(auth, provider);
5015 *
5016 * // The signed-in user info.
5017 * const user = result.user;
5018 * // This gives you a Twitter Access Token and Secret.
5019 * const credential = TwitterAuthProvider.credentialFromResult(result);
5020 * const token = credential.accessToken;
5021 * const secret = credential.secret;
5022 * ```
5023 *
5024 * @public
5025 */
5026var TwitterAuthProvider = /** @class */ (function (_super) {
5027 __extends(TwitterAuthProvider, _super);
5028 function TwitterAuthProvider() {
5029 return _super.call(this, "twitter.com" /* TWITTER */) || this;
5030 }
5031 /**
5032 * Creates a credential for Twitter.
5033 *
5034 * @param token - Twitter access token.
5035 * @param secret - Twitter secret.
5036 */
5037 TwitterAuthProvider.credential = function (token, secret) {
5038 return OAuthCredential._fromParams({
5039 providerId: TwitterAuthProvider.PROVIDER_ID,
5040 signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
5041 oauthToken: token,
5042 oauthTokenSecret: secret
5043 });
5044 };
5045 /**
5046 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
5047 *
5048 * @param userCredential - The user credential.
5049 */
5050 TwitterAuthProvider.credentialFromResult = function (userCredential) {
5051 return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
5052 };
5053 /**
5054 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5055 * thrown during a sign-in, link, or reauthenticate operation.
5056 *
5057 * @param userCredential - The user credential.
5058 */
5059 TwitterAuthProvider.credentialFromError = function (error) {
5060 return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
5061 };
5062 TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
5063 var tokenResponse = _a._tokenResponse;
5064 if (!tokenResponse) {
5065 return null;
5066 }
5067 var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
5068 if (!oauthAccessToken || !oauthTokenSecret) {
5069 return null;
5070 }
5071 try {
5072 return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
5073 }
5074 catch (_c) {
5075 return null;
5076 }
5077 };
5078 /** Always set to {@link SignInMethod}.TWITTER. */
5079 TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* TWITTER */;
5080 /** Always set to {@link ProviderId}.TWITTER. */
5081 TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* TWITTER */;
5082 return TwitterAuthProvider;
5083}(BaseOAuthProvider));
5084
5085/**
5086 * @license
5087 * Copyright 2020 Google LLC
5088 *
5089 * Licensed under the Apache License, Version 2.0 (the "License");
5090 * you may not use this file except in compliance with the License.
5091 * You may obtain a copy of the License at
5092 *
5093 * http://www.apache.org/licenses/LICENSE-2.0
5094 *
5095 * Unless required by applicable law or agreed to in writing, software
5096 * distributed under the License is distributed on an "AS IS" BASIS,
5097 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5098 * See the License for the specific language governing permissions and
5099 * limitations under the License.
5100 */
5101function signUp(auth, request) {
5102 return __awaiter(this, void 0, void 0, function () {
5103 return __generator(this, function (_a) {
5104 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signUp" /* SIGN_UP */, _addTidIfNecessary(auth, request))];
5105 });
5106 });
5107}
5108
5109/**
5110 * @license
5111 * Copyright 2020 Google LLC
5112 *
5113 * Licensed under the Apache License, Version 2.0 (the "License");
5114 * you may not use this file except in compliance with the License.
5115 * You may obtain a copy of the License at
5116 *
5117 * http://www.apache.org/licenses/LICENSE-2.0
5118 *
5119 * Unless required by applicable law or agreed to in writing, software
5120 * distributed under the License is distributed on an "AS IS" BASIS,
5121 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5122 * See the License for the specific language governing permissions and
5123 * limitations under the License.
5124 */
5125var UserCredentialImpl = /** @class */ (function () {
5126 function UserCredentialImpl(params) {
5127 this.user = params.user;
5128 this.providerId = params.providerId;
5129 this._tokenResponse = params._tokenResponse;
5130 this.operationType = params.operationType;
5131 }
5132 UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
5133 if (isAnonymous === void 0) { isAnonymous = false; }
5134 return __awaiter(this, void 0, void 0, function () {
5135 var user, providerId, userCred;
5136 return __generator(this, function (_a) {
5137 switch (_a.label) {
5138 case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
5139 case 1:
5140 user = _a.sent();
5141 providerId = providerIdForResponse(idTokenResponse);
5142 userCred = new UserCredentialImpl({
5143 user: user,
5144 providerId: providerId,
5145 _tokenResponse: idTokenResponse,
5146 operationType: operationType
5147 });
5148 return [2 /*return*/, userCred];
5149 }
5150 });
5151 });
5152 };
5153 UserCredentialImpl._forOperation = function (user, operationType, response) {
5154 return __awaiter(this, void 0, void 0, function () {
5155 var providerId;
5156 return __generator(this, function (_a) {
5157 switch (_a.label) {
5158 case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
5159 case 1:
5160 _a.sent();
5161 providerId = providerIdForResponse(response);
5162 return [2 /*return*/, new UserCredentialImpl({
5163 user: user,
5164 providerId: providerId,
5165 _tokenResponse: response,
5166 operationType: operationType
5167 })];
5168 }
5169 });
5170 });
5171 };
5172 return UserCredentialImpl;
5173}());
5174function providerIdForResponse(response) {
5175 if (response.providerId) {
5176 return response.providerId;
5177 }
5178 if ('phoneNumber' in response) {
5179 return "phone" /* PHONE */;
5180 }
5181 return null;
5182}
5183
5184/**
5185 * @license
5186 * Copyright 2020 Google LLC
5187 *
5188 * Licensed under the Apache License, Version 2.0 (the "License");
5189 * you may not use this file except in compliance with the License.
5190 * You may obtain a copy of the License at
5191 *
5192 * http://www.apache.org/licenses/LICENSE-2.0
5193 *
5194 * Unless required by applicable law or agreed to in writing, software
5195 * distributed under the License is distributed on an "AS IS" BASIS,
5196 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5197 * See the License for the specific language governing permissions and
5198 * limitations under the License.
5199 */
5200/**
5201 * Asynchronously signs in as an anonymous user.
5202 *
5203 * @remarks
5204 * If there is already an anonymous user signed in, that user will be returned; otherwise, a
5205 * new anonymous user identity will be created and returned.
5206 *
5207 * @param auth - The {@link Auth} instance.
5208 *
5209 * @public
5210 */
5211function signInAnonymously(auth) {
5212 var _a;
5213 return __awaiter(this, void 0, void 0, function () {
5214 var authInternal, response, userCredential;
5215 return __generator(this, function (_b) {
5216 switch (_b.label) {
5217 case 0:
5218 authInternal = _castAuth(auth);
5219 return [4 /*yield*/, authInternal._initializationPromise];
5220 case 1:
5221 _b.sent();
5222 if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
5223 // If an anonymous user is already signed in, no need to sign them in again.
5224 return [2 /*return*/, new UserCredentialImpl({
5225 user: authInternal.currentUser,
5226 providerId: null,
5227 operationType: "signIn" /* SIGN_IN */
5228 })];
5229 }
5230 return [4 /*yield*/, signUp(authInternal, {
5231 returnSecureToken: true
5232 })];
5233 case 2:
5234 response = _b.sent();
5235 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response, true)];
5236 case 3:
5237 userCredential = _b.sent();
5238 return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
5239 case 4:
5240 _b.sent();
5241 return [2 /*return*/, userCredential];
5242 }
5243 });
5244 });
5245}
5246
5247/**
5248 * @license
5249 * Copyright 2020 Google LLC
5250 *
5251 * Licensed under the Apache License, Version 2.0 (the "License");
5252 * you may not use this file except in compliance with the License.
5253 * You may obtain a copy of the License at
5254 *
5255 * http://www.apache.org/licenses/LICENSE-2.0
5256 *
5257 * Unless required by applicable law or agreed to in writing, software
5258 * distributed under the License is distributed on an "AS IS" BASIS,
5259 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5260 * See the License for the specific language governing permissions and
5261 * limitations under the License.
5262 */
5263var MultiFactorError = /** @class */ (function (_super) {
5264 __extends(MultiFactorError, _super);
5265 function MultiFactorError(auth, error, operationType, user) {
5266 var _a;
5267 var _this = _super.call(this, error.code, error.message) || this;
5268 _this.operationType = operationType;
5269 _this.user = user;
5270 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
5271 Object.setPrototypeOf(_this, MultiFactorError.prototype);
5272 _this.customData = {
5273 appName: auth.name,
5274 tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
5275 _serverResponse: error.customData._serverResponse,
5276 operationType: operationType,
5277 };
5278 return _this;
5279 }
5280 MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
5281 return new MultiFactorError(auth, error, operationType, user);
5282 };
5283 return MultiFactorError;
5284}(FirebaseError));
5285function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
5286 var idTokenProvider = operationType === "reauthenticate" /* REAUTHENTICATE */
5287 ? credential._getReauthenticationResolver(auth)
5288 : credential._getIdTokenResponse(auth);
5289 return idTokenProvider.catch(function (error) {
5290 if (error.code === "auth/" + "multi-factor-auth-required" /* MFA_REQUIRED */) {
5291 throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
5292 }
5293 throw error;
5294 });
5295}
5296
5297/**
5298 * @license
5299 * Copyright 2020 Google LLC
5300 *
5301 * Licensed under the Apache License, Version 2.0 (the "License");
5302 * you may not use this file except in compliance with the License.
5303 * You may obtain a copy of the License at
5304 *
5305 * http://www.apache.org/licenses/LICENSE-2.0
5306 *
5307 * Unless required by applicable law or agreed to in writing, software
5308 * distributed under the License is distributed on an "AS IS" BASIS,
5309 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5310 * See the License for the specific language governing permissions and
5311 * limitations under the License.
5312 */
5313/**
5314 * Takes a set of UserInfo provider data and converts it to a set of names
5315 */
5316function providerDataAsNames(providerData) {
5317 return new Set(providerData
5318 .map(function (_a) {
5319 var providerId = _a.providerId;
5320 return providerId;
5321 })
5322 .filter(function (pid) { return !!pid; }));
5323}
5324
5325/**
5326 * @license
5327 * Copyright 2019 Google LLC
5328 *
5329 * Licensed under the Apache License, Version 2.0 (the "License");
5330 * you may not use this file except in compliance with the License.
5331 * You may obtain a copy of the License at
5332 *
5333 * http://www.apache.org/licenses/LICENSE-2.0
5334 *
5335 * Unless required by applicable law or agreed to in writing, software
5336 * distributed under the License is distributed on an "AS IS" BASIS,
5337 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5338 * See the License for the specific language governing permissions and
5339 * limitations under the License.
5340 */
5341/**
5342 * Unlinks a provider from a user account.
5343 *
5344 * @param user - The user.
5345 * @param providerId - The provider to unlink.
5346 *
5347 * @public
5348 */
5349function unlink(user, providerId) {
5350 return __awaiter(this, void 0, void 0, function () {
5351 var userInternal, providerUserInfo, _a, _b, providersLeft;
5352 var _c;
5353 return __generator(this, function (_d) {
5354 switch (_d.label) {
5355 case 0:
5356 userInternal = getModularInstance(user);
5357 return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
5358 case 1:
5359 _d.sent();
5360 _a = deleteLinkedAccounts;
5361 _b = [userInternal.auth];
5362 _c = {};
5363 return [4 /*yield*/, userInternal.getIdToken()];
5364 case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
5365 _c.deleteProvider = [providerId],
5366 _c)]))];
5367 case 3:
5368 providerUserInfo = (_d.sent()).providerUserInfo;
5369 providersLeft = providerDataAsNames(providerUserInfo || []);
5370 userInternal.providerData = userInternal.providerData.filter(function (pd) {
5371 return providersLeft.has(pd.providerId);
5372 });
5373 if (!providersLeft.has("phone" /* PHONE */)) {
5374 userInternal.phoneNumber = null;
5375 }
5376 return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
5377 case 4:
5378 _d.sent();
5379 return [2 /*return*/, userInternal];
5380 }
5381 });
5382 });
5383}
5384function _link$1(user, credential, bypassAuthState) {
5385 if (bypassAuthState === void 0) { bypassAuthState = false; }
5386 return __awaiter(this, void 0, void 0, function () {
5387 var response, _a, _b, _c, _d, _e;
5388 return __generator(this, function (_f) {
5389 switch (_f.label) {
5390 case 0:
5391 _a = _logoutIfInvalidated;
5392 _b = [user];
5393 _d = (_c = credential)._linkToIdToken;
5394 _e = [user.auth];
5395 return [4 /*yield*/, user.getIdToken()];
5396 case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])), bypassAuthState]))];
5397 case 2:
5398 response = _f.sent();
5399 return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* LINK */, response)];
5400 }
5401 });
5402 });
5403}
5404function _assertLinkedStatus(expected, user, provider) {
5405 return __awaiter(this, void 0, void 0, function () {
5406 var providerIds, code;
5407 return __generator(this, function (_a) {
5408 switch (_a.label) {
5409 case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
5410 case 1:
5411 _a.sent();
5412 providerIds = providerDataAsNames(user.providerData);
5413 code = expected === false
5414 ? "provider-already-linked" /* PROVIDER_ALREADY_LINKED */
5415 : "no-such-provider" /* NO_SUCH_PROVIDER */;
5416 _assert(providerIds.has(provider) === expected, user.auth, code);
5417 return [2 /*return*/];
5418 }
5419 });
5420 });
5421}
5422
5423/**
5424 * @license
5425 * Copyright 2019 Google LLC
5426 *
5427 * Licensed under the Apache License, Version 2.0 (the "License");
5428 * you may not use this file except in compliance with the License.
5429 * You may obtain a copy of the License at
5430 *
5431 * http://www.apache.org/licenses/LICENSE-2.0
5432 *
5433 * Unless required by applicable law or agreed to in writing, software
5434 * distributed under the License is distributed on an "AS IS" BASIS,
5435 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5436 * See the License for the specific language governing permissions and
5437 * limitations under the License.
5438 */
5439function _reauthenticate(user, credential, bypassAuthState) {
5440 if (bypassAuthState === void 0) { bypassAuthState = false; }
5441 return __awaiter(this, void 0, void 0, function () {
5442 var auth, operationType, response, parsed, localId, e_1;
5443 return __generator(this, function (_a) {
5444 switch (_a.label) {
5445 case 0:
5446 auth = user.auth;
5447 operationType = "reauthenticate" /* REAUTHENTICATE */;
5448 _a.label = 1;
5449 case 1:
5450 _a.trys.push([1, 3, , 4]);
5451 return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
5452 case 2:
5453 response = _a.sent();
5454 _assert(response.idToken, auth, "internal-error" /* INTERNAL_ERROR */);
5455 parsed = _parseToken(response.idToken);
5456 _assert(parsed, auth, "internal-error" /* INTERNAL_ERROR */);
5457 localId = parsed.sub;
5458 _assert(user.uid === localId, auth, "user-mismatch" /* USER_MISMATCH */);
5459 return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
5460 case 3:
5461 e_1 = _a.sent();
5462 // Convert user deleted error into user mismatch
5463 if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/" + "user-not-found" /* USER_DELETED */) {
5464 _fail(auth, "user-mismatch" /* USER_MISMATCH */);
5465 }
5466 throw e_1;
5467 case 4: return [2 /*return*/];
5468 }
5469 });
5470 });
5471}
5472
5473/**
5474 * @license
5475 * Copyright 2020 Google LLC
5476 *
5477 * Licensed under the Apache License, Version 2.0 (the "License");
5478 * you may not use this file except in compliance with the License.
5479 * You may obtain a copy of the License at
5480 *
5481 * http://www.apache.org/licenses/LICENSE-2.0
5482 *
5483 * Unless required by applicable law or agreed to in writing, software
5484 * distributed under the License is distributed on an "AS IS" BASIS,
5485 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5486 * See the License for the specific language governing permissions and
5487 * limitations under the License.
5488 */
5489function _signInWithCredential(auth, credential, bypassAuthState) {
5490 if (bypassAuthState === void 0) { bypassAuthState = false; }
5491 return __awaiter(this, void 0, void 0, function () {
5492 var operationType, response, userCredential;
5493 return __generator(this, function (_a) {
5494 switch (_a.label) {
5495 case 0:
5496 operationType = "signIn" /* SIGN_IN */;
5497 return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
5498 case 1:
5499 response = _a.sent();
5500 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
5501 case 2:
5502 userCredential = _a.sent();
5503 if (!!bypassAuthState) return [3 /*break*/, 4];
5504 return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
5505 case 3:
5506 _a.sent();
5507 _a.label = 4;
5508 case 4: return [2 /*return*/, userCredential];
5509 }
5510 });
5511 });
5512}
5513/**
5514 * Asynchronously signs in with the given credentials.
5515 *
5516 * @remarks
5517 * An {@link AuthProvider} can be used to generate the credential.
5518 *
5519 * @param auth - The {@link Auth} instance.
5520 * @param credential - The auth credential.
5521 *
5522 * @public
5523 */
5524function signInWithCredential(auth, credential) {
5525 return __awaiter(this, void 0, void 0, function () {
5526 return __generator(this, function (_a) {
5527 return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
5528 });
5529 });
5530}
5531/**
5532 * Links the user account with the given credentials.
5533 *
5534 * @remarks
5535 * An {@link AuthProvider} can be used to generate the credential.
5536 *
5537 * @param user - The user.
5538 * @param credential - The auth credential.
5539 *
5540 * @public
5541 */
5542function linkWithCredential(user, credential) {
5543 return __awaiter(this, void 0, void 0, function () {
5544 var userInternal;
5545 return __generator(this, function (_a) {
5546 switch (_a.label) {
5547 case 0:
5548 userInternal = getModularInstance(user);
5549 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
5550 case 1:
5551 _a.sent();
5552 return [2 /*return*/, _link$1(userInternal, credential)];
5553 }
5554 });
5555 });
5556}
5557/**
5558 * Re-authenticates a user using a fresh credential.
5559 *
5560 * @remarks
5561 * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
5562 * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
5563 *
5564 * @param user - The user.
5565 * @param credential - The auth credential.
5566 *
5567 * @public
5568 */
5569function reauthenticateWithCredential(user, credential) {
5570 return __awaiter(this, void 0, void 0, function () {
5571 return __generator(this, function (_a) {
5572 return [2 /*return*/, _reauthenticate(getModularInstance(user), credential)];
5573 });
5574 });
5575}
5576
5577/**
5578 * @license
5579 * Copyright 2020 Google LLC
5580 *
5581 * Licensed under the Apache License, Version 2.0 (the "License");
5582 * you may not use this file except in compliance with the License.
5583 * You may obtain a copy of the License at
5584 *
5585 * http://www.apache.org/licenses/LICENSE-2.0
5586 *
5587 * Unless required by applicable law or agreed to in writing, software
5588 * distributed under the License is distributed on an "AS IS" BASIS,
5589 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5590 * See the License for the specific language governing permissions and
5591 * limitations under the License.
5592 */
5593function signInWithCustomToken$1(auth, request) {
5594 return __awaiter(this, void 0, void 0, function () {
5595 return __generator(this, function (_a) {
5596 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithCustomToken" /* SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
5597 });
5598 });
5599}
5600
5601/**
5602 * @license
5603 * Copyright 2020 Google LLC
5604 *
5605 * Licensed under the Apache License, Version 2.0 (the "License");
5606 * you may not use this file except in compliance with the License.
5607 * You may obtain a copy of the License at
5608 *
5609 * http://www.apache.org/licenses/LICENSE-2.0
5610 *
5611 * Unless required by applicable law or agreed to in writing, software
5612 * distributed under the License is distributed on an "AS IS" BASIS,
5613 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5614 * See the License for the specific language governing permissions and
5615 * limitations under the License.
5616 */
5617/**
5618 * Asynchronously signs in using a custom token.
5619 *
5620 * @remarks
5621 * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
5622 * be generated by an auth backend using the
5623 * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
5624 * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
5625 *
5626 * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
5627 *
5628 * @param auth - The {@link Auth} instance.
5629 * @param customToken - The custom token to sign in with.
5630 *
5631 * @public
5632 */
5633function signInWithCustomToken(auth, customToken) {
5634 return __awaiter(this, void 0, void 0, function () {
5635 var authInternal, response, cred;
5636 return __generator(this, function (_a) {
5637 switch (_a.label) {
5638 case 0:
5639 authInternal = _castAuth(auth);
5640 return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
5641 token: customToken,
5642 returnSecureToken: true
5643 })];
5644 case 1:
5645 response = _a.sent();
5646 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response)];
5647 case 2:
5648 cred = _a.sent();
5649 return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
5650 case 3:
5651 _a.sent();
5652 return [2 /*return*/, cred];
5653 }
5654 });
5655 });
5656}
5657
5658/**
5659 * @license
5660 * Copyright 2020 Google LLC
5661 *
5662 * Licensed under the Apache License, Version 2.0 (the "License");
5663 * you may not use this file except in compliance with the License.
5664 * You may obtain a copy of the License at
5665 *
5666 * http://www.apache.org/licenses/LICENSE-2.0
5667 *
5668 * Unless required by applicable law or agreed to in writing, software
5669 * distributed under the License is distributed on an "AS IS" BASIS,
5670 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5671 * See the License for the specific language governing permissions and
5672 * limitations under the License.
5673 */
5674var MultiFactorInfoImpl = /** @class */ (function () {
5675 function MultiFactorInfoImpl(factorId, response) {
5676 this.factorId = factorId;
5677 this.uid = response.mfaEnrollmentId;
5678 this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
5679 this.displayName = response.displayName;
5680 }
5681 MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
5682 if ('phoneInfo' in enrollment) {
5683 return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
5684 }
5685 return _fail(auth, "internal-error" /* INTERNAL_ERROR */);
5686 };
5687 return MultiFactorInfoImpl;
5688}());
5689var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
5690 __extends(PhoneMultiFactorInfoImpl, _super);
5691 function PhoneMultiFactorInfoImpl(response) {
5692 var _this = _super.call(this, "phone" /* PHONE */, response) || this;
5693 _this.phoneNumber = response.phoneInfo;
5694 return _this;
5695 }
5696 PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
5697 return new PhoneMultiFactorInfoImpl(enrollment);
5698 };
5699 return PhoneMultiFactorInfoImpl;
5700}(MultiFactorInfoImpl));
5701
5702/**
5703 * @license
5704 * Copyright 2020 Google LLC
5705 *
5706 * Licensed under the Apache License, Version 2.0 (the "License");
5707 * you may not use this file except in compliance with the License.
5708 * You may obtain a copy of the License at
5709 *
5710 * http://www.apache.org/licenses/LICENSE-2.0
5711 *
5712 * Unless required by applicable law or agreed to in writing, software
5713 * distributed under the License is distributed on an "AS IS" BASIS,
5714 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5715 * See the License for the specific language governing permissions and
5716 * limitations under the License.
5717 */
5718function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
5719 var _a;
5720 _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* INVALID_CONTINUE_URI */);
5721 _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
5722 actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* INVALID_DYNAMIC_LINK_DOMAIN */);
5723 request.continueUrl = actionCodeSettings.url;
5724 request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
5725 request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
5726 if (actionCodeSettings.iOS) {
5727 _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* MISSING_IOS_BUNDLE_ID */);
5728 request.iOSBundleId = actionCodeSettings.iOS.bundleId;
5729 }
5730 if (actionCodeSettings.android) {
5731 _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */);
5732 request.androidInstallApp = actionCodeSettings.android.installApp;
5733 request.androidMinimumVersionCode =
5734 actionCodeSettings.android.minimumVersion;
5735 request.androidPackageName = actionCodeSettings.android.packageName;
5736 }
5737}
5738
5739/**
5740 * @license
5741 * Copyright 2020 Google LLC
5742 *
5743 * Licensed under the Apache License, Version 2.0 (the "License");
5744 * you may not use this file except in compliance with the License.
5745 * You may obtain a copy of the License at
5746 *
5747 * http://www.apache.org/licenses/LICENSE-2.0
5748 *
5749 * Unless required by applicable law or agreed to in writing, software
5750 * distributed under the License is distributed on an "AS IS" BASIS,
5751 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5752 * See the License for the specific language governing permissions and
5753 * limitations under the License.
5754 */
5755/**
5756 * Sends a password reset email to the given email address.
5757 *
5758 * @remarks
5759 * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
5760 * the email sent to the user, along with the new password specified by the user.
5761 *
5762 * @example
5763 * ```javascript
5764 * const actionCodeSettings = {
5765 * url: 'https://www.example.com/?email=user@example.com',
5766 * iOS: {
5767 * bundleId: 'com.example.ios'
5768 * },
5769 * android: {
5770 * packageName: 'com.example.android',
5771 * installApp: true,
5772 * minimumVersion: '12'
5773 * },
5774 * handleCodeInApp: true
5775 * };
5776 * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
5777 * // Obtain code from user.
5778 * await confirmPasswordReset('user@example.com', code);
5779 * ```
5780 *
5781 * @param auth - The {@link Auth} instance.
5782 * @param email - The user's email address.
5783 * @param actionCodeSettings - The {@link ActionCodeSettings}.
5784 *
5785 * @public
5786 */
5787function sendPasswordResetEmail(auth, email, actionCodeSettings) {
5788 return __awaiter(this, void 0, void 0, function () {
5789 var authModular, request;
5790 return __generator(this, function (_a) {
5791 switch (_a.label) {
5792 case 0:
5793 authModular = getModularInstance(auth);
5794 request = {
5795 requestType: "PASSWORD_RESET" /* PASSWORD_RESET */,
5796 email: email
5797 };
5798 if (actionCodeSettings) {
5799 _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
5800 }
5801 return [4 /*yield*/, sendPasswordResetEmail$1(authModular, request)];
5802 case 1:
5803 _a.sent();
5804 return [2 /*return*/];
5805 }
5806 });
5807 });
5808}
5809/**
5810 * Completes the password reset process, given a confirmation code and new password.
5811 *
5812 * @param auth - The {@link Auth} instance.
5813 * @param oobCode - A confirmation code sent to the user.
5814 * @param newPassword - The new password.
5815 *
5816 * @public
5817 */
5818function confirmPasswordReset(auth, oobCode, newPassword) {
5819 return __awaiter(this, void 0, void 0, function () {
5820 return __generator(this, function (_a) {
5821 switch (_a.label) {
5822 case 0: return [4 /*yield*/, resetPassword(getModularInstance(auth), {
5823 oobCode: oobCode,
5824 newPassword: newPassword
5825 })];
5826 case 1:
5827 _a.sent();
5828 return [2 /*return*/];
5829 }
5830 });
5831 });
5832}
5833/**
5834 * Applies a verification code sent to the user by email or other out-of-band mechanism.
5835 *
5836 * @param auth - The {@link Auth} instance.
5837 * @param oobCode - A verification code sent to the user.
5838 *
5839 * @public
5840 */
5841function applyActionCode(auth, oobCode) {
5842 return __awaiter(this, void 0, void 0, function () {
5843 return __generator(this, function (_a) {
5844 switch (_a.label) {
5845 case 0: return [4 /*yield*/, applyActionCode$1(getModularInstance(auth), { oobCode: oobCode })];
5846 case 1:
5847 _a.sent();
5848 return [2 /*return*/];
5849 }
5850 });
5851 });
5852}
5853/**
5854 * Checks a verification code sent to the user by email or other out-of-band mechanism.
5855 *
5856 * @returns metadata about the code.
5857 *
5858 * @param auth - The {@link Auth} instance.
5859 * @param oobCode - A verification code sent to the user.
5860 *
5861 * @public
5862 */
5863function checkActionCode(auth, oobCode) {
5864 return __awaiter(this, void 0, void 0, function () {
5865 var authModular, response, operation, multiFactorInfo;
5866 return __generator(this, function (_a) {
5867 switch (_a.label) {
5868 case 0:
5869 authModular = getModularInstance(auth);
5870 return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
5871 case 1:
5872 response = _a.sent();
5873 operation = response.requestType;
5874 _assert(operation, authModular, "internal-error" /* INTERNAL_ERROR */);
5875 switch (operation) {
5876 case "EMAIL_SIGNIN" /* EMAIL_SIGNIN */:
5877 break;
5878 case "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */:
5879 _assert(response.newEmail, authModular, "internal-error" /* INTERNAL_ERROR */);
5880 break;
5881 case "REVERT_SECOND_FACTOR_ADDITION" /* REVERT_SECOND_FACTOR_ADDITION */:
5882 _assert(response.mfaInfo, authModular, "internal-error" /* INTERNAL_ERROR */);
5883 // fall through
5884 default:
5885 _assert(response.email, authModular, "internal-error" /* INTERNAL_ERROR */);
5886 }
5887 multiFactorInfo = null;
5888 if (response.mfaInfo) {
5889 multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
5890 }
5891 return [2 /*return*/, {
5892 data: {
5893 email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */
5894 ? response.newEmail
5895 : response.email) || null,
5896 previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */
5897 ? response.email
5898 : response.newEmail) || null,
5899 multiFactorInfo: multiFactorInfo
5900 },
5901 operation: operation
5902 }];
5903 }
5904 });
5905 });
5906}
5907/**
5908 * Checks a password reset code sent to the user by email or other out-of-band mechanism.
5909 *
5910 * @returns the user's email address if valid.
5911 *
5912 * @param auth - The {@link Auth} instance.
5913 * @param code - A verification code sent to the user.
5914 *
5915 * @public
5916 */
5917function verifyPasswordResetCode(auth, code) {
5918 return __awaiter(this, void 0, void 0, function () {
5919 var data;
5920 return __generator(this, function (_a) {
5921 switch (_a.label) {
5922 case 0: return [4 /*yield*/, checkActionCode(getModularInstance(auth), code)];
5923 case 1:
5924 data = (_a.sent()).data;
5925 // Email should always be present since a code was sent to it
5926 return [2 /*return*/, data.email];
5927 }
5928 });
5929 });
5930}
5931/**
5932 * Creates a new user account associated with the specified email address and password.
5933 *
5934 * @remarks
5935 * On successful creation of the user account, this user will also be signed in to your application.
5936 *
5937 * User account creation can fail if the account already exists or the password is invalid.
5938 *
5939 * Note: The email address acts as a unique identifier for the user and enables an email-based
5940 * password reset. This function will create a new user account and set the initial user password.
5941 *
5942 * @param auth - The {@link Auth} instance.
5943 * @param email - The user's email address.
5944 * @param password - The user's chosen password.
5945 *
5946 * @public
5947 */
5948function createUserWithEmailAndPassword(auth, email, password) {
5949 return __awaiter(this, void 0, void 0, function () {
5950 var authInternal, response, userCredential;
5951 return __generator(this, function (_a) {
5952 switch (_a.label) {
5953 case 0:
5954 authInternal = _castAuth(auth);
5955 return [4 /*yield*/, signUp(authInternal, {
5956 returnSecureToken: true,
5957 email: email,
5958 password: password
5959 })];
5960 case 1:
5961 response = _a.sent();
5962 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response)];
5963 case 2:
5964 userCredential = _a.sent();
5965 return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
5966 case 3:
5967 _a.sent();
5968 return [2 /*return*/, userCredential];
5969 }
5970 });
5971 });
5972}
5973/**
5974 * Asynchronously signs in using an email and password.
5975 *
5976 * @remarks
5977 * Fails with an error if the email address and password do not match.
5978 *
5979 * Note: The user's password is NOT the password used to access the user's email account. The
5980 * email address serves as a unique identifier for the user, and the password is used to access
5981 * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
5982 *
5983 * @param auth - The {@link Auth} instance.
5984 * @param email - The users email address.
5985 * @param password - The users password.
5986 *
5987 * @public
5988 */
5989function signInWithEmailAndPassword(auth, email, password) {
5990 return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
5991}
5992
5993/**
5994 * @license
5995 * Copyright 2020 Google LLC
5996 *
5997 * Licensed under the Apache License, Version 2.0 (the "License");
5998 * you may not use this file except in compliance with the License.
5999 * You may obtain a copy of the License at
6000 *
6001 * http://www.apache.org/licenses/LICENSE-2.0
6002 *
6003 * Unless required by applicable law or agreed to in writing, software
6004 * distributed under the License is distributed on an "AS IS" BASIS,
6005 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6006 * See the License for the specific language governing permissions and
6007 * limitations under the License.
6008 */
6009/**
6010 * Sends a sign-in email link to the user with the specified email.
6011 *
6012 * @remarks
6013 * The sign-in operation has to always be completed in the app unlike other out of band email
6014 * actions (password reset and email verifications). This is because, at the end of the flow,
6015 * the user is expected to be signed in and their Auth state persisted within the app.
6016 *
6017 * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
6018 * address and the email link supplied in the email sent to the user.
6019 *
6020 * @example
6021 * ```javascript
6022 * const actionCodeSettings = {
6023 * url: 'https://www.example.com/?email=user@example.com',
6024 * iOS: {
6025 * bundleId: 'com.example.ios'
6026 * },
6027 * android: {
6028 * packageName: 'com.example.android',
6029 * installApp: true,
6030 * minimumVersion: '12'
6031 * },
6032 * handleCodeInApp: true
6033 * };
6034 * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
6035 * // Obtain emailLink from the user.
6036 * if(isSignInWithEmailLink(auth, emailLink)) {
6037 * await signInWithEmailLink(auth, 'user@example.com', emailLink);
6038 * }
6039 * ```
6040 *
6041 * @param authInternal - The {@link Auth} instance.
6042 * @param email - The user's email address.
6043 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6044 *
6045 * @public
6046 */
6047function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
6048 return __awaiter(this, void 0, void 0, function () {
6049 var authModular, request;
6050 return __generator(this, function (_a) {
6051 switch (_a.label) {
6052 case 0:
6053 authModular = getModularInstance(auth);
6054 request = {
6055 requestType: "EMAIL_SIGNIN" /* EMAIL_SIGNIN */,
6056 email: email
6057 };
6058 _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* ARGUMENT_ERROR */);
6059 if (actionCodeSettings) {
6060 _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
6061 }
6062 return [4 /*yield*/, sendSignInLinkToEmail$1(authModular, request)];
6063 case 1:
6064 _a.sent();
6065 return [2 /*return*/];
6066 }
6067 });
6068 });
6069}
6070/**
6071 * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
6072 *
6073 * @param auth - The {@link Auth} instance.
6074 * @param emailLink - The link sent to the user's email address.
6075 *
6076 * @public
6077 */
6078function isSignInWithEmailLink(auth, emailLink) {
6079 var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
6080 return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* EMAIL_SIGNIN */;
6081}
6082/**
6083 * Asynchronously signs in using an email and sign-in email link.
6084 *
6085 * @remarks
6086 * If no link is passed, the link is inferred from the current URL.
6087 *
6088 * Fails with an error if the email address is invalid or OTP in email link expires.
6089 *
6090 * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
6091 *
6092 * @example
6093 * ```javascript
6094 * const actionCodeSettings = {
6095 * url: 'https://www.example.com/?email=user@example.com',
6096 * iOS: {
6097 * bundleId: 'com.example.ios'
6098 * },
6099 * android: {
6100 * packageName: 'com.example.android',
6101 * installApp: true,
6102 * minimumVersion: '12'
6103 * },
6104 * handleCodeInApp: true
6105 * };
6106 * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
6107 * // Obtain emailLink from the user.
6108 * if(isSignInWithEmailLink(auth, emailLink)) {
6109 * await signInWithEmailLink(auth, 'user@example.com', emailLink);
6110 * }
6111 * ```
6112 *
6113 * @param auth - The {@link Auth} instance.
6114 * @param email - The user's email address.
6115 * @param emailLink - The link sent to the user's email address.
6116 *
6117 * @public
6118 */
6119function signInWithEmailLink(auth, email, emailLink) {
6120 return __awaiter(this, void 0, void 0, function () {
6121 var authModular, credential;
6122 return __generator(this, function (_a) {
6123 authModular = getModularInstance(auth);
6124 credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
6125 // Check if the tenant ID in the email link matches the tenant ID on Auth
6126 // instance.
6127 _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* TENANT_ID_MISMATCH */);
6128 return [2 /*return*/, signInWithCredential(authModular, credential)];
6129 });
6130 });
6131}
6132
6133/**
6134 * @license
6135 * Copyright 2020 Google LLC
6136 *
6137 * Licensed under the Apache License, Version 2.0 (the "License");
6138 * you may not use this file except in compliance with the License.
6139 * You may obtain a copy of the License at
6140 *
6141 * http://www.apache.org/licenses/LICENSE-2.0
6142 *
6143 * Unless required by applicable law or agreed to in writing, software
6144 * distributed under the License is distributed on an "AS IS" BASIS,
6145 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6146 * See the License for the specific language governing permissions and
6147 * limitations under the License.
6148 */
6149function createAuthUri(auth, request) {
6150 return __awaiter(this, void 0, void 0, function () {
6151 return __generator(this, function (_a) {
6152 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:createAuthUri" /* CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
6153 });
6154 });
6155}
6156
6157/**
6158 * @license
6159 * Copyright 2020 Google LLC
6160 *
6161 * Licensed under the Apache License, Version 2.0 (the "License");
6162 * you may not use this file except in compliance with the License.
6163 * You may obtain a copy of the License at
6164 *
6165 * http://www.apache.org/licenses/LICENSE-2.0
6166 *
6167 * Unless required by applicable law or agreed to in writing, software
6168 * distributed under the License is distributed on an "AS IS" BASIS,
6169 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6170 * See the License for the specific language governing permissions and
6171 * limitations under the License.
6172 */
6173/**
6174 * Gets the list of possible sign in methods for the given email address.
6175 *
6176 * @remarks
6177 * This is useful to differentiate methods of sign-in for the same provider, eg.
6178 * {@link EmailAuthProvider} which has 2 methods of sign-in,
6179 * {@link SignInMethod}.EMAIL_PASSWORD and
6180 * {@link SignInMethod}.EMAIL_LINK.
6181 *
6182 * @param auth - The {@link Auth} instance.
6183 * @param email - The user's email address.
6184 *
6185 * @public
6186 */
6187function fetchSignInMethodsForEmail(auth, email) {
6188 return __awaiter(this, void 0, void 0, function () {
6189 var continueUri, request, signinMethods;
6190 return __generator(this, function (_a) {
6191 switch (_a.label) {
6192 case 0:
6193 continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
6194 request = {
6195 identifier: email,
6196 continueUri: continueUri
6197 };
6198 return [4 /*yield*/, createAuthUri(getModularInstance(auth), request)];
6199 case 1:
6200 signinMethods = (_a.sent()).signinMethods;
6201 return [2 /*return*/, signinMethods || []];
6202 }
6203 });
6204 });
6205}
6206/**
6207 * Sends a verification email to a user.
6208 *
6209 * @remarks
6210 * The verification process is completed by calling {@link applyActionCode}.
6211 *
6212 * @example
6213 * ```javascript
6214 * const actionCodeSettings = {
6215 * url: 'https://www.example.com/?email=user@example.com',
6216 * iOS: {
6217 * bundleId: 'com.example.ios'
6218 * },
6219 * android: {
6220 * packageName: 'com.example.android',
6221 * installApp: true,
6222 * minimumVersion: '12'
6223 * },
6224 * handleCodeInApp: true
6225 * };
6226 * await sendEmailVerification(user, actionCodeSettings);
6227 * // Obtain code from the user.
6228 * await applyActionCode(auth, code);
6229 * ```
6230 *
6231 * @param user - The user.
6232 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6233 *
6234 * @public
6235 */
6236function sendEmailVerification(user, actionCodeSettings) {
6237 return __awaiter(this, void 0, void 0, function () {
6238 var userInternal, idToken, request, email;
6239 return __generator(this, function (_a) {
6240 switch (_a.label) {
6241 case 0:
6242 userInternal = getModularInstance(user);
6243 return [4 /*yield*/, user.getIdToken()];
6244 case 1:
6245 idToken = _a.sent();
6246 request = {
6247 requestType: "VERIFY_EMAIL" /* VERIFY_EMAIL */,
6248 idToken: idToken
6249 };
6250 if (actionCodeSettings) {
6251 _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
6252 }
6253 return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
6254 case 2:
6255 email = (_a.sent()).email;
6256 if (!(email !== user.email)) return [3 /*break*/, 4];
6257 return [4 /*yield*/, user.reload()];
6258 case 3:
6259 _a.sent();
6260 _a.label = 4;
6261 case 4: return [2 /*return*/];
6262 }
6263 });
6264 });
6265}
6266/**
6267 * Sends a verification email to a new email address.
6268 *
6269 * @remarks
6270 * The user's email will be updated to the new one after being verified.
6271 *
6272 * If you have a custom email action handler, you can complete the verification process by calling
6273 * {@link applyActionCode}.
6274 *
6275 * @example
6276 * ```javascript
6277 * const actionCodeSettings = {
6278 * url: 'https://www.example.com/?email=user@example.com',
6279 * iOS: {
6280 * bundleId: 'com.example.ios'
6281 * },
6282 * android: {
6283 * packageName: 'com.example.android',
6284 * installApp: true,
6285 * minimumVersion: '12'
6286 * },
6287 * handleCodeInApp: true
6288 * };
6289 * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
6290 * // Obtain code from the user.
6291 * await applyActionCode(auth, code);
6292 * ```
6293 *
6294 * @param user - The user.
6295 * @param newEmail - The new email address to be verified before update.
6296 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6297 *
6298 * @public
6299 */
6300function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
6301 return __awaiter(this, void 0, void 0, function () {
6302 var userInternal, idToken, request, email;
6303 return __generator(this, function (_a) {
6304 switch (_a.label) {
6305 case 0:
6306 userInternal = getModularInstance(user);
6307 return [4 /*yield*/, user.getIdToken()];
6308 case 1:
6309 idToken = _a.sent();
6310 request = {
6311 requestType: "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */,
6312 idToken: idToken,
6313 newEmail: newEmail
6314 };
6315 if (actionCodeSettings) {
6316 _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
6317 }
6318 return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
6319 case 2:
6320 email = (_a.sent()).email;
6321 if (!(email !== user.email)) return [3 /*break*/, 4];
6322 // If the local copy of the email on user is outdated, reload the
6323 // user.
6324 return [4 /*yield*/, user.reload()];
6325 case 3:
6326 // If the local copy of the email on user is outdated, reload the
6327 // user.
6328 _a.sent();
6329 _a.label = 4;
6330 case 4: return [2 /*return*/];
6331 }
6332 });
6333 });
6334}
6335
6336/**
6337 * @license
6338 * Copyright 2020 Google LLC
6339 *
6340 * Licensed under the Apache License, Version 2.0 (the "License");
6341 * you may not use this file except in compliance with the License.
6342 * You may obtain a copy of the License at
6343 *
6344 * http://www.apache.org/licenses/LICENSE-2.0
6345 *
6346 * Unless required by applicable law or agreed to in writing, software
6347 * distributed under the License is distributed on an "AS IS" BASIS,
6348 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6349 * See the License for the specific language governing permissions and
6350 * limitations under the License.
6351 */
6352function updateProfile$1(auth, request) {
6353 return __awaiter(this, void 0, void 0, function () {
6354 return __generator(this, function (_a) {
6355 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
6356 });
6357 });
6358}
6359
6360/**
6361 * @license
6362 * Copyright 2020 Google LLC
6363 *
6364 * Licensed under the Apache License, Version 2.0 (the "License");
6365 * you may not use this file except in compliance with the License.
6366 * You may obtain a copy of the License at
6367 *
6368 * http://www.apache.org/licenses/LICENSE-2.0
6369 *
6370 * Unless required by applicable law or agreed to in writing, software
6371 * distributed under the License is distributed on an "AS IS" BASIS,
6372 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6373 * See the License for the specific language governing permissions and
6374 * limitations under the License.
6375 */
6376/**
6377 * Updates a user's profile data.
6378 *
6379 * @param user - The user.
6380 * @param profile - The profile's `displayName` and `photoURL` to update.
6381 *
6382 * @public
6383 */
6384function updateProfile(user, _a) {
6385 var displayName = _a.displayName, photoUrl = _a.photoURL;
6386 return __awaiter(this, void 0, void 0, function () {
6387 var userInternal, idToken, profileRequest, response, passwordProvider;
6388 return __generator(this, function (_b) {
6389 switch (_b.label) {
6390 case 0:
6391 if (displayName === undefined && photoUrl === undefined) {
6392 return [2 /*return*/];
6393 }
6394 userInternal = getModularInstance(user);
6395 return [4 /*yield*/, userInternal.getIdToken()];
6396 case 1:
6397 idToken = _b.sent();
6398 profileRequest = {
6399 idToken: idToken,
6400 displayName: displayName,
6401 photoUrl: photoUrl,
6402 returnSecureToken: true
6403 };
6404 return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
6405 case 2:
6406 response = _b.sent();
6407 userInternal.displayName = response.displayName || null;
6408 userInternal.photoURL = response.photoUrl || null;
6409 passwordProvider = userInternal.providerData.find(function (_a) {
6410 var providerId = _a.providerId;
6411 return providerId === "password" /* PASSWORD */;
6412 });
6413 if (passwordProvider) {
6414 passwordProvider.displayName = userInternal.displayName;
6415 passwordProvider.photoURL = userInternal.photoURL;
6416 }
6417 return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
6418 case 3:
6419 _b.sent();
6420 return [2 /*return*/];
6421 }
6422 });
6423 });
6424}
6425/**
6426 * Updates the user's email address.
6427 *
6428 * @remarks
6429 * An email will be sent to the original email address (if it was set) that allows to revoke the
6430 * email address change, in order to protect them from account hijacking.
6431 *
6432 * Important: this is a security sensitive operation that requires the user to have recently signed
6433 * in. If this requirement isn't met, ask the user to authenticate again and then call
6434 * {@link reauthenticateWithCredential}.
6435 *
6436 * @param user - The user.
6437 * @param newEmail - The new email address.
6438 *
6439 * @public
6440 */
6441function updateEmail(user, newEmail) {
6442 return updateEmailOrPassword(getModularInstance(user), newEmail, null);
6443}
6444/**
6445 * Updates the user's password.
6446 *
6447 * @remarks
6448 * Important: this is a security sensitive operation that requires the user to have recently signed
6449 * in. If this requirement isn't met, ask the user to authenticate again and then call
6450 * {@link reauthenticateWithCredential}.
6451 *
6452 * @param user - The user.
6453 * @param newPassword - The new password.
6454 *
6455 * @public
6456 */
6457function updatePassword(user, newPassword) {
6458 return updateEmailOrPassword(getModularInstance(user), null, newPassword);
6459}
6460function updateEmailOrPassword(user, email, password) {
6461 return __awaiter(this, void 0, void 0, function () {
6462 var auth, idToken, request, response;
6463 return __generator(this, function (_a) {
6464 switch (_a.label) {
6465 case 0:
6466 auth = user.auth;
6467 return [4 /*yield*/, user.getIdToken()];
6468 case 1:
6469 idToken = _a.sent();
6470 request = {
6471 idToken: idToken,
6472 returnSecureToken: true
6473 };
6474 if (email) {
6475 request.email = email;
6476 }
6477 if (password) {
6478 request.password = password;
6479 }
6480 return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
6481 case 2:
6482 response = _a.sent();
6483 return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
6484 case 3:
6485 _a.sent();
6486 return [2 /*return*/];
6487 }
6488 });
6489 });
6490}
6491
6492/**
6493 * @license
6494 * Copyright 2019 Google LLC
6495 *
6496 * Licensed under the Apache License, Version 2.0 (the "License");
6497 * you may not use this file except in compliance with the License.
6498 * You may obtain a copy of the License at
6499 *
6500 * http://www.apache.org/licenses/LICENSE-2.0
6501 *
6502 * Unless required by applicable law or agreed to in writing, software
6503 * distributed under the License is distributed on an "AS IS" BASIS,
6504 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6505 * See the License for the specific language governing permissions and
6506 * limitations under the License.
6507 */
6508/**
6509 * Parse the `AdditionalUserInfo` from the ID token response.
6510 *
6511 */
6512function _fromIdTokenResponse(idTokenResponse) {
6513 var _a, _b;
6514 if (!idTokenResponse) {
6515 return null;
6516 }
6517 var providerId = idTokenResponse.providerId;
6518 var profile = idTokenResponse.rawUserInfo
6519 ? JSON.parse(idTokenResponse.rawUserInfo)
6520 : {};
6521 var isNewUser = idTokenResponse.isNewUser ||
6522 idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* SignupNewUser */;
6523 if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
6524 var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
6525 if (signInProvider) {
6526 var filteredProviderId = signInProvider !== "anonymous" /* ANONYMOUS */ &&
6527 signInProvider !== "custom" /* CUSTOM */
6528 ? signInProvider
6529 : null;
6530 // Uses generic class in accordance with the legacy SDK.
6531 return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
6532 }
6533 }
6534 if (!providerId) {
6535 return null;
6536 }
6537 switch (providerId) {
6538 case "facebook.com" /* FACEBOOK */:
6539 return new FacebookAdditionalUserInfo(isNewUser, profile);
6540 case "github.com" /* GITHUB */:
6541 return new GithubAdditionalUserInfo(isNewUser, profile);
6542 case "google.com" /* GOOGLE */:
6543 return new GoogleAdditionalUserInfo(isNewUser, profile);
6544 case "twitter.com" /* TWITTER */:
6545 return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
6546 case "custom" /* CUSTOM */:
6547 case "anonymous" /* ANONYMOUS */:
6548 return new GenericAdditionalUserInfo(isNewUser, null);
6549 default:
6550 return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
6551 }
6552}
6553var GenericAdditionalUserInfo = /** @class */ (function () {
6554 function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
6555 if (profile === void 0) { profile = {}; }
6556 this.isNewUser = isNewUser;
6557 this.providerId = providerId;
6558 this.profile = profile;
6559 }
6560 return GenericAdditionalUserInfo;
6561}());
6562var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
6563 __extends(FederatedAdditionalUserInfoWithUsername, _super);
6564 function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
6565 var _this = _super.call(this, isNewUser, providerId, profile) || this;
6566 _this.username = username;
6567 return _this;
6568 }
6569 return FederatedAdditionalUserInfoWithUsername;
6570}(GenericAdditionalUserInfo));
6571var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
6572 __extends(FacebookAdditionalUserInfo, _super);
6573 function FacebookAdditionalUserInfo(isNewUser, profile) {
6574 return _super.call(this, isNewUser, "facebook.com" /* FACEBOOK */, profile) || this;
6575 }
6576 return FacebookAdditionalUserInfo;
6577}(GenericAdditionalUserInfo));
6578var GithubAdditionalUserInfo = /** @class */ (function (_super) {
6579 __extends(GithubAdditionalUserInfo, _super);
6580 function GithubAdditionalUserInfo(isNewUser, profile) {
6581 return _super.call(this, isNewUser, "github.com" /* GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null) || this;
6582 }
6583 return GithubAdditionalUserInfo;
6584}(FederatedAdditionalUserInfoWithUsername));
6585var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
6586 __extends(GoogleAdditionalUserInfo, _super);
6587 function GoogleAdditionalUserInfo(isNewUser, profile) {
6588 return _super.call(this, isNewUser, "google.com" /* GOOGLE */, profile) || this;
6589 }
6590 return GoogleAdditionalUserInfo;
6591}(GenericAdditionalUserInfo));
6592var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
6593 __extends(TwitterAdditionalUserInfo, _super);
6594 function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
6595 return _super.call(this, isNewUser, "twitter.com" /* TWITTER */, profile, screenName) || this;
6596 }
6597 return TwitterAdditionalUserInfo;
6598}(FederatedAdditionalUserInfoWithUsername));
6599/**
6600 * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
6601 *
6602 * @param userCredential - The user credential.
6603 *
6604 * @public
6605 */
6606function getAdditionalUserInfo(userCredential) {
6607 var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
6608 if (user.isAnonymous && !_tokenResponse) {
6609 // Handle the special case where signInAnonymously() gets called twice.
6610 // No network call is made so there's nothing to actually fill this in
6611 return {
6612 providerId: null,
6613 isNewUser: false,
6614 profile: null
6615 };
6616 }
6617 return _fromIdTokenResponse(_tokenResponse);
6618}
6619
6620/**
6621 * @license
6622 * Copyright 2020 Google LLC
6623 *
6624 * Licensed under the Apache License, Version 2.0 (the "License");
6625 * you may not use this file except in compliance with the License.
6626 * You may obtain a copy of the License at
6627 *
6628 * http://www.apache.org/licenses/LICENSE-2.0
6629 *
6630 * Unless required by applicable law or agreed to in writing, software
6631 * distributed under the License is distributed on an "AS IS" BASIS,
6632 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6633 * See the License for the specific language governing permissions and
6634 * limitations under the License.
6635 */
6636// Non-optional auth methods.
6637/**
6638 * Changes the type of persistence on the {@link Auth} instance for the currently saved
6639 * `Auth` session and applies this type of persistence for future sign-in requests, including
6640 * sign-in with redirect requests.
6641 *
6642 * @remarks
6643 * This makes it easy for a user signing in to specify whether their session should be
6644 * remembered or not. It also makes it easier to never persist the `Auth` state for applications
6645 * that are shared by other users or have sensitive data.
6646 *
6647 * @example
6648 * ```javascript
6649 * setPersistence(auth, browserSessionPersistence);
6650 * ```
6651 *
6652 * @param auth - The {@link Auth} instance.
6653 * @param persistence - The {@link Persistence} to use.
6654 * @returns A `Promise` that resolves once the persistence change has completed
6655 *
6656 * @public
6657 */
6658function setPersistence(auth, persistence) {
6659 return getModularInstance(auth).setPersistence(persistence);
6660}
6661/**
6662 * Adds an observer for changes to the signed-in user's ID token, which includes sign-in,
6663 * sign-out, and token refresh events.
6664 *
6665 * @param auth - The {@link Auth} instance.
6666 * @param nextOrObserver - callback triggered on change.
6667 * @param error - callback triggered on error.
6668 * @param completed - callback triggered when observer is removed.
6669 *
6670 * @public
6671 */
6672function onIdTokenChanged(auth, nextOrObserver, error, completed) {
6673 return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
6674}
6675/**
6676 * Adds a blocking callback that runs before an auth state change
6677 * sets a new user.
6678 *
6679 * @param auth - The {@link Auth} instance.
6680 * @param callback - callback triggered before new user value is set.
6681 * If this throws, it blocks the user from being set.
6682 * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
6683 * callback throws, allowing you to undo any side effects.
6684 */
6685function beforeAuthStateChanged(auth, callback, onAbort) {
6686 return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
6687}
6688/**
6689 * Adds an observer for changes to the user's sign-in state.
6690 *
6691 * @remarks
6692 * To keep the old behavior, see {@link onIdTokenChanged}.
6693 *
6694 * @param auth - The {@link Auth} instance.
6695 * @param nextOrObserver - callback triggered on change.
6696 * @param error - callback triggered on error.
6697 * @param completed - callback triggered when observer is removed.
6698 *
6699 * @public
6700 */
6701function onAuthStateChanged(auth, nextOrObserver, error, completed) {
6702 return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
6703}
6704/**
6705 * Sets the current language to the default device/browser preference.
6706 *
6707 * @param auth - The {@link Auth} instance.
6708 *
6709 * @public
6710 */
6711function useDeviceLanguage(auth) {
6712 getModularInstance(auth).useDeviceLanguage();
6713}
6714/**
6715 * Asynchronously sets the provided user as {@link Auth.currentUser} on the
6716 * {@link Auth} instance.
6717 *
6718 * @remarks
6719 * A new instance copy of the user provided will be made and set as currentUser.
6720 *
6721 * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
6722 * like other sign in methods.
6723 *
6724 * The operation fails with an error if the user to be updated belongs to a different Firebase
6725 * project.
6726 *
6727 * @param auth - The {@link Auth} instance.
6728 * @param user - The new {@link User}.
6729 *
6730 * @public
6731 */
6732function updateCurrentUser(auth, user) {
6733 return getModularInstance(auth).updateCurrentUser(user);
6734}
6735/**
6736 * Signs out the current user.
6737 *
6738 * @param auth - The {@link Auth} instance.
6739 *
6740 * @public
6741 */
6742function signOut(auth) {
6743 return getModularInstance(auth).signOut();
6744}
6745/**
6746 * Deletes and signs out the user.
6747 *
6748 * @remarks
6749 * Important: this is a security-sensitive operation that requires the user to have recently
6750 * signed in. If this requirement isn't met, ask the user to authenticate again and then call
6751 * {@link reauthenticateWithCredential}.
6752 *
6753 * @param user - The user.
6754 *
6755 * @public
6756 */
6757function deleteUser(user) {
6758 return __awaiter(this, void 0, void 0, function () {
6759 return __generator(this, function (_a) {
6760 return [2 /*return*/, getModularInstance(user).delete()];
6761 });
6762 });
6763}
6764
6765var MultiFactorSessionImpl = /** @class */ (function () {
6766 function MultiFactorSessionImpl(type, credential) {
6767 this.type = type;
6768 this.credential = credential;
6769 }
6770 MultiFactorSessionImpl._fromIdtoken = function (idToken) {
6771 return new MultiFactorSessionImpl("enroll" /* ENROLL */, idToken);
6772 };
6773 MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
6774 return new MultiFactorSessionImpl("signin" /* SIGN_IN */, mfaPendingCredential);
6775 };
6776 MultiFactorSessionImpl.prototype.toJSON = function () {
6777 var _a;
6778 var key = this.type === "enroll" /* ENROLL */
6779 ? 'idToken'
6780 : 'pendingCredential';
6781 return {
6782 multiFactorSession: (_a = {},
6783 _a[key] = this.credential,
6784 _a)
6785 };
6786 };
6787 MultiFactorSessionImpl.fromJSON = function (obj) {
6788 var _a, _b;
6789 if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
6790 if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
6791 return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
6792 }
6793 else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
6794 return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
6795 }
6796 }
6797 return null;
6798 };
6799 return MultiFactorSessionImpl;
6800}());
6801
6802/**
6803 * @license
6804 * Copyright 2020 Google LLC
6805 *
6806 * Licensed under the Apache License, Version 2.0 (the "License");
6807 * you may not use this file except in compliance with the License.
6808 * You may obtain a copy of the License at
6809 *
6810 * http://www.apache.org/licenses/LICENSE-2.0
6811 *
6812 * Unless required by applicable law or agreed to in writing, software
6813 * distributed under the License is distributed on an "AS IS" BASIS,
6814 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6815 * See the License for the specific language governing permissions and
6816 * limitations under the License.
6817 */
6818var MultiFactorResolverImpl = /** @class */ (function () {
6819 function MultiFactorResolverImpl(session, hints, signInResolver) {
6820 this.session = session;
6821 this.hints = hints;
6822 this.signInResolver = signInResolver;
6823 }
6824 /** @internal */
6825 MultiFactorResolverImpl._fromError = function (authExtern, error) {
6826 var _this = this;
6827 var auth = _castAuth(authExtern);
6828 var serverResponse = error.customData._serverResponse;
6829 var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
6830 return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
6831 });
6832 _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* INTERNAL_ERROR */);
6833 var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
6834 return new MultiFactorResolverImpl(session, hints, function (assertion) { return __awaiter(_this, void 0, void 0, function () {
6835 var mfaResponse, idTokenResponse, _a, userCredential;
6836 return __generator(this, function (_b) {
6837 switch (_b.label) {
6838 case 0: return [4 /*yield*/, assertion._process(auth, session)];
6839 case 1:
6840 mfaResponse = _b.sent();
6841 // Clear out the unneeded fields from the old login response
6842 delete serverResponse.mfaInfo;
6843 delete serverResponse.mfaPendingCredential;
6844 idTokenResponse = __assign(__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
6845 _a = error.operationType;
6846 switch (_a) {
6847 case "signIn" /* SIGN_IN */: return [3 /*break*/, 2];
6848 case "reauthenticate" /* REAUTHENTICATE */: return [3 /*break*/, 5];
6849 }
6850 return [3 /*break*/, 6];
6851 case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
6852 case 3:
6853 userCredential = _b.sent();
6854 return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
6855 case 4:
6856 _b.sent();
6857 return [2 /*return*/, userCredential];
6858 case 5:
6859 _assert(error.user, auth, "internal-error" /* INTERNAL_ERROR */);
6860 return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
6861 case 6:
6862 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
6863 _b.label = 7;
6864 case 7: return [2 /*return*/];
6865 }
6866 });
6867 }); });
6868 };
6869 MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
6870 return __awaiter(this, void 0, void 0, function () {
6871 var assertion;
6872 return __generator(this, function (_a) {
6873 assertion = assertionExtern;
6874 return [2 /*return*/, this.signInResolver(assertion)];
6875 });
6876 });
6877 };
6878 return MultiFactorResolverImpl;
6879}());
6880/**
6881 * Provides a {@link MultiFactorResolver} suitable for completion of a
6882 * multi-factor flow.
6883 *
6884 * @param auth - The {@link Auth} instance.
6885 * @param error - The {@link MultiFactorError} raised during a sign-in, or
6886 * reauthentication operation.
6887 *
6888 * @public
6889 */
6890function getMultiFactorResolver(auth, error) {
6891 var _a;
6892 var authModular = getModularInstance(auth);
6893 var errorInternal = error;
6894 _assert(error.customData.operationType, authModular, "argument-error" /* ARGUMENT_ERROR */);
6895 _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* ARGUMENT_ERROR */);
6896 return MultiFactorResolverImpl._fromError(authModular, errorInternal);
6897}
6898
6899/**
6900 * @license
6901 * Copyright 2020 Google LLC
6902 *
6903 * Licensed under the Apache License, Version 2.0 (the "License");
6904 * you may not use this file except in compliance with the License.
6905 * You may obtain a copy of the License at
6906 *
6907 * http://www.apache.org/licenses/LICENSE-2.0
6908 *
6909 * Unless required by applicable law or agreed to in writing, software
6910 * distributed under the License is distributed on an "AS IS" BASIS,
6911 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6912 * See the License for the specific language governing permissions and
6913 * limitations under the License.
6914 */
6915function startEnrollPhoneMfa(auth, request) {
6916 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:start" /* START_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
6917}
6918function finalizeEnrollPhoneMfa(auth, request) {
6919 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:finalize" /* FINALIZE_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
6920}
6921function withdrawMfa(auth, request) {
6922 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:withdraw" /* WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
6923}
6924
6925var MultiFactorUserImpl = /** @class */ (function () {
6926 function MultiFactorUserImpl(user) {
6927 var _this = this;
6928 this.user = user;
6929 this.enrolledFactors = [];
6930 user._onReload(function (userInfo) {
6931 if (userInfo.mfaInfo) {
6932 _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
6933 return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
6934 });
6935 }
6936 });
6937 }
6938 MultiFactorUserImpl._fromUser = function (user) {
6939 return new MultiFactorUserImpl(user);
6940 };
6941 MultiFactorUserImpl.prototype.getSession = function () {
6942 return __awaiter(this, void 0, void 0, function () {
6943 var _a, _b;
6944 return __generator(this, function (_c) {
6945 switch (_c.label) {
6946 case 0:
6947 _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
6948 return [4 /*yield*/, this.user.getIdToken()];
6949 case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
6950 }
6951 });
6952 });
6953 };
6954 MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
6955 return __awaiter(this, void 0, void 0, function () {
6956 var assertion, session, finalizeMfaResponse;
6957 return __generator(this, function (_a) {
6958 switch (_a.label) {
6959 case 0:
6960 assertion = assertionExtern;
6961 return [4 /*yield*/, this.getSession()];
6962 case 1:
6963 session = (_a.sent());
6964 return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
6965 case 2:
6966 finalizeMfaResponse = _a.sent();
6967 // New tokens will be issued after enrollment of the new second factors.
6968 // They need to be updated on the user.
6969 return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
6970 case 3:
6971 // New tokens will be issued after enrollment of the new second factors.
6972 // They need to be updated on the user.
6973 _a.sent();
6974 // The user needs to be reloaded to get the new multi-factor information
6975 // from server. USER_RELOADED event will be triggered and `enrolledFactors`
6976 // will be updated.
6977 return [2 /*return*/, this.user.reload()];
6978 }
6979 });
6980 });
6981 };
6982 MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
6983 return __awaiter(this, void 0, void 0, function () {
6984 var mfaEnrollmentId, idToken, idTokenResponse, e_1;
6985 return __generator(this, function (_a) {
6986 switch (_a.label) {
6987 case 0:
6988 mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
6989 return [4 /*yield*/, this.user.getIdToken()];
6990 case 1:
6991 idToken = _a.sent();
6992 return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
6993 idToken: idToken,
6994 mfaEnrollmentId: mfaEnrollmentId
6995 }))];
6996 case 2:
6997 idTokenResponse = _a.sent();
6998 // Remove the second factor from the user's list.
6999 this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
7000 var uid = _a.uid;
7001 return uid !== mfaEnrollmentId;
7002 });
7003 // Depending on whether the backend decided to revoke the user's session,
7004 // the tokenResponse may be empty. If the tokens were not updated (and they
7005 // are now invalid), reloading the user will discover this and invalidate
7006 // the user's state accordingly.
7007 return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
7008 case 3:
7009 // Depending on whether the backend decided to revoke the user's session,
7010 // the tokenResponse may be empty. If the tokens were not updated (and they
7011 // are now invalid), reloading the user will discover this and invalidate
7012 // the user's state accordingly.
7013 _a.sent();
7014 _a.label = 4;
7015 case 4:
7016 _a.trys.push([4, 6, , 7]);
7017 return [4 /*yield*/, this.user.reload()];
7018 case 5:
7019 _a.sent();
7020 return [3 /*break*/, 7];
7021 case 6:
7022 e_1 = _a.sent();
7023 if (e_1.code !== "auth/" + "user-token-expired" /* TOKEN_EXPIRED */) {
7024 throw e_1;
7025 }
7026 return [3 /*break*/, 7];
7027 case 7: return [2 /*return*/];
7028 }
7029 });
7030 });
7031 };
7032 return MultiFactorUserImpl;
7033}());
7034var multiFactorUserCache = new WeakMap();
7035/**
7036 * The {@link MultiFactorUser} corresponding to the user.
7037 *
7038 * @remarks
7039 * This is used to access all multi-factor properties and operations related to the user.
7040 *
7041 * @param user - The user.
7042 *
7043 * @public
7044 */
7045function multiFactor(user) {
7046 var userModular = getModularInstance(user);
7047 if (!multiFactorUserCache.has(userModular)) {
7048 multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
7049 }
7050 return multiFactorUserCache.get(userModular);
7051}
7052
7053var STORAGE_AVAILABLE_KEY = '__sak';
7054
7055/**
7056 * @license
7057 * Copyright 2019 Google LLC
7058 *
7059 * Licensed under the Apache License, Version 2.0 (the "License");
7060 * you may not use this file except in compliance with the License.
7061 * You may obtain a copy of the License at
7062 *
7063 * http://www.apache.org/licenses/LICENSE-2.0
7064 *
7065 * Unless required by applicable law or agreed to in writing, software
7066 * distributed under the License is distributed on an "AS IS" BASIS,
7067 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7068 * See the License for the specific language governing permissions and
7069 * limitations under the License.
7070 */
7071// There are two different browser persistence types: local and session.
7072// Both have the same implementation but use a different underlying storage
7073// object.
7074var BrowserPersistenceClass = /** @class */ (function () {
7075 function BrowserPersistenceClass(storageRetriever, type) {
7076 this.storageRetriever = storageRetriever;
7077 this.type = type;
7078 }
7079 BrowserPersistenceClass.prototype._isAvailable = function () {
7080 try {
7081 if (!this.storage) {
7082 return Promise.resolve(false);
7083 }
7084 this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
7085 this.storage.removeItem(STORAGE_AVAILABLE_KEY);
7086 return Promise.resolve(true);
7087 }
7088 catch (_a) {
7089 return Promise.resolve(false);
7090 }
7091 };
7092 BrowserPersistenceClass.prototype._set = function (key, value) {
7093 this.storage.setItem(key, JSON.stringify(value));
7094 return Promise.resolve();
7095 };
7096 BrowserPersistenceClass.prototype._get = function (key) {
7097 var json = this.storage.getItem(key);
7098 return Promise.resolve(json ? JSON.parse(json) : null);
7099 };
7100 BrowserPersistenceClass.prototype._remove = function (key) {
7101 this.storage.removeItem(key);
7102 return Promise.resolve();
7103 };
7104 Object.defineProperty(BrowserPersistenceClass.prototype, "storage", {
7105 get: function () {
7106 return this.storageRetriever();
7107 },
7108 enumerable: false,
7109 configurable: true
7110 });
7111 return BrowserPersistenceClass;
7112}());
7113
7114/**
7115 * @license
7116 * Copyright 2020 Google LLC
7117 *
7118 * Licensed under the Apache License, Version 2.0 (the "License");
7119 * you may not use this file except in compliance with the License.
7120 * You may obtain a copy of the License at
7121 *
7122 * http://www.apache.org/licenses/LICENSE-2.0
7123 *
7124 * Unless required by applicable law or agreed to in writing, software
7125 * distributed under the License is distributed on an "AS IS" BASIS,
7126 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7127 * See the License for the specific language governing permissions and
7128 * limitations under the License.
7129 */
7130function _iframeCannotSyncWebStorage() {
7131 var ua = getUA();
7132 return _isSafari(ua) || _isIOS(ua);
7133}
7134// The polling period in case events are not supported
7135var _POLLING_INTERVAL_MS$1 = 1000;
7136// The IE 10 localStorage cross tab synchronization delay in milliseconds
7137var IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
7138var BrowserLocalPersistence = /** @class */ (function (_super) {
7139 __extends(BrowserLocalPersistence, _super);
7140 function BrowserLocalPersistence() {
7141 var _this = _super.call(this, function () { return window.localStorage; }, "LOCAL" /* LOCAL */) || this;
7142 _this.boundEventHandler = function (event, poll) { return _this.onStorageEvent(event, poll); };
7143 _this.listeners = {};
7144 _this.localCache = {};
7145 // setTimeout return value is platform specific
7146 // eslint-disable-next-line @typescript-eslint/no-explicit-any
7147 _this.pollTimer = null;
7148 // Safari or iOS browser and embedded in an iframe.
7149 _this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();
7150 // Whether to use polling instead of depending on window events
7151 _this.fallbackToPolling = _isMobileBrowser();
7152 _this._shouldAllowMigration = true;
7153 return _this;
7154 }
7155 BrowserLocalPersistence.prototype.forAllChangedKeys = function (cb) {
7156 // Check all keys with listeners on them.
7157 for (var _i = 0, _a = Object.keys(this.listeners); _i < _a.length; _i++) {
7158 var key = _a[_i];
7159 // Get value from localStorage.
7160 var newValue = this.storage.getItem(key);
7161 var oldValue = this.localCache[key];
7162 // If local map value does not match, trigger listener with storage event.
7163 // Differentiate this simulated event from the real storage event.
7164 if (newValue !== oldValue) {
7165 cb(key, oldValue, newValue);
7166 }
7167 }
7168 };
7169 BrowserLocalPersistence.prototype.onStorageEvent = function (event, poll) {
7170 var _this = this;
7171 if (poll === void 0) { poll = false; }
7172 // Key would be null in some situations, like when localStorage is cleared
7173 if (!event.key) {
7174 this.forAllChangedKeys(function (key, _oldValue, newValue) {
7175 _this.notifyListeners(key, newValue);
7176 });
7177 return;
7178 }
7179 var key = event.key;
7180 // Check the mechanism how this event was detected.
7181 // The first event will dictate the mechanism to be used.
7182 if (poll) {
7183 // Environment detects storage changes via polling.
7184 // Remove storage event listener to prevent possible event duplication.
7185 this.detachListener();
7186 }
7187 else {
7188 // Environment detects storage changes via storage event listener.
7189 // Remove polling listener to prevent possible event duplication.
7190 this.stopPolling();
7191 }
7192 // Safari embedded iframe. Storage event will trigger with the delta
7193 // changes but no changes will be applied to the iframe localStorage.
7194 if (this.safariLocalStorageNotSynced) {
7195 // Get current iframe page value.
7196 var storedValue_1 = this.storage.getItem(key);
7197 // Value not synchronized, synchronize manually.
7198 if (event.newValue !== storedValue_1) {
7199 if (event.newValue !== null) {
7200 // Value changed from current value.
7201 this.storage.setItem(key, event.newValue);
7202 }
7203 else {
7204 // Current value deleted.
7205 this.storage.removeItem(key);
7206 }
7207 }
7208 else if (this.localCache[key] === event.newValue && !poll) {
7209 // Already detected and processed, do not trigger listeners again.
7210 return;
7211 }
7212 }
7213 var triggerListeners = function () {
7214 // Keep local map up to date in case storage event is triggered before
7215 // poll.
7216 var storedValue = _this.storage.getItem(key);
7217 if (!poll && _this.localCache[key] === storedValue) {
7218 // Real storage event which has already been detected, do nothing.
7219 // This seems to trigger in some IE browsers for some reason.
7220 return;
7221 }
7222 _this.notifyListeners(key, storedValue);
7223 };
7224 var storedValue = this.storage.getItem(key);
7225 if (_isIE10() &&
7226 storedValue !== event.newValue &&
7227 event.newValue !== event.oldValue) {
7228 // IE 10 has this weird bug where a storage event would trigger with the
7229 // correct key, oldValue and newValue but localStorage.getItem(key) does
7230 // not yield the updated value until a few milliseconds. This ensures
7231 // this recovers from that situation.
7232 setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
7233 }
7234 else {
7235 triggerListeners();
7236 }
7237 };
7238 BrowserLocalPersistence.prototype.notifyListeners = function (key, value) {
7239 this.localCache[key] = value;
7240 var listeners = this.listeners[key];
7241 if (listeners) {
7242 for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
7243 var listener = _a[_i];
7244 listener(value ? JSON.parse(value) : value);
7245 }
7246 }
7247 };
7248 BrowserLocalPersistence.prototype.startPolling = function () {
7249 var _this = this;
7250 this.stopPolling();
7251 this.pollTimer = setInterval(function () {
7252 _this.forAllChangedKeys(function (key, oldValue, newValue) {
7253 _this.onStorageEvent(new StorageEvent('storage', {
7254 key: key,
7255 oldValue: oldValue,
7256 newValue: newValue
7257 }),
7258 /* poll */ true);
7259 });
7260 }, _POLLING_INTERVAL_MS$1);
7261 };
7262 BrowserLocalPersistence.prototype.stopPolling = function () {
7263 if (this.pollTimer) {
7264 clearInterval(this.pollTimer);
7265 this.pollTimer = null;
7266 }
7267 };
7268 BrowserLocalPersistence.prototype.attachListener = function () {
7269 window.addEventListener('storage', this.boundEventHandler);
7270 };
7271 BrowserLocalPersistence.prototype.detachListener = function () {
7272 window.removeEventListener('storage', this.boundEventHandler);
7273 };
7274 BrowserLocalPersistence.prototype._addListener = function (key, listener) {
7275 if (Object.keys(this.listeners).length === 0) {
7276 // Whether browser can detect storage event when it had already been pushed to the background.
7277 // This may happen in some mobile browsers. A localStorage change in the foreground window
7278 // will not be detected in the background window via the storage event.
7279 // This was detected in iOS 7.x mobile browsers
7280 if (this.fallbackToPolling) {
7281 this.startPolling();
7282 }
7283 else {
7284 this.attachListener();
7285 }
7286 }
7287 if (!this.listeners[key]) {
7288 this.listeners[key] = new Set();
7289 // Populate the cache to avoid spuriously triggering on first poll.
7290 this.localCache[key] = this.storage.getItem(key);
7291 }
7292 this.listeners[key].add(listener);
7293 };
7294 BrowserLocalPersistence.prototype._removeListener = function (key, listener) {
7295 if (this.listeners[key]) {
7296 this.listeners[key].delete(listener);
7297 if (this.listeners[key].size === 0) {
7298 delete this.listeners[key];
7299 }
7300 }
7301 if (Object.keys(this.listeners).length === 0) {
7302 this.detachListener();
7303 this.stopPolling();
7304 }
7305 };
7306 // Update local cache on base operations:
7307 BrowserLocalPersistence.prototype._set = function (key, value) {
7308 return __awaiter(this, void 0, void 0, function () {
7309 return __generator(this, function (_a) {
7310 switch (_a.label) {
7311 case 0: return [4 /*yield*/, _super.prototype._set.call(this, key, value)];
7312 case 1:
7313 _a.sent();
7314 this.localCache[key] = JSON.stringify(value);
7315 return [2 /*return*/];
7316 }
7317 });
7318 });
7319 };
7320 BrowserLocalPersistence.prototype._get = function (key) {
7321 return __awaiter(this, void 0, void 0, function () {
7322 var value;
7323 return __generator(this, function (_a) {
7324 switch (_a.label) {
7325 case 0: return [4 /*yield*/, _super.prototype._get.call(this, key)];
7326 case 1:
7327 value = _a.sent();
7328 this.localCache[key] = JSON.stringify(value);
7329 return [2 /*return*/, value];
7330 }
7331 });
7332 });
7333 };
7334 BrowserLocalPersistence.prototype._remove = function (key) {
7335 return __awaiter(this, void 0, void 0, function () {
7336 return __generator(this, function (_a) {
7337 switch (_a.label) {
7338 case 0: return [4 /*yield*/, _super.prototype._remove.call(this, key)];
7339 case 1:
7340 _a.sent();
7341 delete this.localCache[key];
7342 return [2 /*return*/];
7343 }
7344 });
7345 });
7346 };
7347 BrowserLocalPersistence.type = 'LOCAL';
7348 return BrowserLocalPersistence;
7349}(BrowserPersistenceClass));
7350/**
7351 * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
7352 * for the underlying storage.
7353 *
7354 * @public
7355 */
7356var browserLocalPersistence = BrowserLocalPersistence;
7357
7358/**
7359 * @license
7360 * Copyright 2020 Google LLC
7361 *
7362 * Licensed under the Apache License, Version 2.0 (the "License");
7363 * you may not use this file except in compliance with the License.
7364 * You may obtain a copy of the License at
7365 *
7366 * http://www.apache.org/licenses/LICENSE-2.0
7367 *
7368 * Unless required by applicable law or agreed to in writing, software
7369 * distributed under the License is distributed on an "AS IS" BASIS,
7370 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7371 * See the License for the specific language governing permissions and
7372 * limitations under the License.
7373 */
7374var BrowserSessionPersistence = /** @class */ (function (_super) {
7375 __extends(BrowserSessionPersistence, _super);
7376 function BrowserSessionPersistence() {
7377 return _super.call(this, function () { return window.sessionStorage; }, "SESSION" /* SESSION */) || this;
7378 }
7379 BrowserSessionPersistence.prototype._addListener = function (_key, _listener) {
7380 // Listeners are not supported for session storage since it cannot be shared across windows
7381 return;
7382 };
7383 BrowserSessionPersistence.prototype._removeListener = function (_key, _listener) {
7384 // Listeners are not supported for session storage since it cannot be shared across windows
7385 return;
7386 };
7387 BrowserSessionPersistence.type = 'SESSION';
7388 return BrowserSessionPersistence;
7389}(BrowserPersistenceClass));
7390/**
7391 * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
7392 * for the underlying storage.
7393 *
7394 * @public
7395 */
7396var browserSessionPersistence = BrowserSessionPersistence;
7397
7398/**
7399 * @license
7400 * Copyright 2019 Google LLC
7401 *
7402 * Licensed under the Apache License, Version 2.0 (the "License");
7403 * you may not use this file except in compliance with the License.
7404 * You may obtain a copy of the License at
7405 *
7406 * http://www.apache.org/licenses/LICENSE-2.0
7407 *
7408 * Unless required by applicable law or agreed to in writing, software
7409 * distributed under the License is distributed on an "AS IS" BASIS,
7410 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7411 * See the License for the specific language governing permissions and
7412 * limitations under the License.
7413 */
7414/**
7415 * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
7416 *
7417 * @param promises - Array of promises to wait on.
7418 */
7419function _allSettled(promises) {
7420 var _this = this;
7421 return Promise.all(promises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
7422 var value, reason_1;
7423 return __generator(this, function (_a) {
7424 switch (_a.label) {
7425 case 0:
7426 _a.trys.push([0, 2, , 3]);
7427 return [4 /*yield*/, promise];
7428 case 1:
7429 value = _a.sent();
7430 return [2 /*return*/, {
7431 fulfilled: true,
7432 value: value
7433 }];
7434 case 2:
7435 reason_1 = _a.sent();
7436 return [2 /*return*/, {
7437 fulfilled: false,
7438 reason: reason_1
7439 }];
7440 case 3: return [2 /*return*/];
7441 }
7442 });
7443 }); }));
7444}
7445
7446/**
7447 * @license
7448 * Copyright 2019 Google LLC
7449 *
7450 * Licensed under the Apache License, Version 2.0 (the "License");
7451 * you may not use this file except in compliance with the License.
7452 * You may obtain a copy of the License at
7453 *
7454 * http://www.apache.org/licenses/LICENSE-2.0
7455 *
7456 * Unless required by applicable law or agreed to in writing, software
7457 * distributed under the License is distributed on an "AS IS" BASIS,
7458 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7459 * See the License for the specific language governing permissions and
7460 * limitations under the License.
7461 */
7462/**
7463 * Interface class for receiving messages.
7464 *
7465 */
7466var Receiver = /** @class */ (function () {
7467 function Receiver(eventTarget) {
7468 this.eventTarget = eventTarget;
7469 this.handlersMap = {};
7470 this.boundEventHandler = this.handleEvent.bind(this);
7471 }
7472 /**
7473 * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
7474 *
7475 * @param eventTarget - An event target (such as window or self) through which the underlying
7476 * messages will be received.
7477 */
7478 Receiver._getInstance = function (eventTarget) {
7479 // The results are stored in an array since objects can't be keys for other
7480 // objects. In addition, setting a unique property on an event target as a
7481 // hash map key may not be allowed due to CORS restrictions.
7482 var existingInstance = this.receivers.find(function (receiver) {
7483 return receiver.isListeningto(eventTarget);
7484 });
7485 if (existingInstance) {
7486 return existingInstance;
7487 }
7488 var newInstance = new Receiver(eventTarget);
7489 this.receivers.push(newInstance);
7490 return newInstance;
7491 };
7492 Receiver.prototype.isListeningto = function (eventTarget) {
7493 return this.eventTarget === eventTarget;
7494 };
7495 /**
7496 * Fans out a MessageEvent to the appropriate listeners.
7497 *
7498 * @remarks
7499 * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
7500 * finished processing.
7501 *
7502 * @param event - The MessageEvent.
7503 *
7504 */
7505 Receiver.prototype.handleEvent = function (event) {
7506 return __awaiter(this, void 0, void 0, function () {
7507 var messageEvent, _a, eventId, eventType, data, handlers, promises, response;
7508 var _this = this;
7509 return __generator(this, function (_b) {
7510 switch (_b.label) {
7511 case 0:
7512 messageEvent = event;
7513 _a = messageEvent.data, eventId = _a.eventId, eventType = _a.eventType, data = _a.data;
7514 handlers = this.handlersMap[eventType];
7515 if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
7516 return [2 /*return*/];
7517 }
7518 messageEvent.ports[0].postMessage({
7519 status: "ack" /* ACK */,
7520 eventId: eventId,
7521 eventType: eventType
7522 });
7523 promises = Array.from(handlers).map(function (handler) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
7524 return [2 /*return*/, handler(messageEvent.origin, data)];
7525 }); }); });
7526 return [4 /*yield*/, _allSettled(promises)];
7527 case 1:
7528 response = _b.sent();
7529 messageEvent.ports[0].postMessage({
7530 status: "done" /* DONE */,
7531 eventId: eventId,
7532 eventType: eventType,
7533 response: response
7534 });
7535 return [2 /*return*/];
7536 }
7537 });
7538 });
7539 };
7540 /**
7541 * Subscribe an event handler for a particular event.
7542 *
7543 * @param eventType - Event name to subscribe to.
7544 * @param eventHandler - The event handler which should receive the events.
7545 *
7546 */
7547 Receiver.prototype._subscribe = function (eventType, eventHandler) {
7548 if (Object.keys(this.handlersMap).length === 0) {
7549 this.eventTarget.addEventListener('message', this.boundEventHandler);
7550 }
7551 if (!this.handlersMap[eventType]) {
7552 this.handlersMap[eventType] = new Set();
7553 }
7554 this.handlersMap[eventType].add(eventHandler);
7555 };
7556 /**
7557 * Unsubscribe an event handler from a particular event.
7558 *
7559 * @param eventType - Event name to unsubscribe from.
7560 * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
7561 *
7562 */
7563 Receiver.prototype._unsubscribe = function (eventType, eventHandler) {
7564 if (this.handlersMap[eventType] && eventHandler) {
7565 this.handlersMap[eventType].delete(eventHandler);
7566 }
7567 if (!eventHandler || this.handlersMap[eventType].size === 0) {
7568 delete this.handlersMap[eventType];
7569 }
7570 if (Object.keys(this.handlersMap).length === 0) {
7571 this.eventTarget.removeEventListener('message', this.boundEventHandler);
7572 }
7573 };
7574 Receiver.receivers = [];
7575 return Receiver;
7576}());
7577
7578/**
7579 * @license
7580 * Copyright 2020 Google LLC
7581 *
7582 * Licensed under the Apache License, Version 2.0 (the "License");
7583 * you may not use this file except in compliance with the License.
7584 * You may obtain a copy of the License at
7585 *
7586 * http://www.apache.org/licenses/LICENSE-2.0
7587 *
7588 * Unless required by applicable law or agreed to in writing, software
7589 * distributed under the License is distributed on an "AS IS" BASIS,
7590 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7591 * See the License for the specific language governing permissions and
7592 * limitations under the License.
7593 */
7594function _generateEventId(prefix, digits) {
7595 if (prefix === void 0) { prefix = ''; }
7596 if (digits === void 0) { digits = 10; }
7597 var random = '';
7598 for (var i = 0; i < digits; i++) {
7599 random += Math.floor(Math.random() * 10);
7600 }
7601 return prefix + random;
7602}
7603
7604/**
7605 * @license
7606 * Copyright 2019 Google LLC
7607 *
7608 * Licensed under the Apache License, Version 2.0 (the "License");
7609 * you may not use this file except in compliance with the License.
7610 * You may obtain a copy of the License at
7611 *
7612 * http://www.apache.org/licenses/LICENSE-2.0
7613 *
7614 * Unless required by applicable law or agreed to in writing, software
7615 * distributed under the License is distributed on an "AS IS" BASIS,
7616 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7617 * See the License for the specific language governing permissions and
7618 * limitations under the License.
7619 */
7620/**
7621 * Interface for sending messages and waiting for a completion response.
7622 *
7623 */
7624var Sender = /** @class */ (function () {
7625 function Sender(target) {
7626 this.target = target;
7627 this.handlers = new Set();
7628 }
7629 /**
7630 * Unsubscribe the handler and remove it from our tracking Set.
7631 *
7632 * @param handler - The handler to unsubscribe.
7633 */
7634 Sender.prototype.removeMessageHandler = function (handler) {
7635 if (handler.messageChannel) {
7636 handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
7637 handler.messageChannel.port1.close();
7638 }
7639 this.handlers.delete(handler);
7640 };
7641 /**
7642 * Send a message to the Receiver located at {@link target}.
7643 *
7644 * @remarks
7645 * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
7646 * receiver has had a chance to fully process the event.
7647 *
7648 * @param eventType - Type of event to send.
7649 * @param data - The payload of the event.
7650 * @param timeout - Timeout for waiting on an ACK from the receiver.
7651 *
7652 * @returns An array of settled promises from all the handlers that were listening on the receiver.
7653 */
7654 Sender.prototype._send = function (eventType, data, timeout) {
7655 if (timeout === void 0) { timeout = 50 /* ACK */; }
7656 return __awaiter(this, void 0, void 0, function () {
7657 var messageChannel, completionTimer, handler;
7658 var _this = this;
7659 return __generator(this, function (_a) {
7660 messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
7661 if (!messageChannel) {
7662 throw new Error("connection_unavailable" /* CONNECTION_UNAVAILABLE */);
7663 }
7664 return [2 /*return*/, new Promise(function (resolve, reject) {
7665 var eventId = _generateEventId('', 20);
7666 messageChannel.port1.start();
7667 var ackTimer = setTimeout(function () {
7668 reject(new Error("unsupported_event" /* UNSUPPORTED_EVENT */));
7669 }, timeout);
7670 handler = {
7671 messageChannel: messageChannel,
7672 onMessage: function (event) {
7673 var messageEvent = event;
7674 if (messageEvent.data.eventId !== eventId) {
7675 return;
7676 }
7677 switch (messageEvent.data.status) {
7678 case "ack" /* ACK */:
7679 // The receiver should ACK first.
7680 clearTimeout(ackTimer);
7681 completionTimer = setTimeout(function () {
7682 reject(new Error("timeout" /* TIMEOUT */));
7683 }, 3000 /* COMPLETION */);
7684 break;
7685 case "done" /* DONE */:
7686 // Once the receiver's handlers are finished we will get the results.
7687 clearTimeout(completionTimer);
7688 resolve(messageEvent.data.response);
7689 break;
7690 default:
7691 clearTimeout(ackTimer);
7692 clearTimeout(completionTimer);
7693 reject(new Error("invalid_response" /* INVALID_RESPONSE */));
7694 break;
7695 }
7696 }
7697 };
7698 _this.handlers.add(handler);
7699 messageChannel.port1.addEventListener('message', handler.onMessage);
7700 _this.target.postMessage({
7701 eventType: eventType,
7702 eventId: eventId,
7703 data: data
7704 }, [messageChannel.port2]);
7705 }).finally(function () {
7706 if (handler) {
7707 _this.removeMessageHandler(handler);
7708 }
7709 })];
7710 });
7711 });
7712 };
7713 return Sender;
7714}());
7715
7716/**
7717 * @license
7718 * Copyright 2020 Google LLC
7719 *
7720 * Licensed under the Apache License, Version 2.0 (the "License");
7721 * you may not use this file except in compliance with the License.
7722 * You may obtain a copy of the License at
7723 *
7724 * http://www.apache.org/licenses/LICENSE-2.0
7725 *
7726 * Unless required by applicable law or agreed to in writing, software
7727 * distributed under the License is distributed on an "AS IS" BASIS,
7728 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7729 * See the License for the specific language governing permissions and
7730 * limitations under the License.
7731 */
7732/**
7733 * Lazy accessor for window, since the compat layer won't tree shake this out,
7734 * we need to make sure not to mess with window unless we have to
7735 */
7736function _window() {
7737 return window;
7738}
7739function _setWindowLocation(url) {
7740 _window().location.href = url;
7741}
7742
7743/**
7744 * @license
7745 * Copyright 2020 Google LLC.
7746 *
7747 * Licensed under the Apache License, Version 2.0 (the "License");
7748 * you may not use this file except in compliance with the License.
7749 * You may obtain a copy of the License at
7750 *
7751 * http://www.apache.org/licenses/LICENSE-2.0
7752 *
7753 * Unless required by applicable law or agreed to in writing, software
7754 * distributed under the License is distributed on an "AS IS" BASIS,
7755 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7756 * See the License for the specific language governing permissions and
7757 * limitations under the License.
7758 */
7759function _isWorker() {
7760 return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
7761 typeof _window()['importScripts'] === 'function');
7762}
7763function _getActiveServiceWorker() {
7764 return __awaiter(this, void 0, void 0, function () {
7765 var registration;
7766 return __generator(this, function (_b) {
7767 switch (_b.label) {
7768 case 0:
7769 if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
7770 return [2 /*return*/, null];
7771 }
7772 _b.label = 1;
7773 case 1:
7774 _b.trys.push([1, 3, , 4]);
7775 return [4 /*yield*/, navigator.serviceWorker.ready];
7776 case 2:
7777 registration = _b.sent();
7778 return [2 /*return*/, registration.active];
7779 case 3:
7780 _b.sent();
7781 return [2 /*return*/, null];
7782 case 4: return [2 /*return*/];
7783 }
7784 });
7785 });
7786}
7787function _getServiceWorkerController() {
7788 var _a;
7789 return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
7790}
7791function _getWorkerGlobalScope() {
7792 return _isWorker() ? self : null;
7793}
7794
7795/**
7796 * @license
7797 * Copyright 2019 Google LLC
7798 *
7799 * Licensed under the Apache License, Version 2.0 (the "License");
7800 * you may not use this file except in compliance with the License.
7801 * You may obtain a copy of the License at
7802 *
7803 * http://www.apache.org/licenses/LICENSE-2.0
7804 *
7805 * Unless required by applicable law or agreed to in writing, software
7806 * distributed under the License is distributed on an "AS IS" BASIS,
7807 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7808 * See the License for the specific language governing permissions and
7809 * limitations under the License.
7810 */
7811var DB_NAME = 'firebaseLocalStorageDb';
7812var DB_VERSION = 1;
7813var DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
7814var DB_DATA_KEYPATH = 'fbase_key';
7815/**
7816 * Promise wrapper for IDBRequest
7817 *
7818 * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
7819 *
7820 */
7821var DBPromise = /** @class */ (function () {
7822 function DBPromise(request) {
7823 this.request = request;
7824 }
7825 DBPromise.prototype.toPromise = function () {
7826 var _this = this;
7827 return new Promise(function (resolve, reject) {
7828 _this.request.addEventListener('success', function () {
7829 resolve(_this.request.result);
7830 });
7831 _this.request.addEventListener('error', function () {
7832 reject(_this.request.error);
7833 });
7834 });
7835 };
7836 return DBPromise;
7837}());
7838function getObjectStore(db, isReadWrite) {
7839 return db
7840 .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
7841 .objectStore(DB_OBJECTSTORE_NAME);
7842}
7843function _deleteDatabase() {
7844 var request = indexedDB.deleteDatabase(DB_NAME);
7845 return new DBPromise(request).toPromise();
7846}
7847function _openDatabase() {
7848 var _this = this;
7849 var request = indexedDB.open(DB_NAME, DB_VERSION);
7850 return new Promise(function (resolve, reject) {
7851 request.addEventListener('error', function () {
7852 reject(request.error);
7853 });
7854 request.addEventListener('upgradeneeded', function () {
7855 var db = request.result;
7856 try {
7857 db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
7858 }
7859 catch (e) {
7860 reject(e);
7861 }
7862 });
7863 request.addEventListener('success', function () { return __awaiter(_this, void 0, void 0, function () {
7864 var db, _a;
7865 return __generator(this, function (_b) {
7866 switch (_b.label) {
7867 case 0:
7868 db = request.result;
7869 if (!!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) return [3 /*break*/, 3];
7870 // Need to close the database or else you get a `blocked` event
7871 db.close();
7872 return [4 /*yield*/, _deleteDatabase()];
7873 case 1:
7874 _b.sent();
7875 _a = resolve;
7876 return [4 /*yield*/, _openDatabase()];
7877 case 2:
7878 _a.apply(void 0, [_b.sent()]);
7879 return [3 /*break*/, 4];
7880 case 3:
7881 resolve(db);
7882 _b.label = 4;
7883 case 4: return [2 /*return*/];
7884 }
7885 });
7886 }); });
7887 });
7888}
7889function _putObject(db, key, value) {
7890 return __awaiter(this, void 0, void 0, function () {
7891 var request;
7892 var _a;
7893 return __generator(this, function (_b) {
7894 request = getObjectStore(db, true).put((_a = {},
7895 _a[DB_DATA_KEYPATH] = key,
7896 _a.value = value,
7897 _a));
7898 return [2 /*return*/, new DBPromise(request).toPromise()];
7899 });
7900 });
7901}
7902function getObject(db, key) {
7903 return __awaiter(this, void 0, void 0, function () {
7904 var request, data;
7905 return __generator(this, function (_a) {
7906 switch (_a.label) {
7907 case 0:
7908 request = getObjectStore(db, false).get(key);
7909 return [4 /*yield*/, new DBPromise(request).toPromise()];
7910 case 1:
7911 data = _a.sent();
7912 return [2 /*return*/, data === undefined ? null : data.value];
7913 }
7914 });
7915 });
7916}
7917function _deleteObject(db, key) {
7918 var request = getObjectStore(db, true).delete(key);
7919 return new DBPromise(request).toPromise();
7920}
7921var _POLLING_INTERVAL_MS = 800;
7922var _TRANSACTION_RETRY_COUNT = 3;
7923var IndexedDBLocalPersistence = /** @class */ (function () {
7924 function IndexedDBLocalPersistence() {
7925 this.type = "LOCAL" /* LOCAL */;
7926 this._shouldAllowMigration = true;
7927 this.listeners = {};
7928 this.localCache = {};
7929 // setTimeout return value is platform specific
7930 // eslint-disable-next-line @typescript-eslint/no-explicit-any
7931 this.pollTimer = null;
7932 this.pendingWrites = 0;
7933 this.receiver = null;
7934 this.sender = null;
7935 this.serviceWorkerReceiverAvailable = false;
7936 this.activeServiceWorker = null;
7937 // Fire & forget the service worker registration as it may never resolve
7938 this._workerInitializationPromise =
7939 this.initializeServiceWorkerMessaging().then(function () { }, function () { });
7940 }
7941 IndexedDBLocalPersistence.prototype._openDb = function () {
7942 return __awaiter(this, void 0, void 0, function () {
7943 var _a;
7944 return __generator(this, function (_b) {
7945 switch (_b.label) {
7946 case 0:
7947 if (this.db) {
7948 return [2 /*return*/, this.db];
7949 }
7950 _a = this;
7951 return [4 /*yield*/, _openDatabase()];
7952 case 1:
7953 _a.db = _b.sent();
7954 return [2 /*return*/, this.db];
7955 }
7956 });
7957 });
7958 };
7959 IndexedDBLocalPersistence.prototype._withRetries = function (op) {
7960 return __awaiter(this, void 0, void 0, function () {
7961 var numAttempts, db, e_1;
7962 return __generator(this, function (_a) {
7963 switch (_a.label) {
7964 case 0:
7965 numAttempts = 0;
7966 _a.label = 1;
7967 case 1:
7968 _a.label = 2;
7969 case 2:
7970 _a.trys.push([2, 5, , 6]);
7971 return [4 /*yield*/, this._openDb()];
7972 case 3:
7973 db = _a.sent();
7974 return [4 /*yield*/, op(db)];
7975 case 4: return [2 /*return*/, _a.sent()];
7976 case 5:
7977 e_1 = _a.sent();
7978 if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
7979 throw e_1;
7980 }
7981 if (this.db) {
7982 this.db.close();
7983 this.db = undefined;
7984 }
7985 return [3 /*break*/, 6];
7986 case 6: return [3 /*break*/, 1];
7987 case 7: return [2 /*return*/];
7988 }
7989 });
7990 });
7991 };
7992 /**
7993 * IndexedDB events do not propagate from the main window to the worker context. We rely on a
7994 * postMessage interface to send these events to the worker ourselves.
7995 */
7996 IndexedDBLocalPersistence.prototype.initializeServiceWorkerMessaging = function () {
7997 return __awaiter(this, void 0, void 0, function () {
7998 return __generator(this, function (_a) {
7999 return [2 /*return*/, _isWorker() ? this.initializeReceiver() : this.initializeSender()];
8000 });
8001 });
8002 };
8003 /**
8004 * As the worker we should listen to events from the main window.
8005 */
8006 IndexedDBLocalPersistence.prototype.initializeReceiver = function () {
8007 return __awaiter(this, void 0, void 0, function () {
8008 var _this = this;
8009 return __generator(this, function (_a) {
8010 this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
8011 // Refresh from persistence if we receive a KeyChanged message.
8012 this.receiver._subscribe("keyChanged" /* KEY_CHANGED */, function (_origin, data) { return __awaiter(_this, void 0, void 0, function () {
8013 var keys;
8014 return __generator(this, function (_a) {
8015 switch (_a.label) {
8016 case 0: return [4 /*yield*/, this._poll()];
8017 case 1:
8018 keys = _a.sent();
8019 return [2 /*return*/, {
8020 keyProcessed: keys.includes(data.key)
8021 }];
8022 }
8023 });
8024 }); });
8025 // Let the sender know that we are listening so they give us more timeout.
8026 this.receiver._subscribe("ping" /* PING */, function (_origin, _data) { return __awaiter(_this, void 0, void 0, function () {
8027 return __generator(this, function (_a) {
8028 return [2 /*return*/, ["keyChanged" /* KEY_CHANGED */]];
8029 });
8030 }); });
8031 return [2 /*return*/];
8032 });
8033 });
8034 };
8035 /**
8036 * As the main window, we should let the worker know when keys change (set and remove).
8037 *
8038 * @remarks
8039 * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
8040 * may not resolve.
8041 */
8042 IndexedDBLocalPersistence.prototype.initializeSender = function () {
8043 var _a, _b;
8044 return __awaiter(this, void 0, void 0, function () {
8045 var _c, results;
8046 return __generator(this, function (_d) {
8047 switch (_d.label) {
8048 case 0:
8049 // Check to see if there's an active service worker.
8050 _c = this;
8051 return [4 /*yield*/, _getActiveServiceWorker()];
8052 case 1:
8053 // Check to see if there's an active service worker.
8054 _c.activeServiceWorker = _d.sent();
8055 if (!this.activeServiceWorker) {
8056 return [2 /*return*/];
8057 }
8058 this.sender = new Sender(this.activeServiceWorker);
8059 return [4 /*yield*/, this.sender._send("ping" /* PING */, {}, 800 /* LONG_ACK */)];
8060 case 2:
8061 results = _d.sent();
8062 if (!results) {
8063 return [2 /*return*/];
8064 }
8065 if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
8066 ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* KEY_CHANGED */))) {
8067 this.serviceWorkerReceiverAvailable = true;
8068 }
8069 return [2 /*return*/];
8070 }
8071 });
8072 });
8073 };
8074 /**
8075 * Let the worker know about a changed key, the exact key doesn't technically matter since the
8076 * worker will just trigger a full sync anyway.
8077 *
8078 * @remarks
8079 * For now, we only support one service worker per page.
8080 *
8081 * @param key - Storage key which changed.
8082 */
8083 IndexedDBLocalPersistence.prototype.notifyServiceWorker = function (key) {
8084 return __awaiter(this, void 0, void 0, function () {
8085 return __generator(this, function (_b) {
8086 switch (_b.label) {
8087 case 0:
8088 if (!this.sender ||
8089 !this.activeServiceWorker ||
8090 _getServiceWorkerController() !== this.activeServiceWorker) {
8091 return [2 /*return*/];
8092 }
8093 _b.label = 1;
8094 case 1:
8095 _b.trys.push([1, 3, , 4]);
8096 return [4 /*yield*/, this.sender._send("keyChanged" /* KEY_CHANGED */, { key: key },
8097 // Use long timeout if receiver has previously responded to a ping from us.
8098 this.serviceWorkerReceiverAvailable
8099 ? 800 /* LONG_ACK */
8100 : 50 /* ACK */)];
8101 case 2:
8102 _b.sent();
8103 return [3 /*break*/, 4];
8104 case 3:
8105 _b.sent();
8106 return [3 /*break*/, 4];
8107 case 4: return [2 /*return*/];
8108 }
8109 });
8110 });
8111 };
8112 IndexedDBLocalPersistence.prototype._isAvailable = function () {
8113 return __awaiter(this, void 0, void 0, function () {
8114 var db;
8115 return __generator(this, function (_b) {
8116 switch (_b.label) {
8117 case 0:
8118 _b.trys.push([0, 4, , 5]);
8119 if (!indexedDB) {
8120 return [2 /*return*/, false];
8121 }
8122 return [4 /*yield*/, _openDatabase()];
8123 case 1:
8124 db = _b.sent();
8125 return [4 /*yield*/, _putObject(db, STORAGE_AVAILABLE_KEY, '1')];
8126 case 2:
8127 _b.sent();
8128 return [4 /*yield*/, _deleteObject(db, STORAGE_AVAILABLE_KEY)];
8129 case 3:
8130 _b.sent();
8131 return [2 /*return*/, true];
8132 case 4:
8133 _b.sent();
8134 return [3 /*break*/, 5];
8135 case 5: return [2 /*return*/, false];
8136 }
8137 });
8138 });
8139 };
8140 IndexedDBLocalPersistence.prototype._withPendingWrite = function (write) {
8141 return __awaiter(this, void 0, void 0, function () {
8142 return __generator(this, function (_a) {
8143 switch (_a.label) {
8144 case 0:
8145 this.pendingWrites++;
8146 _a.label = 1;
8147 case 1:
8148 _a.trys.push([1, , 3, 4]);
8149 return [4 /*yield*/, write()];
8150 case 2:
8151 _a.sent();
8152 return [3 /*break*/, 4];
8153 case 3:
8154 this.pendingWrites--;
8155 return [7 /*endfinally*/];
8156 case 4: return [2 /*return*/];
8157 }
8158 });
8159 });
8160 };
8161 IndexedDBLocalPersistence.prototype._set = function (key, value) {
8162 return __awaiter(this, void 0, void 0, function () {
8163 var _this = this;
8164 return __generator(this, function (_a) {
8165 return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
8166 return __generator(this, function (_a) {
8167 switch (_a.label) {
8168 case 0: return [4 /*yield*/, this._withRetries(function (db) { return _putObject(db, key, value); })];
8169 case 1:
8170 _a.sent();
8171 this.localCache[key] = value;
8172 return [2 /*return*/, this.notifyServiceWorker(key)];
8173 }
8174 });
8175 }); })];
8176 });
8177 });
8178 };
8179 IndexedDBLocalPersistence.prototype._get = function (key) {
8180 return __awaiter(this, void 0, void 0, function () {
8181 var obj;
8182 return __generator(this, function (_a) {
8183 switch (_a.label) {
8184 case 0: return [4 /*yield*/, this._withRetries(function (db) {
8185 return getObject(db, key);
8186 })];
8187 case 1:
8188 obj = (_a.sent());
8189 this.localCache[key] = obj;
8190 return [2 /*return*/, obj];
8191 }
8192 });
8193 });
8194 };
8195 IndexedDBLocalPersistence.prototype._remove = function (key) {
8196 return __awaiter(this, void 0, void 0, function () {
8197 var _this = this;
8198 return __generator(this, function (_a) {
8199 return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
8200 return __generator(this, function (_a) {
8201 switch (_a.label) {
8202 case 0: return [4 /*yield*/, this._withRetries(function (db) { return _deleteObject(db, key); })];
8203 case 1:
8204 _a.sent();
8205 delete this.localCache[key];
8206 return [2 /*return*/, this.notifyServiceWorker(key)];
8207 }
8208 });
8209 }); })];
8210 });
8211 });
8212 };
8213 IndexedDBLocalPersistence.prototype._poll = function () {
8214 return __awaiter(this, void 0, void 0, function () {
8215 var result, keys, keysInResult, _i, result_1, _a, key, value, _b, _c, localKey;
8216 return __generator(this, function (_d) {
8217 switch (_d.label) {
8218 case 0: return [4 /*yield*/, this._withRetries(function (db) {
8219 var getAllRequest = getObjectStore(db, false).getAll();
8220 return new DBPromise(getAllRequest).toPromise();
8221 })];
8222 case 1:
8223 result = _d.sent();
8224 if (!result) {
8225 return [2 /*return*/, []];
8226 }
8227 // If we have pending writes in progress abort, we'll get picked up on the next poll
8228 if (this.pendingWrites !== 0) {
8229 return [2 /*return*/, []];
8230 }
8231 keys = [];
8232 keysInResult = new Set();
8233 for (_i = 0, result_1 = result; _i < result_1.length; _i++) {
8234 _a = result_1[_i], key = _a.fbase_key, value = _a.value;
8235 keysInResult.add(key);
8236 if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
8237 this.notifyListeners(key, value);
8238 keys.push(key);
8239 }
8240 }
8241 for (_b = 0, _c = Object.keys(this.localCache); _b < _c.length; _b++) {
8242 localKey = _c[_b];
8243 if (this.localCache[localKey] && !keysInResult.has(localKey)) {
8244 // Deleted
8245 this.notifyListeners(localKey, null);
8246 keys.push(localKey);
8247 }
8248 }
8249 return [2 /*return*/, keys];
8250 }
8251 });
8252 });
8253 };
8254 IndexedDBLocalPersistence.prototype.notifyListeners = function (key, newValue) {
8255 this.localCache[key] = newValue;
8256 var listeners = this.listeners[key];
8257 if (listeners) {
8258 for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
8259 var listener = _a[_i];
8260 listener(newValue);
8261 }
8262 }
8263 };
8264 IndexedDBLocalPersistence.prototype.startPolling = function () {
8265 var _this = this;
8266 this.stopPolling();
8267 this.pollTimer = setInterval(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
8268 return [2 /*return*/, this._poll()];
8269 }); }); }, _POLLING_INTERVAL_MS);
8270 };
8271 IndexedDBLocalPersistence.prototype.stopPolling = function () {
8272 if (this.pollTimer) {
8273 clearInterval(this.pollTimer);
8274 this.pollTimer = null;
8275 }
8276 };
8277 IndexedDBLocalPersistence.prototype._addListener = function (key, listener) {
8278 if (Object.keys(this.listeners).length === 0) {
8279 this.startPolling();
8280 }
8281 if (!this.listeners[key]) {
8282 this.listeners[key] = new Set();
8283 // Populate the cache to avoid spuriously triggering on first poll.
8284 void this._get(key); // This can happen in the background async and we can return immediately.
8285 }
8286 this.listeners[key].add(listener);
8287 };
8288 IndexedDBLocalPersistence.prototype._removeListener = function (key, listener) {
8289 if (this.listeners[key]) {
8290 this.listeners[key].delete(listener);
8291 if (this.listeners[key].size === 0) {
8292 delete this.listeners[key];
8293 }
8294 }
8295 if (Object.keys(this.listeners).length === 0) {
8296 this.stopPolling();
8297 }
8298 };
8299 IndexedDBLocalPersistence.type = 'LOCAL';
8300 return IndexedDBLocalPersistence;
8301}());
8302/**
8303 * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
8304 * for the underlying storage.
8305 *
8306 * @public
8307 */
8308var indexedDBLocalPersistence = IndexedDBLocalPersistence;
8309
8310/**
8311 * @license
8312 * Copyright 2020 Google LLC
8313 *
8314 * Licensed under the Apache License, Version 2.0 (the "License");
8315 * you may not use this file except in compliance with the License.
8316 * You may obtain a copy of the License at
8317 *
8318 * http://www.apache.org/licenses/LICENSE-2.0
8319 *
8320 * Unless required by applicable law or agreed to in writing, software
8321 * distributed under the License is distributed on an "AS IS" BASIS,
8322 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8323 * See the License for the specific language governing permissions and
8324 * limitations under the License.
8325 */
8326function startSignInPhoneMfa(auth, request) {
8327 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaSignIn:start" /* START_PHONE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
8328}
8329function finalizeSignInPhoneMfa(auth, request) {
8330 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaSignIn:finalize" /* FINALIZE_PHONE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
8331}
8332
8333/**
8334 * @license
8335 * Copyright 2020 Google LLC
8336 *
8337 * Licensed under the Apache License, Version 2.0 (the "License");
8338 * you may not use this file except in compliance with the License.
8339 * You may obtain a copy of the License at
8340 *
8341 * http://www.apache.org/licenses/LICENSE-2.0
8342 *
8343 * Unless required by applicable law or agreed to in writing, software
8344 * distributed under the License is distributed on an "AS IS" BASIS,
8345 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8346 * See the License for the specific language governing permissions and
8347 * limitations under the License.
8348 */
8349function getRecaptchaParams(auth) {
8350 return __awaiter(this, void 0, void 0, function () {
8351 return __generator(this, function (_a) {
8352 switch (_a.label) {
8353 case 0: return [4 /*yield*/, _performApiRequest(auth, "GET" /* GET */, "/v1/recaptchaParams" /* GET_RECAPTCHA_PARAM */)];
8354 case 1: return [2 /*return*/, ((_a.sent()).recaptchaSiteKey || '')];
8355 }
8356 });
8357 });
8358}
8359
8360/**
8361 * @license
8362 * Copyright 2020 Google LLC
8363 *
8364 * Licensed under the Apache License, Version 2.0 (the "License");
8365 * you may not use this file except in compliance with the License.
8366 * You may obtain a copy of the License at
8367 *
8368 * http://www.apache.org/licenses/LICENSE-2.0
8369 *
8370 * Unless required by applicable law or agreed to in writing, software
8371 * distributed under the License is distributed on an "AS IS" BASIS,
8372 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8373 * See the License for the specific language governing permissions and
8374 * limitations under the License.
8375 */
8376function getScriptParentElement() {
8377 var _a, _b;
8378 return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
8379}
8380function _loadJS(url) {
8381 // TODO: consider adding timeout support & cancellation
8382 return new Promise(function (resolve, reject) {
8383 var el = document.createElement('script');
8384 el.setAttribute('src', url);
8385 el.onload = resolve;
8386 el.onerror = function (e) {
8387 var error = _createError("internal-error" /* INTERNAL_ERROR */);
8388 error.customData = e;
8389 reject(error);
8390 };
8391 el.type = 'text/javascript';
8392 el.charset = 'UTF-8';
8393 getScriptParentElement().appendChild(el);
8394 });
8395}
8396function _generateCallbackName(prefix) {
8397 return "__" + prefix + Math.floor(Math.random() * 1000000);
8398}
8399
8400/**
8401 * @license
8402 * Copyright 2020 Google LLC
8403 *
8404 * Licensed under the Apache License, Version 2.0 (the "License");
8405 * you may not use this file except in compliance with the License.
8406 * You may obtain a copy of the License at
8407 *
8408 * http://www.apache.org/licenses/LICENSE-2.0
8409 *
8410 * Unless required by applicable law or agreed to in writing, software
8411 * distributed under the License is distributed on an "AS IS" BASIS,
8412 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8413 * See the License for the specific language governing permissions and
8414 * limitations under the License.
8415 */
8416var _SOLVE_TIME_MS = 500;
8417var _EXPIRATION_TIME_MS = 60000;
8418var _WIDGET_ID_START = 1000000000000;
8419var MockReCaptcha = /** @class */ (function () {
8420 function MockReCaptcha(auth) {
8421 this.auth = auth;
8422 this.counter = _WIDGET_ID_START;
8423 this._widgets = new Map();
8424 }
8425 MockReCaptcha.prototype.render = function (container, parameters) {
8426 var id = this.counter;
8427 this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
8428 this.counter++;
8429 return id;
8430 };
8431 MockReCaptcha.prototype.reset = function (optWidgetId) {
8432 var _a;
8433 var id = optWidgetId || _WIDGET_ID_START;
8434 void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
8435 this._widgets.delete(id);
8436 };
8437 MockReCaptcha.prototype.getResponse = function (optWidgetId) {
8438 var _a;
8439 var id = optWidgetId || _WIDGET_ID_START;
8440 return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
8441 };
8442 MockReCaptcha.prototype.execute = function (optWidgetId) {
8443 var _a;
8444 return __awaiter(this, void 0, void 0, function () {
8445 var id;
8446 return __generator(this, function (_b) {
8447 id = optWidgetId || _WIDGET_ID_START;
8448 void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
8449 return [2 /*return*/, ''];
8450 });
8451 });
8452 };
8453 return MockReCaptcha;
8454}());
8455var MockWidget = /** @class */ (function () {
8456 function MockWidget(containerOrId, appName, params) {
8457 var _this = this;
8458 this.params = params;
8459 this.timerId = null;
8460 this.deleted = false;
8461 this.responseToken = null;
8462 this.clickHandler = function () {
8463 _this.execute();
8464 };
8465 var container = typeof containerOrId === 'string'
8466 ? document.getElementById(containerOrId)
8467 : containerOrId;
8468 _assert(container, "argument-error" /* ARGUMENT_ERROR */, { appName: appName });
8469 this.container = container;
8470 this.isVisible = this.params.size !== 'invisible';
8471 if (this.isVisible) {
8472 this.execute();
8473 }
8474 else {
8475 this.container.addEventListener('click', this.clickHandler);
8476 }
8477 }
8478 MockWidget.prototype.getResponse = function () {
8479 this.checkIfDeleted();
8480 return this.responseToken;
8481 };
8482 MockWidget.prototype.delete = function () {
8483 this.checkIfDeleted();
8484 this.deleted = true;
8485 if (this.timerId) {
8486 clearTimeout(this.timerId);
8487 this.timerId = null;
8488 }
8489 this.container.removeEventListener('click', this.clickHandler);
8490 };
8491 MockWidget.prototype.execute = function () {
8492 var _this = this;
8493 this.checkIfDeleted();
8494 if (this.timerId) {
8495 return;
8496 }
8497 this.timerId = window.setTimeout(function () {
8498 _this.responseToken = generateRandomAlphaNumericString(50);
8499 var _a = _this.params, callback = _a.callback, expiredCallback = _a["expired-callback"];
8500 if (callback) {
8501 try {
8502 callback(_this.responseToken);
8503 }
8504 catch (e) { }
8505 }
8506 _this.timerId = window.setTimeout(function () {
8507 _this.timerId = null;
8508 _this.responseToken = null;
8509 if (expiredCallback) {
8510 try {
8511 expiredCallback();
8512 }
8513 catch (e) { }
8514 }
8515 if (_this.isVisible) {
8516 _this.execute();
8517 }
8518 }, _EXPIRATION_TIME_MS);
8519 }, _SOLVE_TIME_MS);
8520 };
8521 MockWidget.prototype.checkIfDeleted = function () {
8522 if (this.deleted) {
8523 throw new Error('reCAPTCHA mock was already deleted!');
8524 }
8525 };
8526 return MockWidget;
8527}());
8528function generateRandomAlphaNumericString(len) {
8529 var chars = [];
8530 var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
8531 for (var i = 0; i < len; i++) {
8532 chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
8533 }
8534 return chars.join('');
8535}
8536
8537/**
8538 * @license
8539 * Copyright 2020 Google LLC
8540 *
8541 * Licensed under the Apache License, Version 2.0 (the "License");
8542 * you may not use this file except in compliance with the License.
8543 * You may obtain a copy of the License at
8544 *
8545 * http://www.apache.org/licenses/LICENSE-2.0
8546 *
8547 * Unless required by applicable law or agreed to in writing, software
8548 * distributed under the License is distributed on an "AS IS" BASIS,
8549 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8550 * See the License for the specific language governing permissions and
8551 * limitations under the License.
8552 */
8553// ReCaptcha will load using the same callback, so the callback function needs
8554// to be kept around
8555var _JSLOAD_CALLBACK = _generateCallbackName('rcb');
8556var NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
8557var RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
8558/**
8559 * Loader for the GReCaptcha library. There should only ever be one of this.
8560 */
8561var ReCaptchaLoaderImpl = /** @class */ (function () {
8562 function ReCaptchaLoaderImpl() {
8563 this.hostLanguage = '';
8564 this.counter = 0;
8565 this.librarySeparatelyLoaded = !!_window().grecaptcha;
8566 }
8567 ReCaptchaLoaderImpl.prototype.load = function (auth, hl) {
8568 var _this = this;
8569 if (hl === void 0) { hl = ''; }
8570 _assert(isHostLanguageValid(hl), auth, "argument-error" /* ARGUMENT_ERROR */);
8571 if (this.shouldResolveImmediately(hl)) {
8572 return Promise.resolve(_window().grecaptcha);
8573 }
8574 return new Promise(function (resolve, reject) {
8575 var networkTimeout = _window().setTimeout(function () {
8576 reject(_createError(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
8577 }, NETWORK_TIMEOUT_DELAY.get());
8578 _window()[_JSLOAD_CALLBACK] = function () {
8579 _window().clearTimeout(networkTimeout);
8580 delete _window()[_JSLOAD_CALLBACK];
8581 var recaptcha = _window().grecaptcha;
8582 if (!recaptcha) {
8583 reject(_createError(auth, "internal-error" /* INTERNAL_ERROR */));
8584 return;
8585 }
8586 // Wrap the greptcha render function so that we know if the developer has
8587 // called it separately
8588 var render = recaptcha.render;
8589 recaptcha.render = function (container, params) {
8590 var widgetId = render(container, params);
8591 _this.counter++;
8592 return widgetId;
8593 };
8594 _this.hostLanguage = hl;
8595 resolve(recaptcha);
8596 };
8597 var url = RECAPTCHA_BASE + "?" + querystring({
8598 onload: _JSLOAD_CALLBACK,
8599 render: 'explicit',
8600 hl: hl
8601 });
8602 _loadJS(url).catch(function () {
8603 clearTimeout(networkTimeout);
8604 reject(_createError(auth, "internal-error" /* INTERNAL_ERROR */));
8605 });
8606 });
8607 };
8608 ReCaptchaLoaderImpl.prototype.clearedOneInstance = function () {
8609 this.counter--;
8610 };
8611 ReCaptchaLoaderImpl.prototype.shouldResolveImmediately = function (hl) {
8612 // We can resolve immediately if:
8613 // • grecaptcha is already defined AND (
8614 // 1. the requested language codes are the same OR
8615 // 2. there exists already a ReCaptcha on the page
8616 // 3. the library was already loaded by the app
8617 // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
8618 // that are already in the page
8619 return (!!_window().grecaptcha &&
8620 (hl === this.hostLanguage ||
8621 this.counter > 0 ||
8622 this.librarySeparatelyLoaded));
8623 };
8624 return ReCaptchaLoaderImpl;
8625}());
8626function isHostLanguageValid(hl) {
8627 return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
8628}
8629var MockReCaptchaLoaderImpl = /** @class */ (function () {
8630 function MockReCaptchaLoaderImpl() {
8631 }
8632 MockReCaptchaLoaderImpl.prototype.load = function (auth) {
8633 return __awaiter(this, void 0, void 0, function () {
8634 return __generator(this, function (_a) {
8635 return [2 /*return*/, new MockReCaptcha(auth)];
8636 });
8637 });
8638 };
8639 MockReCaptchaLoaderImpl.prototype.clearedOneInstance = function () { };
8640 return MockReCaptchaLoaderImpl;
8641}());
8642
8643/**
8644 * @license
8645 * Copyright 2020 Google LLC
8646 *
8647 * Licensed under the Apache License, Version 2.0 (the "License");
8648 * you may not use this file except in compliance with the License.
8649 * You may obtain a copy of the License at
8650 *
8651 * http://www.apache.org/licenses/LICENSE-2.0
8652 *
8653 * Unless required by applicable law or agreed to in writing, software
8654 * distributed under the License is distributed on an "AS IS" BASIS,
8655 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8656 * See the License for the specific language governing permissions and
8657 * limitations under the License.
8658 */
8659var RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
8660var DEFAULT_PARAMS = {
8661 theme: 'light',
8662 type: 'image'
8663};
8664/**
8665 * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
8666 *
8667 * @public
8668 */
8669var RecaptchaVerifier = /** @class */ (function () {
8670 /**
8671 *
8672 * @param containerOrId - The reCAPTCHA container parameter.
8673 *
8674 * @remarks
8675 * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
8676 * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
8677 * an element ID. The corresponding element must also must be in the DOM at the time of
8678 * initialization.
8679 *
8680 * @param parameters - The optional reCAPTCHA parameters.
8681 *
8682 * @remarks
8683 * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
8684 * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
8685 * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
8686 * 'invisible'.
8687 *
8688 * @param authExtern - The corresponding Firebase {@link Auth} instance.
8689 *
8690 * @remarks
8691 * If none is provided, the default Firebase {@link Auth} instance is used. A Firebase {@link Auth} instance
8692 * must be initialized with an API key, otherwise an error will be thrown.
8693 */
8694 function RecaptchaVerifier(containerOrId, parameters, authExtern) {
8695 if (parameters === void 0) { parameters = __assign({}, DEFAULT_PARAMS); }
8696 this.parameters = parameters;
8697 /**
8698 * The application verifier type.
8699 *
8700 * @remarks
8701 * For a reCAPTCHA verifier, this is 'recaptcha'.
8702 */
8703 this.type = RECAPTCHA_VERIFIER_TYPE;
8704 this.destroyed = false;
8705 this.widgetId = null;
8706 this.tokenChangeListeners = new Set();
8707 this.renderPromise = null;
8708 this.recaptcha = null;
8709 this.auth = _castAuth(authExtern);
8710 this.isInvisible = this.parameters.size === 'invisible';
8711 _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
8712 var container = typeof containerOrId === 'string'
8713 ? document.getElementById(containerOrId)
8714 : containerOrId;
8715 _assert(container, this.auth, "argument-error" /* ARGUMENT_ERROR */);
8716 this.container = container;
8717 this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
8718 this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
8719 ? new MockReCaptchaLoaderImpl()
8720 : new ReCaptchaLoaderImpl();
8721 this.validateStartingState();
8722 // TODO: Figure out if sdk version is needed
8723 }
8724 /**
8725 * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
8726 *
8727 * @returns A Promise for the reCAPTCHA token.
8728 */
8729 RecaptchaVerifier.prototype.verify = function () {
8730 return __awaiter(this, void 0, void 0, function () {
8731 var id, recaptcha, response;
8732 var _this = this;
8733 return __generator(this, function (_a) {
8734 switch (_a.label) {
8735 case 0:
8736 this.assertNotDestroyed();
8737 return [4 /*yield*/, this.render()];
8738 case 1:
8739 id = _a.sent();
8740 recaptcha = this.getAssertedRecaptcha();
8741 response = recaptcha.getResponse(id);
8742 if (response) {
8743 return [2 /*return*/, response];
8744 }
8745 return [2 /*return*/, new Promise(function (resolve) {
8746 var tokenChange = function (token) {
8747 if (!token) {
8748 return; // Ignore token expirations.
8749 }
8750 _this.tokenChangeListeners.delete(tokenChange);
8751 resolve(token);
8752 };
8753 _this.tokenChangeListeners.add(tokenChange);
8754 if (_this.isInvisible) {
8755 recaptcha.execute(id);
8756 }
8757 })];
8758 }
8759 });
8760 });
8761 };
8762 /**
8763 * Renders the reCAPTCHA widget on the page.
8764 *
8765 * @returns A Promise that resolves with the reCAPTCHA widget ID.
8766 */
8767 RecaptchaVerifier.prototype.render = function () {
8768 var _this = this;
8769 try {
8770 this.assertNotDestroyed();
8771 }
8772 catch (e) {
8773 // This method returns a promise. Since it's not async (we want to return the
8774 // _same_ promise if rendering is still occurring), the API surface should
8775 // reject with the error rather than just throw
8776 return Promise.reject(e);
8777 }
8778 if (this.renderPromise) {
8779 return this.renderPromise;
8780 }
8781 this.renderPromise = this.makeRenderPromise().catch(function (e) {
8782 _this.renderPromise = null;
8783 throw e;
8784 });
8785 return this.renderPromise;
8786 };
8787 /** @internal */
8788 RecaptchaVerifier.prototype._reset = function () {
8789 this.assertNotDestroyed();
8790 if (this.widgetId !== null) {
8791 this.getAssertedRecaptcha().reset(this.widgetId);
8792 }
8793 };
8794 /**
8795 * Clears the reCAPTCHA widget from the page and destroys the instance.
8796 */
8797 RecaptchaVerifier.prototype.clear = function () {
8798 var _this = this;
8799 this.assertNotDestroyed();
8800 this.destroyed = true;
8801 this._recaptchaLoader.clearedOneInstance();
8802 if (!this.isInvisible) {
8803 this.container.childNodes.forEach(function (node) {
8804 _this.container.removeChild(node);
8805 });
8806 }
8807 };
8808 RecaptchaVerifier.prototype.validateStartingState = function () {
8809 _assert(!this.parameters.sitekey, this.auth, "argument-error" /* ARGUMENT_ERROR */);
8810 _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* ARGUMENT_ERROR */);
8811 _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
8812 };
8813 RecaptchaVerifier.prototype.makeTokenCallback = function (existing) {
8814 var _this = this;
8815 return function (token) {
8816 _this.tokenChangeListeners.forEach(function (listener) { return listener(token); });
8817 if (typeof existing === 'function') {
8818 existing(token);
8819 }
8820 else if (typeof existing === 'string') {
8821 var globalFunc = _window()[existing];
8822 if (typeof globalFunc === 'function') {
8823 globalFunc(token);
8824 }
8825 }
8826 };
8827 };
8828 RecaptchaVerifier.prototype.assertNotDestroyed = function () {
8829 _assert(!this.destroyed, this.auth, "internal-error" /* INTERNAL_ERROR */);
8830 };
8831 RecaptchaVerifier.prototype.makeRenderPromise = function () {
8832 return __awaiter(this, void 0, void 0, function () {
8833 var container, guaranteedEmpty;
8834 return __generator(this, function (_a) {
8835 switch (_a.label) {
8836 case 0: return [4 /*yield*/, this.init()];
8837 case 1:
8838 _a.sent();
8839 if (!this.widgetId) {
8840 container = this.container;
8841 if (!this.isInvisible) {
8842 guaranteedEmpty = document.createElement('div');
8843 container.appendChild(guaranteedEmpty);
8844 container = guaranteedEmpty;
8845 }
8846 this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
8847 }
8848 return [2 /*return*/, this.widgetId];
8849 }
8850 });
8851 });
8852 };
8853 RecaptchaVerifier.prototype.init = function () {
8854 return __awaiter(this, void 0, void 0, function () {
8855 var _a, siteKey;
8856 return __generator(this, function (_b) {
8857 switch (_b.label) {
8858 case 0:
8859 _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* INTERNAL_ERROR */);
8860 return [4 /*yield*/, domReady()];
8861 case 1:
8862 _b.sent();
8863 _a = this;
8864 return [4 /*yield*/, this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined)];
8865 case 2:
8866 _a.recaptcha = _b.sent();
8867 return [4 /*yield*/, getRecaptchaParams(this.auth)];
8868 case 3:
8869 siteKey = _b.sent();
8870 _assert(siteKey, this.auth, "internal-error" /* INTERNAL_ERROR */);
8871 this.parameters.sitekey = siteKey;
8872 return [2 /*return*/];
8873 }
8874 });
8875 });
8876 };
8877 RecaptchaVerifier.prototype.getAssertedRecaptcha = function () {
8878 _assert(this.recaptcha, this.auth, "internal-error" /* INTERNAL_ERROR */);
8879 return this.recaptcha;
8880 };
8881 return RecaptchaVerifier;
8882}());
8883function domReady() {
8884 var resolver = null;
8885 return new Promise(function (resolve) {
8886 if (document.readyState === 'complete') {
8887 resolve();
8888 return;
8889 }
8890 // Document not ready, wait for load before resolving.
8891 // Save resolver, so we can remove listener in case it was externally
8892 // cancelled.
8893 resolver = function () { return resolve(); };
8894 window.addEventListener('load', resolver);
8895 }).catch(function (e) {
8896 if (resolver) {
8897 window.removeEventListener('load', resolver);
8898 }
8899 throw e;
8900 });
8901}
8902
8903/**
8904 * @license
8905 * Copyright 2020 Google LLC
8906 *
8907 * Licensed under the Apache License, Version 2.0 (the "License");
8908 * you may not use this file except in compliance with the License.
8909 * You may obtain a copy of the License at
8910 *
8911 * http://www.apache.org/licenses/LICENSE-2.0
8912 *
8913 * Unless required by applicable law or agreed to in writing, software
8914 * distributed under the License is distributed on an "AS IS" BASIS,
8915 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8916 * See the License for the specific language governing permissions and
8917 * limitations under the License.
8918 */
8919var ConfirmationResultImpl = /** @class */ (function () {
8920 function ConfirmationResultImpl(verificationId, onConfirmation) {
8921 this.verificationId = verificationId;
8922 this.onConfirmation = onConfirmation;
8923 }
8924 ConfirmationResultImpl.prototype.confirm = function (verificationCode) {
8925 var authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
8926 return this.onConfirmation(authCredential);
8927 };
8928 return ConfirmationResultImpl;
8929}());
8930/**
8931 * Asynchronously signs in using a phone number.
8932 *
8933 * @remarks
8934 * This method sends a code via SMS to the given
8935 * phone number, and returns a {@link ConfirmationResult}. After the user
8936 * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
8937 * with the code to sign the user in.
8938 *
8939 * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
8940 * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
8941 * This function can work on other platforms that do not support the
8942 * {@link RecaptchaVerifier} (like React Native), but you need to use a
8943 * third-party {@link ApplicationVerifier} implementation.
8944 *
8945 * @example
8946 * ```javascript
8947 * // 'recaptcha-container' is the ID of an element in the DOM.
8948 * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
8949 * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
8950 * // Obtain a verificationCode from the user.
8951 * const credential = await confirmationResult.confirm(verificationCode);
8952 * ```
8953 *
8954 * @param auth - The {@link Auth} instance.
8955 * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
8956 * @param appVerifier - The {@link ApplicationVerifier}.
8957 *
8958 * @public
8959 */
8960function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
8961 return __awaiter(this, void 0, void 0, function () {
8962 var authInternal, verificationId;
8963 return __generator(this, function (_a) {
8964 switch (_a.label) {
8965 case 0:
8966 authInternal = _castAuth(auth);
8967 return [4 /*yield*/, _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier))];
8968 case 1:
8969 verificationId = _a.sent();
8970 return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
8971 return signInWithCredential(authInternal, cred);
8972 })];
8973 }
8974 });
8975 });
8976}
8977/**
8978 * Links the user account with the given phone number.
8979 *
8980 * @param user - The user.
8981 * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
8982 * @param appVerifier - The {@link ApplicationVerifier}.
8983 *
8984 * @public
8985 */
8986function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
8987 return __awaiter(this, void 0, void 0, function () {
8988 var userInternal, verificationId;
8989 return __generator(this, function (_a) {
8990 switch (_a.label) {
8991 case 0:
8992 userInternal = getModularInstance(user);
8993 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, "phone" /* PHONE */)];
8994 case 1:
8995 _a.sent();
8996 return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
8997 case 2:
8998 verificationId = _a.sent();
8999 return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
9000 return linkWithCredential(userInternal, cred);
9001 })];
9002 }
9003 });
9004 });
9005}
9006/**
9007 * Re-authenticates a user using a fresh phone credential.
9008 *
9009 * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
9010 *
9011 * @param user - The user.
9012 * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
9013 * @param appVerifier - The {@link ApplicationVerifier}.
9014 *
9015 * @public
9016 */
9017function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
9018 return __awaiter(this, void 0, void 0, function () {
9019 var userInternal, verificationId;
9020 return __generator(this, function (_a) {
9021 switch (_a.label) {
9022 case 0:
9023 userInternal = getModularInstance(user);
9024 return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
9025 case 1:
9026 verificationId = _a.sent();
9027 return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
9028 return reauthenticateWithCredential(userInternal, cred);
9029 })];
9030 }
9031 });
9032 });
9033}
9034/**
9035 * Returns a verification ID to be used in conjunction with the SMS code that is sent.
9036 *
9037 */
9038function _verifyPhoneNumber(auth, options, verifier) {
9039 var _a;
9040 return __awaiter(this, void 0, void 0, function () {
9041 var recaptchaToken, phoneInfoOptions, session, response, mfaEnrollmentId, response, sessionInfo;
9042 return __generator(this, function (_b) {
9043 switch (_b.label) {
9044 case 0: return [4 /*yield*/, verifier.verify()];
9045 case 1:
9046 recaptchaToken = _b.sent();
9047 _b.label = 2;
9048 case 2:
9049 _b.trys.push([2, , 10, 11]);
9050 _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* ARGUMENT_ERROR */);
9051 _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* ARGUMENT_ERROR */);
9052 phoneInfoOptions = void 0;
9053 if (typeof options === 'string') {
9054 phoneInfoOptions = {
9055 phoneNumber: options
9056 };
9057 }
9058 else {
9059 phoneInfoOptions = options;
9060 }
9061 if (!('session' in phoneInfoOptions)) return [3 /*break*/, 7];
9062 session = phoneInfoOptions.session;
9063 if (!('phoneNumber' in phoneInfoOptions)) return [3 /*break*/, 4];
9064 _assert(session.type === "enroll" /* ENROLL */, auth, "internal-error" /* INTERNAL_ERROR */);
9065 return [4 /*yield*/, startEnrollPhoneMfa(auth, {
9066 idToken: session.credential,
9067 phoneEnrollmentInfo: {
9068 phoneNumber: phoneInfoOptions.phoneNumber,
9069 recaptchaToken: recaptchaToken
9070 }
9071 })];
9072 case 3:
9073 response = _b.sent();
9074 return [2 /*return*/, response.phoneSessionInfo.sessionInfo];
9075 case 4:
9076 _assert(session.type === "signin" /* SIGN_IN */, auth, "internal-error" /* INTERNAL_ERROR */);
9077 mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
9078 phoneInfoOptions.multiFactorUid;
9079 _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* MISSING_MFA_INFO */);
9080 return [4 /*yield*/, startSignInPhoneMfa(auth, {
9081 mfaPendingCredential: session.credential,
9082 mfaEnrollmentId: mfaEnrollmentId,
9083 phoneSignInInfo: {
9084 recaptchaToken: recaptchaToken
9085 }
9086 })];
9087 case 5:
9088 response = _b.sent();
9089 return [2 /*return*/, response.phoneResponseInfo.sessionInfo];
9090 case 6: return [3 /*break*/, 9];
9091 case 7: return [4 /*yield*/, sendPhoneVerificationCode(auth, {
9092 phoneNumber: phoneInfoOptions.phoneNumber,
9093 recaptchaToken: recaptchaToken
9094 })];
9095 case 8:
9096 sessionInfo = (_b.sent()).sessionInfo;
9097 return [2 /*return*/, sessionInfo];
9098 case 9: return [3 /*break*/, 11];
9099 case 10:
9100 verifier._reset();
9101 return [7 /*endfinally*/];
9102 case 11: return [2 /*return*/];
9103 }
9104 });
9105 });
9106}
9107/**
9108 * Updates the user's phone number.
9109 *
9110 * @example
9111 * ```
9112 * // 'recaptcha-container' is the ID of an element in the DOM.
9113 * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
9114 * const provider = new PhoneAuthProvider(auth);
9115 * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
9116 * // Obtain the verificationCode from the user.
9117 * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
9118 * await updatePhoneNumber(user, phoneCredential);
9119 * ```
9120 *
9121 * @param user - The user.
9122 * @param credential - A credential authenticating the new phone number.
9123 *
9124 * @public
9125 */
9126function updatePhoneNumber(user, credential) {
9127 return __awaiter(this, void 0, void 0, function () {
9128 return __generator(this, function (_a) {
9129 switch (_a.label) {
9130 case 0: return [4 /*yield*/, _link$1(getModularInstance(user), credential)];
9131 case 1:
9132 _a.sent();
9133 return [2 /*return*/];
9134 }
9135 });
9136 });
9137}
9138
9139/**
9140 * @license
9141 * Copyright 2020 Google LLC
9142 *
9143 * Licensed under the Apache License, Version 2.0 (the "License");
9144 * you may not use this file except in compliance with the License.
9145 * You may obtain a copy of the License at
9146 *
9147 * http://www.apache.org/licenses/LICENSE-2.0
9148 *
9149 * Unless required by applicable law or agreed to in writing, software
9150 * distributed under the License is distributed on an "AS IS" BASIS,
9151 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9152 * See the License for the specific language governing permissions and
9153 * limitations under the License.
9154 */
9155/**
9156 * Provider for generating an {@link PhoneAuthCredential}.
9157 *
9158 * @example
9159 * ```javascript
9160 * // 'recaptcha-container' is the ID of an element in the DOM.
9161 * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
9162 * const provider = new PhoneAuthProvider(auth);
9163 * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
9164 * // Obtain the verificationCode from the user.
9165 * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
9166 * const userCredential = await signInWithCredential(auth, phoneCredential);
9167 * ```
9168 *
9169 * @public
9170 */
9171var PhoneAuthProvider = /** @class */ (function () {
9172 /**
9173 * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
9174 *
9175 */
9176 function PhoneAuthProvider(auth) {
9177 /** Always set to {@link ProviderId}.PHONE. */
9178 this.providerId = PhoneAuthProvider.PROVIDER_ID;
9179 this.auth = _castAuth(auth);
9180 }
9181 /**
9182 *
9183 * Starts a phone number authentication flow by sending a verification code to the given phone
9184 * number.
9185 *
9186 * @example
9187 * ```javascript
9188 * const provider = new PhoneAuthProvider(auth);
9189 * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
9190 * // Obtain verificationCode from the user.
9191 * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
9192 * const userCredential = await signInWithCredential(auth, authCredential);
9193 * ```
9194 *
9195 * @example
9196 * An alternative flow is provided using the `signInWithPhoneNumber` method.
9197 * ```javascript
9198 * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
9199 * // Obtain verificationCode from the user.
9200 * const userCredential = confirmationResult.confirm(verificationCode);
9201 * ```
9202 *
9203 * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
9204 * E.164 format (e.g. +16505550101).
9205 * @param applicationVerifier - For abuse prevention, this method also requires a
9206 * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
9207 * {@link RecaptchaVerifier}.
9208 *
9209 * @returns A Promise for a verification ID that can be passed to
9210 * {@link PhoneAuthProvider.credential} to identify this flow..
9211 */
9212 PhoneAuthProvider.prototype.verifyPhoneNumber = function (phoneOptions, applicationVerifier) {
9213 return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
9214 };
9215 /**
9216 * Creates a phone auth credential, given the verification ID from
9217 * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
9218 * mobile device.
9219 *
9220 * @example
9221 * ```javascript
9222 * const provider = new PhoneAuthProvider(auth);
9223 * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
9224 * // Obtain verificationCode from the user.
9225 * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
9226 * const userCredential = signInWithCredential(auth, authCredential);
9227 * ```
9228 *
9229 * @example
9230 * An alternative flow is provided using the `signInWithPhoneNumber` method.
9231 * ```javascript
9232 * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
9233 * // Obtain verificationCode from the user.
9234 * const userCredential = await confirmationResult.confirm(verificationCode);
9235 * ```
9236 *
9237 * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
9238 * @param verificationCode - The verification code sent to the user's mobile device.
9239 *
9240 * @returns The auth provider credential.
9241 */
9242 PhoneAuthProvider.credential = function (verificationId, verificationCode) {
9243 return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
9244 };
9245 /**
9246 * Generates an {@link AuthCredential} from a {@link UserCredential}.
9247 * @param userCredential - The user credential.
9248 */
9249 PhoneAuthProvider.credentialFromResult = function (userCredential) {
9250 var credential = userCredential;
9251 return PhoneAuthProvider.credentialFromTaggedObject(credential);
9252 };
9253 /**
9254 * Returns an {@link AuthCredential} when passed an error.
9255 *
9256 * @remarks
9257 *
9258 * This method works for errors like
9259 * `auth/account-exists-with-different-credentials`. This is useful for
9260 * recovering when attempting to set a user's phone number but the number
9261 * in question is already tied to another account. For example, the following
9262 * code tries to update the current user's phone number, and if that
9263 * fails, links the user with the account associated with that number:
9264 *
9265 * ```js
9266 * const provider = new PhoneAuthProvider(auth);
9267 * const verificationId = await provider.verifyPhoneNumber(number, verifier);
9268 * try {
9269 * const code = ''; // Prompt the user for the verification code
9270 * await updatePhoneNumber(
9271 * auth.currentUser,
9272 * PhoneAuthProvider.credential(verificationId, code));
9273 * } catch (e) {
9274 * if (e.code === 'auth/account-exists-with-different-credential') {
9275 * const cred = PhoneAuthProvider.credentialFromError(e);
9276 * await linkWithCredential(auth.currentUser, cred);
9277 * }
9278 * }
9279 *
9280 * // At this point, auth.currentUser.phoneNumber === number.
9281 * ```
9282 *
9283 * @param error - The error to generate a credential from.
9284 */
9285 PhoneAuthProvider.credentialFromError = function (error) {
9286 return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
9287 };
9288 PhoneAuthProvider.credentialFromTaggedObject = function (_a) {
9289 var tokenResponse = _a._tokenResponse;
9290 if (!tokenResponse) {
9291 return null;
9292 }
9293 var _b = tokenResponse, phoneNumber = _b.phoneNumber, temporaryProof = _b.temporaryProof;
9294 if (phoneNumber && temporaryProof) {
9295 return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
9296 }
9297 return null;
9298 };
9299 /** Always set to {@link ProviderId}.PHONE. */
9300 PhoneAuthProvider.PROVIDER_ID = "phone" /* PHONE */;
9301 /** Always set to {@link SignInMethod}.PHONE. */
9302 PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* PHONE */;
9303 return PhoneAuthProvider;
9304}());
9305
9306/**
9307 * @license
9308 * Copyright 2021 Google LLC
9309 *
9310 * Licensed under the Apache License, Version 2.0 (the "License");
9311 * you may not use this file except in compliance with the License.
9312 * You may obtain a copy of the License at
9313 *
9314 * http://www.apache.org/licenses/LICENSE-2.0
9315 *
9316 * Unless required by applicable law or agreed to in writing, software
9317 * distributed under the License is distributed on an "AS IS" BASIS,
9318 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9319 * See the License for the specific language governing permissions and
9320 * limitations under the License.
9321 */
9322/**
9323 * Chooses a popup/redirect resolver to use. This prefers the override (which
9324 * is directly passed in), and falls back to the property set on the auth
9325 * object. If neither are available, this function errors w/ an argument error.
9326 */
9327function _withDefaultResolver(auth, resolverOverride) {
9328 if (resolverOverride) {
9329 return _getInstance(resolverOverride);
9330 }
9331 _assert(auth._popupRedirectResolver, auth, "argument-error" /* ARGUMENT_ERROR */);
9332 return auth._popupRedirectResolver;
9333}
9334
9335/**
9336 * @license
9337 * Copyright 2019 Google LLC
9338 *
9339 * Licensed under the Apache License, Version 2.0 (the "License");
9340 * you may not use this file except in compliance with the License.
9341 * You may obtain a copy of the License at
9342 *
9343 * http://www.apache.org/licenses/LICENSE-2.0
9344 *
9345 * Unless required by applicable law or agreed to in writing, software
9346 * distributed under the License is distributed on an "AS IS" BASIS,
9347 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9348 * See the License for the specific language governing permissions and
9349 * limitations under the License.
9350 */
9351var IdpCredential = /** @class */ (function (_super) {
9352 __extends(IdpCredential, _super);
9353 function IdpCredential(params) {
9354 var _this = _super.call(this, "custom" /* CUSTOM */, "custom" /* CUSTOM */) || this;
9355 _this.params = params;
9356 return _this;
9357 }
9358 IdpCredential.prototype._getIdTokenResponse = function (auth) {
9359 return signInWithIdp(auth, this._buildIdpRequest());
9360 };
9361 IdpCredential.prototype._linkToIdToken = function (auth, idToken) {
9362 return signInWithIdp(auth, this._buildIdpRequest(idToken));
9363 };
9364 IdpCredential.prototype._getReauthenticationResolver = function (auth) {
9365 return signInWithIdp(auth, this._buildIdpRequest());
9366 };
9367 IdpCredential.prototype._buildIdpRequest = function (idToken) {
9368 var request = {
9369 requestUri: this.params.requestUri,
9370 sessionId: this.params.sessionId,
9371 postBody: this.params.postBody,
9372 tenantId: this.params.tenantId,
9373 pendingToken: this.params.pendingToken,
9374 returnSecureToken: true,
9375 returnIdpCredential: true
9376 };
9377 if (idToken) {
9378 request.idToken = idToken;
9379 }
9380 return request;
9381 };
9382 return IdpCredential;
9383}(AuthCredential));
9384function _signIn(params) {
9385 return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
9386}
9387function _reauth(params) {
9388 var auth = params.auth, user = params.user;
9389 _assert(user, auth, "internal-error" /* INTERNAL_ERROR */);
9390 return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
9391}
9392function _link(params) {
9393 return __awaiter(this, void 0, void 0, function () {
9394 var auth, user;
9395 return __generator(this, function (_a) {
9396 auth = params.auth, user = params.user;
9397 _assert(user, auth, "internal-error" /* INTERNAL_ERROR */);
9398 return [2 /*return*/, _link$1(user, new IdpCredential(params), params.bypassAuthState)];
9399 });
9400 });
9401}
9402
9403/**
9404 * @license
9405 * Copyright 2020 Google LLC
9406 *
9407 * Licensed under the Apache License, Version 2.0 (the "License");
9408 * you may not use this file except in compliance with the License.
9409 * You may obtain a copy of the License at
9410 *
9411 * http://www.apache.org/licenses/LICENSE-2.0
9412 *
9413 * Unless required by applicable law or agreed to in writing, software
9414 * distributed under the License is distributed on an "AS IS" BASIS,
9415 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9416 * See the License for the specific language governing permissions and
9417 * limitations under the License.
9418 */
9419/**
9420 * Popup event manager. Handles the popup's entire lifecycle; listens to auth
9421 * events
9422 */
9423var AbstractPopupRedirectOperation = /** @class */ (function () {
9424 function AbstractPopupRedirectOperation(auth, filter, resolver, user, bypassAuthState) {
9425 if (bypassAuthState === void 0) { bypassAuthState = false; }
9426 this.auth = auth;
9427 this.resolver = resolver;
9428 this.user = user;
9429 this.bypassAuthState = bypassAuthState;
9430 this.pendingPromise = null;
9431 this.eventManager = null;
9432 this.filter = Array.isArray(filter) ? filter : [filter];
9433 }
9434 AbstractPopupRedirectOperation.prototype.execute = function () {
9435 var _this = this;
9436 return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
9437 var _a, e_1;
9438 return __generator(this, function (_b) {
9439 switch (_b.label) {
9440 case 0:
9441 this.pendingPromise = { resolve: resolve, reject: reject };
9442 _b.label = 1;
9443 case 1:
9444 _b.trys.push([1, 4, , 5]);
9445 _a = this;
9446 return [4 /*yield*/, this.resolver._initialize(this.auth)];
9447 case 2:
9448 _a.eventManager = _b.sent();
9449 return [4 /*yield*/, this.onExecution()];
9450 case 3:
9451 _b.sent();
9452 this.eventManager.registerConsumer(this);
9453 return [3 /*break*/, 5];
9454 case 4:
9455 e_1 = _b.sent();
9456 this.reject(e_1);
9457 return [3 /*break*/, 5];
9458 case 5: return [2 /*return*/];
9459 }
9460 });
9461 }); });
9462 };
9463 AbstractPopupRedirectOperation.prototype.onAuthEvent = function (event) {
9464 return __awaiter(this, void 0, void 0, function () {
9465 var urlResponse, sessionId, postBody, tenantId, error, type, params, _a, e_2;
9466 return __generator(this, function (_b) {
9467 switch (_b.label) {
9468 case 0:
9469 urlResponse = event.urlResponse, sessionId = event.sessionId, postBody = event.postBody, tenantId = event.tenantId, error = event.error, type = event.type;
9470 if (error) {
9471 this.reject(error);
9472 return [2 /*return*/];
9473 }
9474 params = {
9475 auth: this.auth,
9476 requestUri: urlResponse,
9477 sessionId: sessionId,
9478 tenantId: tenantId || undefined,
9479 postBody: postBody || undefined,
9480 user: this.user,
9481 bypassAuthState: this.bypassAuthState
9482 };
9483 _b.label = 1;
9484 case 1:
9485 _b.trys.push([1, 3, , 4]);
9486 _a = this.resolve;
9487 return [4 /*yield*/, this.getIdpTask(type)(params)];
9488 case 2:
9489 _a.apply(this, [_b.sent()]);
9490 return [3 /*break*/, 4];
9491 case 3:
9492 e_2 = _b.sent();
9493 this.reject(e_2);
9494 return [3 /*break*/, 4];
9495 case 4: return [2 /*return*/];
9496 }
9497 });
9498 });
9499 };
9500 AbstractPopupRedirectOperation.prototype.onError = function (error) {
9501 this.reject(error);
9502 };
9503 AbstractPopupRedirectOperation.prototype.getIdpTask = function (type) {
9504 switch (type) {
9505 case "signInViaPopup" /* SIGN_IN_VIA_POPUP */:
9506 case "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */:
9507 return _signIn;
9508 case "linkViaPopup" /* LINK_VIA_POPUP */:
9509 case "linkViaRedirect" /* LINK_VIA_REDIRECT */:
9510 return _link;
9511 case "reauthViaPopup" /* REAUTH_VIA_POPUP */:
9512 case "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */:
9513 return _reauth;
9514 default:
9515 _fail(this.auth, "internal-error" /* INTERNAL_ERROR */);
9516 }
9517 };
9518 AbstractPopupRedirectOperation.prototype.resolve = function (cred) {
9519 debugAssert(this.pendingPromise, 'Pending promise was never set');
9520 this.pendingPromise.resolve(cred);
9521 this.unregisterAndCleanUp();
9522 };
9523 AbstractPopupRedirectOperation.prototype.reject = function (error) {
9524 debugAssert(this.pendingPromise, 'Pending promise was never set');
9525 this.pendingPromise.reject(error);
9526 this.unregisterAndCleanUp();
9527 };
9528 AbstractPopupRedirectOperation.prototype.unregisterAndCleanUp = function () {
9529 if (this.eventManager) {
9530 this.eventManager.unregisterConsumer(this);
9531 }
9532 this.pendingPromise = null;
9533 this.cleanUp();
9534 };
9535 return AbstractPopupRedirectOperation;
9536}());
9537
9538/**
9539 * @license
9540 * Copyright 2020 Google LLC
9541 *
9542 * Licensed under the Apache License, Version 2.0 (the "License");
9543 * you may not use this file except in compliance with the License.
9544 * You may obtain a copy of the License at
9545 *
9546 * http://www.apache.org/licenses/LICENSE-2.0
9547 *
9548 * Unless required by applicable law or agreed to in writing, software
9549 * distributed under the License is distributed on an "AS IS" BASIS,
9550 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9551 * See the License for the specific language governing permissions and
9552 * limitations under the License.
9553 */
9554var _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);
9555/**
9556 * Authenticates a Firebase client using a popup-based OAuth authentication flow.
9557 *
9558 * @remarks
9559 * If succeeds, returns the signed in user along with the provider's credential. If sign in was
9560 * unsuccessful, returns an error object containing additional information about the error.
9561 *
9562 * @example
9563 * ```javascript
9564 * // Sign in using a popup.
9565 * const provider = new FacebookAuthProvider();
9566 * const result = await signInWithPopup(auth, provider);
9567 *
9568 * // The signed-in user info.
9569 * const user = result.user;
9570 * // This gives you a Facebook Access Token.
9571 * const credential = provider.credentialFromResult(auth, result);
9572 * const token = credential.accessToken;
9573 * ```
9574 *
9575 * @param auth - The {@link Auth} instance.
9576 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
9577 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
9578 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
9579 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
9580 *
9581 *
9582 * @public
9583 */
9584function signInWithPopup(auth, provider, resolver) {
9585 return __awaiter(this, void 0, void 0, function () {
9586 var authInternal, resolverInternal, action;
9587 return __generator(this, function (_a) {
9588 authInternal = _castAuth(auth);
9589 _assertInstanceOf(auth, provider, FederatedAuthProvider);
9590 resolverInternal = _withDefaultResolver(authInternal, resolver);
9591 action = new PopupOperation(authInternal, "signInViaPopup" /* SIGN_IN_VIA_POPUP */, provider, resolverInternal);
9592 return [2 /*return*/, action.executeNotNull()];
9593 });
9594 });
9595}
9596/**
9597 * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
9598 * OAuth flow.
9599 *
9600 * @remarks
9601 * If the reauthentication is successful, the returned result will contain the user and the
9602 * provider's credential.
9603 *
9604 * @example
9605 * ```javascript
9606 * // Sign in using a popup.
9607 * const provider = new FacebookAuthProvider();
9608 * const result = await signInWithPopup(auth, provider);
9609 * // Reauthenticate using a popup.
9610 * await reauthenticateWithPopup(result.user, provider);
9611 * ```
9612 *
9613 * @param user - The user.
9614 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
9615 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
9616 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
9617 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
9618 *
9619 * @public
9620 */
9621function reauthenticateWithPopup(user, provider, resolver) {
9622 return __awaiter(this, void 0, void 0, function () {
9623 var userInternal, resolverInternal, action;
9624 return __generator(this, function (_a) {
9625 userInternal = getModularInstance(user);
9626 _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
9627 resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
9628 action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
9629 return [2 /*return*/, action.executeNotNull()];
9630 });
9631 });
9632}
9633/**
9634 * Links the authenticated provider to the user account using a pop-up based OAuth flow.
9635 *
9636 * @remarks
9637 * If the linking is successful, the returned result will contain the user and the provider's credential.
9638 *
9639 *
9640 * @example
9641 * ```javascript
9642 * // Sign in using some other provider.
9643 * const result = await signInWithEmailAndPassword(auth, email, password);
9644 * // Link using a popup.
9645 * const provider = new FacebookAuthProvider();
9646 * await linkWithPopup(result.user, provider);
9647 * ```
9648 *
9649 * @param user - The user.
9650 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
9651 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
9652 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
9653 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
9654 *
9655 * @public
9656 */
9657function linkWithPopup(user, provider, resolver) {
9658 return __awaiter(this, void 0, void 0, function () {
9659 var userInternal, resolverInternal, action;
9660 return __generator(this, function (_a) {
9661 userInternal = getModularInstance(user);
9662 _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
9663 resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
9664 action = new PopupOperation(userInternal.auth, "linkViaPopup" /* LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
9665 return [2 /*return*/, action.executeNotNull()];
9666 });
9667 });
9668}
9669/**
9670 * Popup event manager. Handles the popup's entire lifecycle; listens to auth
9671 * events
9672 *
9673 */
9674var PopupOperation = /** @class */ (function (_super) {
9675 __extends(PopupOperation, _super);
9676 function PopupOperation(auth, filter, provider, resolver, user) {
9677 var _this = _super.call(this, auth, filter, resolver, user) || this;
9678 _this.provider = provider;
9679 _this.authWindow = null;
9680 _this.pollId = null;
9681 if (PopupOperation.currentPopupAction) {
9682 PopupOperation.currentPopupAction.cancel();
9683 }
9684 PopupOperation.currentPopupAction = _this;
9685 return _this;
9686 }
9687 PopupOperation.prototype.executeNotNull = function () {
9688 return __awaiter(this, void 0, void 0, function () {
9689 var result;
9690 return __generator(this, function (_a) {
9691 switch (_a.label) {
9692 case 0: return [4 /*yield*/, this.execute()];
9693 case 1:
9694 result = _a.sent();
9695 _assert(result, this.auth, "internal-error" /* INTERNAL_ERROR */);
9696 return [2 /*return*/, result];
9697 }
9698 });
9699 });
9700 };
9701 PopupOperation.prototype.onExecution = function () {
9702 return __awaiter(this, void 0, void 0, function () {
9703 var eventId, _a;
9704 var _this = this;
9705 return __generator(this, function (_b) {
9706 switch (_b.label) {
9707 case 0:
9708 debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
9709 eventId = _generateEventId();
9710 _a = this;
9711 return [4 /*yield*/, this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
9712 eventId)];
9713 case 1:
9714 _a.authWindow = _b.sent();
9715 this.authWindow.associatedEvent = eventId;
9716 // Check for web storage support and origin validation _after_ the popup is
9717 // loaded. These operations are slow (~1 second or so) Rather than
9718 // waiting on them before opening the window, optimistically open the popup
9719 // and check for storage support at the same time. If storage support is
9720 // not available, this will cause the whole thing to reject properly. It
9721 // will also close the popup, but since the promise has already rejected,
9722 // the popup closed by user poll will reject into the void.
9723 this.resolver._originValidation(this.auth).catch(function (e) {
9724 _this.reject(e);
9725 });
9726 this.resolver._isIframeWebStorageSupported(this.auth, function (isSupported) {
9727 if (!isSupported) {
9728 _this.reject(_createError(_this.auth, "web-storage-unsupported" /* WEB_STORAGE_UNSUPPORTED */));
9729 }
9730 });
9731 // Handle user closure. Notice this does *not* use await
9732 this.pollUserCancellation();
9733 return [2 /*return*/];
9734 }
9735 });
9736 });
9737 };
9738 Object.defineProperty(PopupOperation.prototype, "eventId", {
9739 get: function () {
9740 var _a;
9741 return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
9742 },
9743 enumerable: false,
9744 configurable: true
9745 });
9746 PopupOperation.prototype.cancel = function () {
9747 this.reject(_createError(this.auth, "cancelled-popup-request" /* EXPIRED_POPUP_REQUEST */));
9748 };
9749 PopupOperation.prototype.cleanUp = function () {
9750 if (this.authWindow) {
9751 this.authWindow.close();
9752 }
9753 if (this.pollId) {
9754 window.clearTimeout(this.pollId);
9755 }
9756 this.authWindow = null;
9757 this.pollId = null;
9758 PopupOperation.currentPopupAction = null;
9759 };
9760 PopupOperation.prototype.pollUserCancellation = function () {
9761 var _this = this;
9762 var poll = function () {
9763 var _a, _b;
9764 if ((_b = (_a = _this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
9765 // Make sure that there is sufficient time for whatever action to
9766 // complete. The window could have closed but the sign in network
9767 // call could still be in flight.
9768 _this.pollId = window.setTimeout(function () {
9769 _this.pollId = null;
9770 _this.reject(_createError(_this.auth, "popup-closed-by-user" /* POPUP_CLOSED_BY_USER */));
9771 }, 2000 /* AUTH_EVENT */);
9772 return;
9773 }
9774 _this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
9775 };
9776 poll();
9777 };
9778 // Only one popup is ever shown at once. The lifecycle of the current popup
9779 // can be managed / cancelled by the constructor.
9780 PopupOperation.currentPopupAction = null;
9781 return PopupOperation;
9782}(AbstractPopupRedirectOperation));
9783
9784/**
9785 * @license
9786 * Copyright 2020 Google LLC
9787 *
9788 * Licensed under the Apache License, Version 2.0 (the "License");
9789 * you may not use this file except in compliance with the License.
9790 * You may obtain a copy of the License at
9791 *
9792 * http://www.apache.org/licenses/LICENSE-2.0
9793 *
9794 * Unless required by applicable law or agreed to in writing, software
9795 * distributed under the License is distributed on an "AS IS" BASIS,
9796 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9797 * See the License for the specific language governing permissions and
9798 * limitations under the License.
9799 */
9800var PENDING_REDIRECT_KEY = 'pendingRedirect';
9801// We only get one redirect outcome for any one auth, so just store it
9802// in here.
9803var redirectOutcomeMap = new Map();
9804var RedirectAction = /** @class */ (function (_super) {
9805 __extends(RedirectAction, _super);
9806 function RedirectAction(auth, resolver, bypassAuthState) {
9807 if (bypassAuthState === void 0) { bypassAuthState = false; }
9808 var _this = _super.call(this, auth, [
9809 "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */,
9810 "linkViaRedirect" /* LINK_VIA_REDIRECT */,
9811 "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */,
9812 "unknown" /* UNKNOWN */
9813 ], resolver, undefined, bypassAuthState) || this;
9814 _this.eventId = null;
9815 return _this;
9816 }
9817 /**
9818 * Override the execute function; if we already have a redirect result, then
9819 * just return it.
9820 */
9821 RedirectAction.prototype.execute = function () {
9822 return __awaiter(this, void 0, void 0, function () {
9823 var readyOutcome, hasPendingRedirect, result_1, _a, e_1;
9824 return __generator(this, function (_b) {
9825 switch (_b.label) {
9826 case 0:
9827 readyOutcome = redirectOutcomeMap.get(this.auth._key());
9828 if (!!readyOutcome) return [3 /*break*/, 8];
9829 _b.label = 1;
9830 case 1:
9831 _b.trys.push([1, 6, , 7]);
9832 return [4 /*yield*/, _getAndClearPendingRedirectStatus(this.resolver, this.auth)];
9833 case 2:
9834 hasPendingRedirect = _b.sent();
9835 if (!hasPendingRedirect) return [3 /*break*/, 4];
9836 return [4 /*yield*/, _super.prototype.execute.call(this)];
9837 case 3:
9838 _a = _b.sent();
9839 return [3 /*break*/, 5];
9840 case 4:
9841 _a = null;
9842 _b.label = 5;
9843 case 5:
9844 result_1 = _a;
9845 readyOutcome = function () { return Promise.resolve(result_1); };
9846 return [3 /*break*/, 7];
9847 case 6:
9848 e_1 = _b.sent();
9849 readyOutcome = function () { return Promise.reject(e_1); };
9850 return [3 /*break*/, 7];
9851 case 7:
9852 redirectOutcomeMap.set(this.auth._key(), readyOutcome);
9853 _b.label = 8;
9854 case 8:
9855 // If we're not bypassing auth state, the ready outcome should be set to
9856 // null.
9857 if (!this.bypassAuthState) {
9858 redirectOutcomeMap.set(this.auth._key(), function () { return Promise.resolve(null); });
9859 }
9860 return [2 /*return*/, readyOutcome()];
9861 }
9862 });
9863 });
9864 };
9865 RedirectAction.prototype.onAuthEvent = function (event) {
9866 return __awaiter(this, void 0, void 0, function () {
9867 var user;
9868 return __generator(this, function (_a) {
9869 switch (_a.label) {
9870 case 0:
9871 if (event.type === "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */) {
9872 return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
9873 }
9874 else if (event.type === "unknown" /* UNKNOWN */) {
9875 // This is a sentinel value indicating there's no pending redirect
9876 this.resolve(null);
9877 return [2 /*return*/];
9878 }
9879 if (!event.eventId) return [3 /*break*/, 2];
9880 return [4 /*yield*/, this.auth._redirectUserForId(event.eventId)];
9881 case 1:
9882 user = _a.sent();
9883 if (user) {
9884 this.user = user;
9885 return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
9886 }
9887 else {
9888 this.resolve(null);
9889 }
9890 _a.label = 2;
9891 case 2: return [2 /*return*/];
9892 }
9893 });
9894 });
9895 };
9896 RedirectAction.prototype.onExecution = function () {
9897 return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
9898 return [2 /*return*/];
9899 }); });
9900 };
9901 RedirectAction.prototype.cleanUp = function () { };
9902 return RedirectAction;
9903}(AbstractPopupRedirectOperation));
9904function _getAndClearPendingRedirectStatus(resolver, auth) {
9905 return __awaiter(this, void 0, void 0, function () {
9906 var key, persistence, hasPendingRedirect;
9907 return __generator(this, function (_a) {
9908 switch (_a.label) {
9909 case 0:
9910 key = pendingRedirectKey(auth);
9911 persistence = resolverPersistence(resolver);
9912 return [4 /*yield*/, persistence._isAvailable()];
9913 case 1:
9914 if (!(_a.sent())) {
9915 return [2 /*return*/, false];
9916 }
9917 return [4 /*yield*/, persistence._get(key)];
9918 case 2:
9919 hasPendingRedirect = (_a.sent()) === 'true';
9920 return [4 /*yield*/, persistence._remove(key)];
9921 case 3:
9922 _a.sent();
9923 return [2 /*return*/, hasPendingRedirect];
9924 }
9925 });
9926 });
9927}
9928function _setPendingRedirectStatus(resolver, auth) {
9929 return __awaiter(this, void 0, void 0, function () {
9930 return __generator(this, function (_a) {
9931 return [2 /*return*/, resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true')];
9932 });
9933 });
9934}
9935function _clearRedirectOutcomes() {
9936 redirectOutcomeMap.clear();
9937}
9938function _overrideRedirectResult(auth, result) {
9939 redirectOutcomeMap.set(auth._key(), result);
9940}
9941function resolverPersistence(resolver) {
9942 return _getInstance(resolver._redirectPersistence);
9943}
9944function pendingRedirectKey(auth) {
9945 return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
9946}
9947
9948/**
9949 * @license
9950 * Copyright 2020 Google LLC
9951 *
9952 * Licensed under the Apache License, Version 2.0 (the "License");
9953 * you may not use this file except in compliance with the License.
9954 * You may obtain a copy of the License at
9955 *
9956 * http://www.apache.org/licenses/LICENSE-2.0
9957 *
9958 * Unless required by applicable law or agreed to in writing, software
9959 * distributed under the License is distributed on an "AS IS" BASIS,
9960 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9961 * See the License for the specific language governing permissions and
9962 * limitations under the License.
9963 */
9964/**
9965 * Authenticates a Firebase client using a full-page redirect flow.
9966 *
9967 * @remarks
9968 * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
9969 *
9970 * @example
9971 * ```javascript
9972 * // Sign in using a redirect.
9973 * const provider = new FacebookAuthProvider();
9974 * // You can add additional scopes to the provider:
9975 * provider.addScope('user_birthday');
9976 * // Start a sign in process for an unauthenticated user.
9977 * await signInWithRedirect(auth, provider);
9978 * // This will trigger a full page redirect away from your app
9979 *
9980 * // After returning from the redirect when your app initializes you can obtain the result
9981 * const result = await getRedirectResult(auth);
9982 * if (result) {
9983 * // This is the signed-in user
9984 * const user = result.user;
9985 * // This gives you a Facebook Access Token.
9986 * const credential = provider.credentialFromResult(auth, result);
9987 * const token = credential.accessToken;
9988 * }
9989 * // As this API can be used for sign-in, linking and reauthentication,
9990 * // check the operationType to determine what triggered this redirect
9991 * // operation.
9992 * const operationType = result.operationType;
9993 * ```
9994 *
9995 * @param auth - The {@link Auth} instance.
9996 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
9997 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
9998 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
9999 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
10000 *
10001 * @public
10002 */
10003function signInWithRedirect(auth, provider, resolver) {
10004 return _signInWithRedirect(auth, provider, resolver);
10005}
10006function _signInWithRedirect(auth, provider, resolver) {
10007 return __awaiter(this, void 0, void 0, function () {
10008 var authInternal, resolverInternal;
10009 return __generator(this, function (_a) {
10010 switch (_a.label) {
10011 case 0:
10012 authInternal = _castAuth(auth);
10013 _assertInstanceOf(auth, provider, FederatedAuthProvider);
10014 resolverInternal = _withDefaultResolver(authInternal, resolver);
10015 return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, authInternal)];
10016 case 1:
10017 _a.sent();
10018 return [2 /*return*/, resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */)];
10019 }
10020 });
10021 });
10022}
10023/**
10024 * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
10025 *
10026 * @example
10027 * ```javascript
10028 * // Sign in using a redirect.
10029 * const provider = new FacebookAuthProvider();
10030 * const result = await signInWithRedirect(auth, provider);
10031 * // This will trigger a full page redirect away from your app
10032 *
10033 * // After returning from the redirect when your app initializes you can obtain the result
10034 * const result = await getRedirectResult(auth);
10035 * // Link using a redirect.
10036 * await linkWithRedirect(result.user, provider);
10037 * // This will again trigger a full page redirect away from your app
10038 *
10039 * // After returning from the redirect when your app initializes you can obtain the result
10040 * const result = await getRedirectResult(auth);
10041 * ```
10042 *
10043 * @param user - The user.
10044 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
10045 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
10046 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
10047 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
10048 *
10049 * @public
10050 */
10051function reauthenticateWithRedirect(user, provider, resolver) {
10052 return _reauthenticateWithRedirect(user, provider, resolver);
10053}
10054function _reauthenticateWithRedirect(user, provider, resolver) {
10055 return __awaiter(this, void 0, void 0, function () {
10056 var userInternal, resolverInternal, eventId;
10057 return __generator(this, function (_a) {
10058 switch (_a.label) {
10059 case 0:
10060 userInternal = getModularInstance(user);
10061 _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
10062 resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
10063 return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
10064 case 1:
10065 _a.sent();
10066 return [4 /*yield*/, prepareUserForRedirect(userInternal)];
10067 case 2:
10068 eventId = _a.sent();
10069 return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */, eventId)];
10070 }
10071 });
10072 });
10073}
10074/**
10075 * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
10076 *
10077 * @example
10078 * ```javascript
10079 * // Sign in using some other provider.
10080 * const result = await signInWithEmailAndPassword(auth, email, password);
10081 * // Link using a redirect.
10082 * const provider = new FacebookAuthProvider();
10083 * await linkWithRedirect(result.user, provider);
10084 * // This will trigger a full page redirect away from your app
10085 *
10086 * // After returning from the redirect when your app initializes you can obtain the result
10087 * const result = await getRedirectResult(auth);
10088 * ```
10089 *
10090 * @param user - The user.
10091 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
10092 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
10093 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
10094 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
10095 *
10096 *
10097 * @public
10098 */
10099function linkWithRedirect(user, provider, resolver) {
10100 return _linkWithRedirect(user, provider, resolver);
10101}
10102function _linkWithRedirect(user, provider, resolver) {
10103 return __awaiter(this, void 0, void 0, function () {
10104 var userInternal, resolverInternal, eventId;
10105 return __generator(this, function (_a) {
10106 switch (_a.label) {
10107 case 0:
10108 userInternal = getModularInstance(user);
10109 _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
10110 resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
10111 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, provider.providerId)];
10112 case 1:
10113 _a.sent();
10114 return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
10115 case 2:
10116 _a.sent();
10117 return [4 /*yield*/, prepareUserForRedirect(userInternal)];
10118 case 3:
10119 eventId = _a.sent();
10120 return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* LINK_VIA_REDIRECT */, eventId)];
10121 }
10122 });
10123 });
10124}
10125/**
10126 * Returns a {@link UserCredential} from the redirect-based sign-in flow.
10127 *
10128 * @remarks
10129 * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
10130 * error. If no redirect operation was called, returns a {@link UserCredential}
10131 * with a null `user`.
10132 *
10133 * @example
10134 * ```javascript
10135 * // Sign in using a redirect.
10136 * const provider = new FacebookAuthProvider();
10137 * // You can add additional scopes to the provider:
10138 * provider.addScope('user_birthday');
10139 * // Start a sign in process for an unauthenticated user.
10140 * await signInWithRedirect(auth, provider);
10141 * // This will trigger a full page redirect away from your app
10142 *
10143 * // After returning from the redirect when your app initializes you can obtain the result
10144 * const result = await getRedirectResult(auth);
10145 * if (result) {
10146 * // This is the signed-in user
10147 * const user = result.user;
10148 * // This gives you a Facebook Access Token.
10149 * const credential = provider.credentialFromResult(auth, result);
10150 * const token = credential.accessToken;
10151 * }
10152 * // As this API can be used for sign-in, linking and reauthentication,
10153 * // check the operationType to determine what triggered this redirect
10154 * // operation.
10155 * const operationType = result.operationType;
10156 * ```
10157 *
10158 * @param auth - The {@link Auth} instance.
10159 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
10160 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
10161 *
10162 * @public
10163 */
10164function getRedirectResult(auth, resolver) {
10165 return __awaiter(this, void 0, void 0, function () {
10166 return __generator(this, function (_a) {
10167 switch (_a.label) {
10168 case 0: return [4 /*yield*/, _castAuth(auth)._initializationPromise];
10169 case 1:
10170 _a.sent();
10171 return [2 /*return*/, _getRedirectResult(auth, resolver, false)];
10172 }
10173 });
10174 });
10175}
10176function _getRedirectResult(auth, resolverExtern, bypassAuthState) {
10177 if (bypassAuthState === void 0) { bypassAuthState = false; }
10178 return __awaiter(this, void 0, void 0, function () {
10179 var authInternal, resolver, action, result;
10180 return __generator(this, function (_a) {
10181 switch (_a.label) {
10182 case 0:
10183 authInternal = _castAuth(auth);
10184 resolver = _withDefaultResolver(authInternal, resolverExtern);
10185 action = new RedirectAction(authInternal, resolver, bypassAuthState);
10186 return [4 /*yield*/, action.execute()];
10187 case 1:
10188 result = _a.sent();
10189 if (!(result && !bypassAuthState)) return [3 /*break*/, 4];
10190 delete result.user._redirectEventId;
10191 return [4 /*yield*/, authInternal._persistUserIfCurrent(result.user)];
10192 case 2:
10193 _a.sent();
10194 return [4 /*yield*/, authInternal._setRedirectUser(null, resolverExtern)];
10195 case 3:
10196 _a.sent();
10197 _a.label = 4;
10198 case 4: return [2 /*return*/, result];
10199 }
10200 });
10201 });
10202}
10203function prepareUserForRedirect(user) {
10204 return __awaiter(this, void 0, void 0, function () {
10205 var eventId;
10206 return __generator(this, function (_a) {
10207 switch (_a.label) {
10208 case 0:
10209 eventId = _generateEventId(user.uid + ":::");
10210 user._redirectEventId = eventId;
10211 return [4 /*yield*/, user.auth._setRedirectUser(user)];
10212 case 1:
10213 _a.sent();
10214 return [4 /*yield*/, user.auth._persistUserIfCurrent(user)];
10215 case 2:
10216 _a.sent();
10217 return [2 /*return*/, eventId];
10218 }
10219 });
10220 });
10221}
10222
10223/**
10224 * @license
10225 * Copyright 2020 Google LLC
10226 *
10227 * Licensed under the Apache License, Version 2.0 (the "License");
10228 * you may not use this file except in compliance with the License.
10229 * You may obtain a copy of the License at
10230 *
10231 * http://www.apache.org/licenses/LICENSE-2.0
10232 *
10233 * Unless required by applicable law or agreed to in writing, software
10234 * distributed under the License is distributed on an "AS IS" BASIS,
10235 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10236 * See the License for the specific language governing permissions and
10237 * limitations under the License.
10238 */
10239// The amount of time to store the UIDs of seen events; this is
10240// set to 10 min by default
10241var EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
10242var AuthEventManager = /** @class */ (function () {
10243 function AuthEventManager(auth) {
10244 this.auth = auth;
10245 this.cachedEventUids = new Set();
10246 this.consumers = new Set();
10247 this.queuedRedirectEvent = null;
10248 this.hasHandledPotentialRedirect = false;
10249 this.lastProcessedEventTime = Date.now();
10250 }
10251 AuthEventManager.prototype.registerConsumer = function (authEventConsumer) {
10252 this.consumers.add(authEventConsumer);
10253 if (this.queuedRedirectEvent &&
10254 this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
10255 this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
10256 this.saveEventToCache(this.queuedRedirectEvent);
10257 this.queuedRedirectEvent = null;
10258 }
10259 };
10260 AuthEventManager.prototype.unregisterConsumer = function (authEventConsumer) {
10261 this.consumers.delete(authEventConsumer);
10262 };
10263 AuthEventManager.prototype.onEvent = function (event) {
10264 var _this = this;
10265 // Check if the event has already been handled
10266 if (this.hasEventBeenHandled(event)) {
10267 return false;
10268 }
10269 var handled = false;
10270 this.consumers.forEach(function (consumer) {
10271 if (_this.isEventForConsumer(event, consumer)) {
10272 handled = true;
10273 _this.sendToConsumer(event, consumer);
10274 _this.saveEventToCache(event);
10275 }
10276 });
10277 if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
10278 // If we've already seen a redirect before, or this is a popup event,
10279 // bail now
10280 return handled;
10281 }
10282 this.hasHandledPotentialRedirect = true;
10283 // If the redirect wasn't handled, hang on to it
10284 if (!handled) {
10285 this.queuedRedirectEvent = event;
10286 handled = true;
10287 }
10288 return handled;
10289 };
10290 AuthEventManager.prototype.sendToConsumer = function (event, consumer) {
10291 var _a;
10292 if (event.error && !isNullRedirectEvent(event)) {
10293 var code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
10294 "internal-error" /* INTERNAL_ERROR */;
10295 consumer.onError(_createError(this.auth, code));
10296 }
10297 else {
10298 consumer.onAuthEvent(event);
10299 }
10300 };
10301 AuthEventManager.prototype.isEventForConsumer = function (event, consumer) {
10302 var eventIdMatches = consumer.eventId === null ||
10303 (!!event.eventId && event.eventId === consumer.eventId);
10304 return consumer.filter.includes(event.type) && eventIdMatches;
10305 };
10306 AuthEventManager.prototype.hasEventBeenHandled = function (event) {
10307 if (Date.now() - this.lastProcessedEventTime >=
10308 EVENT_DUPLICATION_CACHE_DURATION_MS) {
10309 this.cachedEventUids.clear();
10310 }
10311 return this.cachedEventUids.has(eventUid(event));
10312 };
10313 AuthEventManager.prototype.saveEventToCache = function (event) {
10314 this.cachedEventUids.add(eventUid(event));
10315 this.lastProcessedEventTime = Date.now();
10316 };
10317 return AuthEventManager;
10318}());
10319function eventUid(e) {
10320 return [e.type, e.eventId, e.sessionId, e.tenantId].filter(function (v) { return v; }).join('-');
10321}
10322function isNullRedirectEvent(_a) {
10323 var type = _a.type, error = _a.error;
10324 return (type === "unknown" /* UNKNOWN */ &&
10325 (error === null || error === void 0 ? void 0 : error.code) === "auth/" + "no-auth-event" /* NO_AUTH_EVENT */);
10326}
10327function isRedirectEvent(event) {
10328 switch (event.type) {
10329 case "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */:
10330 case "linkViaRedirect" /* LINK_VIA_REDIRECT */:
10331 case "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */:
10332 return true;
10333 case "unknown" /* UNKNOWN */:
10334 return isNullRedirectEvent(event);
10335 default:
10336 return false;
10337 }
10338}
10339
10340/**
10341 * @license
10342 * Copyright 2020 Google LLC
10343 *
10344 * Licensed under the Apache License, Version 2.0 (the "License");
10345 * you may not use this file except in compliance with the License.
10346 * You may obtain a copy of the License at
10347 *
10348 * http://www.apache.org/licenses/LICENSE-2.0
10349 *
10350 * Unless required by applicable law or agreed to in writing, software
10351 * distributed under the License is distributed on an "AS IS" BASIS,
10352 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10353 * See the License for the specific language governing permissions and
10354 * limitations under the License.
10355 */
10356function _getProjectConfig(auth, request) {
10357 if (request === void 0) { request = {}; }
10358 return __awaiter(this, void 0, void 0, function () {
10359 return __generator(this, function (_a) {
10360 return [2 /*return*/, _performApiRequest(auth, "GET" /* GET */, "/v1/projects" /* GET_PROJECT_CONFIG */, request)];
10361 });
10362 });
10363}
10364
10365/**
10366 * @license
10367 * Copyright 2020 Google LLC
10368 *
10369 * Licensed under the Apache License, Version 2.0 (the "License");
10370 * you may not use this file except in compliance with the License.
10371 * You may obtain a copy of the License at
10372 *
10373 * http://www.apache.org/licenses/LICENSE-2.0
10374 *
10375 * Unless required by applicable law or agreed to in writing, software
10376 * distributed under the License is distributed on an "AS IS" BASIS,
10377 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10378 * See the License for the specific language governing permissions and
10379 * limitations under the License.
10380 */
10381var IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
10382var HTTP_REGEX = /^https?/;
10383function _validateOrigin(auth) {
10384 return __awaiter(this, void 0, void 0, function () {
10385 var authorizedDomains, _i, authorizedDomains_1, domain;
10386 return __generator(this, function (_a) {
10387 switch (_a.label) {
10388 case 0:
10389 // Skip origin validation if we are in an emulated environment
10390 if (auth.config.emulator) {
10391 return [2 /*return*/];
10392 }
10393 return [4 /*yield*/, _getProjectConfig(auth)];
10394 case 1:
10395 authorizedDomains = (_a.sent()).authorizedDomains;
10396 for (_i = 0, authorizedDomains_1 = authorizedDomains; _i < authorizedDomains_1.length; _i++) {
10397 domain = authorizedDomains_1[_i];
10398 try {
10399 if (matchDomain(domain)) {
10400 return [2 /*return*/];
10401 }
10402 }
10403 catch (_b) {
10404 // Do nothing if there's a URL error; just continue searching
10405 }
10406 }
10407 // In the old SDK, this error also provides helpful messages.
10408 _fail(auth, "unauthorized-domain" /* INVALID_ORIGIN */);
10409 return [2 /*return*/];
10410 }
10411 });
10412 });
10413}
10414function matchDomain(expected) {
10415 var currentUrl = _getCurrentUrl();
10416 var _a = new URL(currentUrl), protocol = _a.protocol, hostname = _a.hostname;
10417 if (expected.startsWith('chrome-extension://')) {
10418 var ceUrl = new URL(expected);
10419 if (ceUrl.hostname === '' && hostname === '') {
10420 // For some reason we're not parsing chrome URLs properly
10421 return (protocol === 'chrome-extension:' &&
10422 expected.replace('chrome-extension://', '') ===
10423 currentUrl.replace('chrome-extension://', ''));
10424 }
10425 return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
10426 }
10427 if (!HTTP_REGEX.test(protocol)) {
10428 return false;
10429 }
10430 if (IP_ADDRESS_REGEX.test(expected)) {
10431 // The domain has to be exactly equal to the pattern, as an IP domain will
10432 // only contain the IP, no extra character.
10433 return hostname === expected;
10434 }
10435 // Dots in pattern should be escaped.
10436 var escapedDomainPattern = expected.replace(/\./g, '\\.');
10437 // Non ip address domains.
10438 // domain.com = *.domain.com OR domain.com
10439 var re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
10440 return re.test(hostname);
10441}
10442
10443/**
10444 * @license
10445 * Copyright 2020 Google LLC.
10446 *
10447 * Licensed under the Apache License, Version 2.0 (the "License");
10448 * you may not use this file except in compliance with the License.
10449 * You may obtain a copy of the License at
10450 *
10451 * http://www.apache.org/licenses/LICENSE-2.0
10452 *
10453 * Unless required by applicable law or agreed to in writing, software
10454 * distributed under the License is distributed on an "AS IS" BASIS,
10455 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10456 * See the License for the specific language governing permissions and
10457 * limitations under the License.
10458 */
10459var NETWORK_TIMEOUT = new Delay(30000, 60000);
10460/**
10461 * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
10462 * it will stop working after a retrial. This is a hack to fix this issue.
10463 */
10464function resetUnloadedGapiModules() {
10465 // Clear last failed gapi.load state to force next gapi.load to first
10466 // load the failed gapi.iframes module.
10467 // Get gapix.beacon context.
10468 var beacon = _window().___jsl;
10469 // Get current hint.
10470 if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
10471 // Get gapi hint.
10472 for (var _i = 0, _a = Object.keys(beacon.H); _i < _a.length; _i++) {
10473 var hint = _a[_i];
10474 // Requested modules.
10475 beacon.H[hint].r = beacon.H[hint].r || [];
10476 // Loaded modules.
10477 beacon.H[hint].L = beacon.H[hint].L || [];
10478 // Set requested modules to a copy of the loaded modules.
10479 beacon.H[hint].r = __spreadArray([], beacon.H[hint].L);
10480 // Clear pending callbacks.
10481 if (beacon.CP) {
10482 for (var i = 0; i < beacon.CP.length; i++) {
10483 // Remove all failed pending callbacks.
10484 beacon.CP[i] = null;
10485 }
10486 }
10487 }
10488 }
10489}
10490function loadGapi(auth) {
10491 return new Promise(function (resolve, reject) {
10492 var _a, _b, _c;
10493 // Function to run when gapi.load is ready.
10494 function loadGapiIframe() {
10495 // The developer may have tried to previously run gapi.load and failed.
10496 // Run this to fix that.
10497 resetUnloadedGapiModules();
10498 gapi.load('gapi.iframes', {
10499 callback: function () {
10500 resolve(gapi.iframes.getContext());
10501 },
10502 ontimeout: function () {
10503 // The above reset may be sufficient, but having this reset after
10504 // failure ensures that if the developer calls gapi.load after the
10505 // connection is re-established and before another attempt to embed
10506 // the iframe, it would work and would not be broken because of our
10507 // failed attempt.
10508 // Timeout when gapi.iframes.Iframe not loaded.
10509 resetUnloadedGapiModules();
10510 reject(_createError(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
10511 },
10512 timeout: NETWORK_TIMEOUT.get()
10513 });
10514 }
10515 if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
10516 // If gapi.iframes.Iframe available, resolve.
10517 resolve(gapi.iframes.getContext());
10518 }
10519 else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
10520 // Gapi loader ready, load gapi.iframes.
10521 loadGapiIframe();
10522 }
10523 else {
10524 // Create a new iframe callback when this is called so as not to overwrite
10525 // any previous defined callback. This happens if this method is called
10526 // multiple times in parallel and could result in the later callback
10527 // overwriting the previous one. This would end up with a iframe
10528 // timeout.
10529 var cbName = _generateCallbackName('iframefcb');
10530 // GApi loader not available, dynamically load platform.js.
10531 _window()[cbName] = function () {
10532 // GApi loader should be ready.
10533 if (!!gapi.load) {
10534 loadGapiIframe();
10535 }
10536 else {
10537 // Gapi loader failed, throw error.
10538 reject(_createError(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
10539 }
10540 };
10541 // Load GApi loader.
10542 return _loadJS("https://apis.google.com/js/api.js?onload=" + cbName).catch(function (e) { return reject(e); });
10543 }
10544 }).catch(function (error) {
10545 // Reset cached promise to allow for retrial.
10546 cachedGApiLoader = null;
10547 throw error;
10548 });
10549}
10550var cachedGApiLoader = null;
10551function _loadGapi(auth) {
10552 cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
10553 return cachedGApiLoader;
10554}
10555
10556/**
10557 * @license
10558 * Copyright 2020 Google LLC.
10559 *
10560 * Licensed under the Apache License, Version 2.0 (the "License");
10561 * you may not use this file except in compliance with the License.
10562 * You may obtain a copy of the License at
10563 *
10564 * http://www.apache.org/licenses/LICENSE-2.0
10565 *
10566 * Unless required by applicable law or agreed to in writing, software
10567 * distributed under the License is distributed on an "AS IS" BASIS,
10568 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10569 * See the License for the specific language governing permissions and
10570 * limitations under the License.
10571 */
10572var PING_TIMEOUT = new Delay(5000, 15000);
10573var IFRAME_PATH = '__/auth/iframe';
10574var EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
10575var IFRAME_ATTRIBUTES = {
10576 style: {
10577 position: 'absolute',
10578 top: '-100px',
10579 width: '1px',
10580 height: '1px'
10581 },
10582 'aria-hidden': 'true',
10583 tabindex: '-1'
10584};
10585// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
10586// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
10587var EID_FROM_APIHOST = new Map([
10588 ["identitytoolkit.googleapis.com" /* API_HOST */, 'p'],
10589 ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
10590 ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
10591]);
10592function getIframeUrl(auth) {
10593 var config = auth.config;
10594 _assert(config.authDomain, auth, "auth-domain-config-required" /* MISSING_AUTH_DOMAIN */);
10595 var url = config.emulator
10596 ? _emulatorUrl(config, EMULATED_IFRAME_PATH)
10597 : "https://" + auth.config.authDomain + "/" + IFRAME_PATH;
10598 var params = {
10599 apiKey: config.apiKey,
10600 appName: auth.name,
10601 v: SDK_VERSION
10602 };
10603 var eid = EID_FROM_APIHOST.get(auth.config.apiHost);
10604 if (eid) {
10605 params.eid = eid;
10606 }
10607 var frameworks = auth._getFrameworks();
10608 if (frameworks.length) {
10609 params.fw = frameworks.join(',');
10610 }
10611 return url + "?" + querystring(params).slice(1);
10612}
10613function _openIframe(auth) {
10614 return __awaiter(this, void 0, void 0, function () {
10615 var context, gapi;
10616 var _this = this;
10617 return __generator(this, function (_a) {
10618 switch (_a.label) {
10619 case 0: return [4 /*yield*/, _loadGapi(auth)];
10620 case 1:
10621 context = _a.sent();
10622 gapi = _window().gapi;
10623 _assert(gapi, auth, "internal-error" /* INTERNAL_ERROR */);
10624 return [2 /*return*/, context.open({
10625 where: document.body,
10626 url: getIframeUrl(auth),
10627 messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
10628 attributes: IFRAME_ATTRIBUTES,
10629 dontclear: true
10630 }, function (iframe) {
10631 return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
10632 // Clear timer and resolve pending iframe ready promise.
10633 function clearTimerAndResolve() {
10634 _window().clearTimeout(networkErrorTimer);
10635 resolve(iframe);
10636 }
10637 var networkError, networkErrorTimer;
10638 return __generator(this, function (_a) {
10639 switch (_a.label) {
10640 case 0: return [4 /*yield*/, iframe.restyle({
10641 // Prevent iframe from closing on mouse out.
10642 setHideOnLeave: false
10643 })];
10644 case 1:
10645 _a.sent();
10646 networkError = _createError(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */);
10647 networkErrorTimer = _window().setTimeout(function () {
10648 reject(networkError);
10649 }, PING_TIMEOUT.get());
10650 // This returns an IThenable. However the reject part does not call
10651 // when the iframe is not loaded.
10652 iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, function () {
10653 reject(networkError);
10654 });
10655 return [2 /*return*/];
10656 }
10657 });
10658 }); });
10659 })];
10660 }
10661 });
10662 });
10663}
10664
10665/**
10666 * @license
10667 * Copyright 2020 Google LLC.
10668 *
10669 * Licensed under the Apache License, Version 2.0 (the "License");
10670 * you may not use this file except in compliance with the License.
10671 * You may obtain a copy of the License at
10672 *
10673 * http://www.apache.org/licenses/LICENSE-2.0
10674 *
10675 * Unless required by applicable law or agreed to in writing, software
10676 * distributed under the License is distributed on an "AS IS" BASIS,
10677 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10678 * See the License for the specific language governing permissions and
10679 * limitations under the License.
10680 */
10681var BASE_POPUP_OPTIONS = {
10682 location: 'yes',
10683 resizable: 'yes',
10684 statusbar: 'yes',
10685 toolbar: 'no'
10686};
10687var DEFAULT_WIDTH = 500;
10688var DEFAULT_HEIGHT = 600;
10689var TARGET_BLANK = '_blank';
10690var FIREFOX_EMPTY_URL = 'http://localhost';
10691var AuthPopup = /** @class */ (function () {
10692 function AuthPopup(window) {
10693 this.window = window;
10694 this.associatedEvent = null;
10695 }
10696 AuthPopup.prototype.close = function () {
10697 if (this.window) {
10698 try {
10699 this.window.close();
10700 }
10701 catch (e) { }
10702 }
10703 };
10704 return AuthPopup;
10705}());
10706function _open(auth, url, name, width, height) {
10707 if (width === void 0) { width = DEFAULT_WIDTH; }
10708 if (height === void 0) { height = DEFAULT_HEIGHT; }
10709 var top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
10710 var left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
10711 var target = '';
10712 var options = __assign(__assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top: top,
10713 left: left });
10714 // Chrome iOS 7 and 8 is returning an undefined popup win when target is
10715 // specified, even though the popup is not necessarily blocked.
10716 var ua = getUA().toLowerCase();
10717 if (name) {
10718 target = _isChromeIOS(ua) ? TARGET_BLANK : name;
10719 }
10720 if (_isFirefox(ua)) {
10721 // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
10722 url = url || FIREFOX_EMPTY_URL;
10723 // Firefox disables by default scrolling on popup windows, which can create
10724 // issues when the user has many Google accounts, for instance.
10725 options.scrollbars = 'yes';
10726 }
10727 var optionsString = Object.entries(options).reduce(function (accum, _a) {
10728 var key = _a[0], value = _a[1];
10729 return "" + accum + key + "=" + value + ",";
10730 }, '');
10731 if (_isIOSStandalone(ua) && target !== '_self') {
10732 openAsNewWindowIOS(url || '', target);
10733 return new AuthPopup(null);
10734 }
10735 // about:blank getting sanitized causing browsers like IE/Edge to display
10736 // brief error message before redirecting to handler.
10737 var newWin = window.open(url || '', target, optionsString);
10738 _assert(newWin, auth, "popup-blocked" /* POPUP_BLOCKED */);
10739 // Flaky on IE edge, encapsulate with a try and catch.
10740 try {
10741 newWin.focus();
10742 }
10743 catch (e) { }
10744 return new AuthPopup(newWin);
10745}
10746function openAsNewWindowIOS(url, target) {
10747 var el = document.createElement('a');
10748 el.href = url;
10749 el.target = target;
10750 var click = document.createEvent('MouseEvent');
10751 click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
10752 el.dispatchEvent(click);
10753}
10754
10755/**
10756 * @license
10757 * Copyright 2021 Google LLC
10758 *
10759 * Licensed under the Apache License, Version 2.0 (the "License");
10760 * you may not use this file except in compliance with the License.
10761 * You may obtain a copy of the License at
10762 *
10763 * http://www.apache.org/licenses/LICENSE-2.0
10764 *
10765 * Unless required by applicable law or agreed to in writing, software
10766 * distributed under the License is distributed on an "AS IS" BASIS,
10767 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10768 * See the License for the specific language governing permissions and
10769 * limitations under the License.
10770 */
10771/**
10772 * URL for Authentication widget which will initiate the OAuth handshake
10773 *
10774 * @internal
10775 */
10776var WIDGET_PATH = '__/auth/handler';
10777/**
10778 * URL for emulated environment
10779 *
10780 * @internal
10781 */
10782var EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
10783function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
10784 _assert(auth.config.authDomain, auth, "auth-domain-config-required" /* MISSING_AUTH_DOMAIN */);
10785 _assert(auth.config.apiKey, auth, "invalid-api-key" /* INVALID_API_KEY */);
10786 var params = {
10787 apiKey: auth.config.apiKey,
10788 appName: auth.name,
10789 authType: authType,
10790 redirectUrl: redirectUrl,
10791 v: SDK_VERSION,
10792 eventId: eventId
10793 };
10794 if (provider instanceof FederatedAuthProvider) {
10795 provider.setDefaultLanguage(auth.languageCode);
10796 params.providerId = provider.providerId || '';
10797 if (!isEmpty(provider.getCustomParameters())) {
10798 params.customParameters = JSON.stringify(provider.getCustomParameters());
10799 }
10800 // TODO set additionalParams from the provider as well?
10801 for (var _i = 0, _a = Object.entries(additionalParams || {}); _i < _a.length; _i++) {
10802 var _b = _a[_i], key = _b[0], value = _b[1];
10803 params[key] = value;
10804 }
10805 }
10806 if (provider instanceof BaseOAuthProvider) {
10807 var scopes = provider.getScopes().filter(function (scope) { return scope !== ''; });
10808 if (scopes.length > 0) {
10809 params.scopes = scopes.join(',');
10810 }
10811 }
10812 if (auth.tenantId) {
10813 params.tid = auth.tenantId;
10814 }
10815 // TODO: maybe set eid as endipointId
10816 // TODO: maybe set fw as Frameworks.join(",")
10817 var paramsDict = params;
10818 for (var _c = 0, _d = Object.keys(paramsDict); _c < _d.length; _c++) {
10819 var key = _d[_c];
10820 if (paramsDict[key] === undefined) {
10821 delete paramsDict[key];
10822 }
10823 }
10824 return getHandlerBase(auth) + "?" + querystring(paramsDict).slice(1);
10825}
10826function getHandlerBase(_a) {
10827 var config = _a.config;
10828 if (!config.emulator) {
10829 return "https://" + config.authDomain + "/" + WIDGET_PATH;
10830 }
10831 return _emulatorUrl(config, EMULATOR_WIDGET_PATH);
10832}
10833
10834/**
10835 * @license
10836 * Copyright 2020 Google LLC
10837 *
10838 * Licensed under the Apache License, Version 2.0 (the "License");
10839 * you may not use this file except in compliance with the License.
10840 * You may obtain a copy of the License at
10841 *
10842 * http://www.apache.org/licenses/LICENSE-2.0
10843 *
10844 * Unless required by applicable law or agreed to in writing, software
10845 * distributed under the License is distributed on an "AS IS" BASIS,
10846 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10847 * See the License for the specific language governing permissions and
10848 * limitations under the License.
10849 */
10850/**
10851 * The special web storage event
10852 *
10853 */
10854var WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
10855var BrowserPopupRedirectResolver = /** @class */ (function () {
10856 function BrowserPopupRedirectResolver() {
10857 this.eventManagers = {};
10858 this.iframes = {};
10859 this.originValidationPromises = {};
10860 this._redirectPersistence = browserSessionPersistence;
10861 this._completeRedirectFn = _getRedirectResult;
10862 this._overrideRedirectResult = _overrideRedirectResult;
10863 }
10864 // Wrapping in async even though we don't await anywhere in order
10865 // to make sure errors are raised as promise rejections
10866 BrowserPopupRedirectResolver.prototype._openPopup = function (auth, provider, authType, eventId) {
10867 var _a;
10868 return __awaiter(this, void 0, void 0, function () {
10869 var url;
10870 return __generator(this, function (_b) {
10871 debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
10872 url = _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
10873 return [2 /*return*/, _open(auth, url, _generateEventId())];
10874 });
10875 });
10876 };
10877 BrowserPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
10878 return __awaiter(this, void 0, void 0, function () {
10879 return __generator(this, function (_a) {
10880 switch (_a.label) {
10881 case 0: return [4 /*yield*/, this._originValidation(auth)];
10882 case 1:
10883 _a.sent();
10884 _setWindowLocation(_getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId));
10885 return [2 /*return*/, new Promise(function () { })];
10886 }
10887 });
10888 });
10889 };
10890 BrowserPopupRedirectResolver.prototype._initialize = function (auth) {
10891 var _this = this;
10892 var key = auth._key();
10893 if (this.eventManagers[key]) {
10894 var _a = this.eventManagers[key], manager = _a.manager, promise_1 = _a.promise;
10895 if (manager) {
10896 return Promise.resolve(manager);
10897 }
10898 else {
10899 debugAssert(promise_1, 'If manager is not set, promise should be');
10900 return promise_1;
10901 }
10902 }
10903 var promise = this.initAndGetManager(auth);
10904 this.eventManagers[key] = { promise: promise };
10905 // If the promise is rejected, the key should be removed so that the
10906 // operation can be retried later.
10907 promise.catch(function () {
10908 delete _this.eventManagers[key];
10909 });
10910 return promise;
10911 };
10912 BrowserPopupRedirectResolver.prototype.initAndGetManager = function (auth) {
10913 return __awaiter(this, void 0, void 0, function () {
10914 var iframe, manager;
10915 return __generator(this, function (_a) {
10916 switch (_a.label) {
10917 case 0: return [4 /*yield*/, _openIframe(auth)];
10918 case 1:
10919 iframe = _a.sent();
10920 manager = new AuthEventManager(auth);
10921 iframe.register('authEvent', function (iframeEvent) {
10922 _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* INVALID_AUTH_EVENT */);
10923 // TODO: Consider splitting redirect and popup events earlier on
10924 var handled = manager.onEvent(iframeEvent.authEvent);
10925 return { status: handled ? "ACK" /* ACK */ : "ERROR" /* ERROR */ };
10926 }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
10927 this.eventManagers[auth._key()] = { manager: manager };
10928 this.iframes[auth._key()] = iframe;
10929 return [2 /*return*/, manager];
10930 }
10931 });
10932 });
10933 };
10934 BrowserPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (auth, cb) {
10935 var iframe = this.iframes[auth._key()];
10936 iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, function (result) {
10937 var _a;
10938 var isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
10939 if (isSupported !== undefined) {
10940 cb(!!isSupported);
10941 }
10942 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
10943 }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
10944 };
10945 BrowserPopupRedirectResolver.prototype._originValidation = function (auth) {
10946 var key = auth._key();
10947 if (!this.originValidationPromises[key]) {
10948 this.originValidationPromises[key] = _validateOrigin(auth);
10949 }
10950 return this.originValidationPromises[key];
10951 };
10952 Object.defineProperty(BrowserPopupRedirectResolver.prototype, "_shouldInitProactively", {
10953 get: function () {
10954 // Mobile browsers and Safari need to optimistically initialize
10955 return _isMobileBrowser() || _isSafari() || _isIOS();
10956 },
10957 enumerable: false,
10958 configurable: true
10959 });
10960 return BrowserPopupRedirectResolver;
10961}());
10962/**
10963 * An implementation of {@link PopupRedirectResolver} suitable for browser
10964 * based applications.
10965 *
10966 * @public
10967 */
10968var browserPopupRedirectResolver = BrowserPopupRedirectResolver;
10969
10970var MultiFactorAssertionImpl = /** @class */ (function () {
10971 function MultiFactorAssertionImpl(factorId) {
10972 this.factorId = factorId;
10973 }
10974 MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
10975 switch (session.type) {
10976 case "enroll" /* ENROLL */:
10977 return this._finalizeEnroll(auth, session.credential, displayName);
10978 case "signin" /* SIGN_IN */:
10979 return this._finalizeSignIn(auth, session.credential);
10980 default:
10981 return debugFail('unexpected MultiFactorSessionType');
10982 }
10983 };
10984 return MultiFactorAssertionImpl;
10985}());
10986
10987/**
10988 * {@inheritdoc PhoneMultiFactorAssertion}
10989 *
10990 * @public
10991 */
10992var PhoneMultiFactorAssertionImpl = /** @class */ (function (_super) {
10993 __extends(PhoneMultiFactorAssertionImpl, _super);
10994 function PhoneMultiFactorAssertionImpl(credential) {
10995 var _this = _super.call(this, "phone" /* PHONE */) || this;
10996 _this.credential = credential;
10997 return _this;
10998 }
10999 /** @internal */
11000 PhoneMultiFactorAssertionImpl._fromCredential = function (credential) {
11001 return new PhoneMultiFactorAssertionImpl(credential);
11002 };
11003 /** @internal */
11004 PhoneMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
11005 return finalizeEnrollPhoneMfa(auth, {
11006 idToken: idToken,
11007 displayName: displayName,
11008 phoneVerificationInfo: this.credential._makeVerificationRequest()
11009 });
11010 };
11011 /** @internal */
11012 PhoneMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
11013 return finalizeSignInPhoneMfa(auth, {
11014 mfaPendingCredential: mfaPendingCredential,
11015 phoneVerificationInfo: this.credential._makeVerificationRequest()
11016 });
11017 };
11018 return PhoneMultiFactorAssertionImpl;
11019}(MultiFactorAssertionImpl));
11020/**
11021 * Provider for generating a {@link PhoneMultiFactorAssertion}.
11022 *
11023 * @public
11024 */
11025var PhoneMultiFactorGenerator = /** @class */ (function () {
11026 function PhoneMultiFactorGenerator() {
11027 }
11028 /**
11029 * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
11030 *
11031 * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
11032 * @returns A {@link PhoneMultiFactorAssertion} which can be used with
11033 * {@link MultiFactorResolver.resolveSignIn}
11034 */
11035 PhoneMultiFactorGenerator.assertion = function (credential) {
11036 return PhoneMultiFactorAssertionImpl._fromCredential(credential);
11037 };
11038 /**
11039 * The identifier of the phone second factor: `phone`.
11040 */
11041 PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
11042 return PhoneMultiFactorGenerator;
11043}());
11044
11045var name = "@firebase/auth";
11046var version = "0.20.1";
11047
11048/**
11049 * @license
11050 * Copyright 2020 Google LLC
11051 *
11052 * Licensed under the Apache License, Version 2.0 (the "License");
11053 * you may not use this file except in compliance with the License.
11054 * You may obtain a copy of the License at
11055 *
11056 * http://www.apache.org/licenses/LICENSE-2.0
11057 *
11058 * Unless required by applicable law or agreed to in writing, software
11059 * distributed under the License is distributed on an "AS IS" BASIS,
11060 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11061 * See the License for the specific language governing permissions and
11062 * limitations under the License.
11063 */
11064var AuthInterop = /** @class */ (function () {
11065 function AuthInterop(auth) {
11066 this.auth = auth;
11067 this.internalListeners = new Map();
11068 }
11069 AuthInterop.prototype.getUid = function () {
11070 var _a;
11071 this.assertAuthConfigured();
11072 return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
11073 };
11074 AuthInterop.prototype.getToken = function (forceRefresh) {
11075 return __awaiter(this, void 0, void 0, function () {
11076 var accessToken;
11077 return __generator(this, function (_a) {
11078 switch (_a.label) {
11079 case 0:
11080 this.assertAuthConfigured();
11081 return [4 /*yield*/, this.auth._initializationPromise];
11082 case 1:
11083 _a.sent();
11084 if (!this.auth.currentUser) {
11085 return [2 /*return*/, null];
11086 }
11087 return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
11088 case 2:
11089 accessToken = _a.sent();
11090 return [2 /*return*/, { accessToken: accessToken }];
11091 }
11092 });
11093 });
11094 };
11095 AuthInterop.prototype.addAuthTokenListener = function (listener) {
11096 this.assertAuthConfigured();
11097 if (this.internalListeners.has(listener)) {
11098 return;
11099 }
11100 var unsubscribe = this.auth.onIdTokenChanged(function (user) {
11101 var _a;
11102 listener(((_a = user) === null || _a === void 0 ? void 0 : _a.stsTokenManager.accessToken) || null);
11103 });
11104 this.internalListeners.set(listener, unsubscribe);
11105 this.updateProactiveRefresh();
11106 };
11107 AuthInterop.prototype.removeAuthTokenListener = function (listener) {
11108 this.assertAuthConfigured();
11109 var unsubscribe = this.internalListeners.get(listener);
11110 if (!unsubscribe) {
11111 return;
11112 }
11113 this.internalListeners.delete(listener);
11114 unsubscribe();
11115 this.updateProactiveRefresh();
11116 };
11117 AuthInterop.prototype.assertAuthConfigured = function () {
11118 _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */);
11119 };
11120 AuthInterop.prototype.updateProactiveRefresh = function () {
11121 if (this.internalListeners.size > 0) {
11122 this.auth._startProactiveRefresh();
11123 }
11124 else {
11125 this.auth._stopProactiveRefresh();
11126 }
11127 };
11128 return AuthInterop;
11129}());
11130
11131/**
11132 * @license
11133 * Copyright 2020 Google LLC
11134 *
11135 * Licensed under the Apache License, Version 2.0 (the "License");
11136 * you may not use this file except in compliance with the License.
11137 * You may obtain a copy of the License at
11138 *
11139 * http://www.apache.org/licenses/LICENSE-2.0
11140 *
11141 * Unless required by applicable law or agreed to in writing, software
11142 * distributed under the License is distributed on an "AS IS" BASIS,
11143 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11144 * See the License for the specific language governing permissions and
11145 * limitations under the License.
11146 */
11147function getVersionForPlatform(clientPlatform) {
11148 switch (clientPlatform) {
11149 case "Node" /* NODE */:
11150 return 'node';
11151 case "ReactNative" /* REACT_NATIVE */:
11152 return 'rn';
11153 case "Worker" /* WORKER */:
11154 return 'webworker';
11155 case "Cordova" /* CORDOVA */:
11156 return 'cordova';
11157 default:
11158 return undefined;
11159 }
11160}
11161/** @internal */
11162function registerAuth(clientPlatform) {
11163 _registerComponent(new Component("auth" /* AUTH */, function (container, _a) {
11164 var deps = _a.options;
11165 var app = container.getProvider('app').getImmediate();
11166 var heartbeatServiceProvider = container.getProvider('heartbeat');
11167 var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
11168 return (function (app, heartbeatServiceProvider) {
11169 _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* INVALID_API_KEY */, { appName: app.name });
11170 // Auth domain is optional if IdP sign in isn't being used
11171 _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* ARGUMENT_ERROR */, {
11172 appName: app.name
11173 });
11174 var config = {
11175 apiKey: apiKey,
11176 authDomain: authDomain,
11177 clientPlatform: clientPlatform,
11178 apiHost: "identitytoolkit.googleapis.com" /* API_HOST */,
11179 tokenApiHost: "securetoken.googleapis.com" /* TOKEN_API_HOST */,
11180 apiScheme: "https" /* API_SCHEME */,
11181 sdkClientVersion: _getClientVersion(clientPlatform)
11182 };
11183 var authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
11184 _initializeAuthInstance(authInstance, deps);
11185 return authInstance;
11186 })(app, heartbeatServiceProvider);
11187 }, "PUBLIC" /* PUBLIC */)
11188 /**
11189 * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
11190 * For why we do this, See go/firebase-next-auth-init
11191 */
11192 .setInstantiationMode("EXPLICIT" /* EXPLICIT */)
11193 /**
11194 * Because all firebase products that depend on auth depend on auth-internal directly,
11195 * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
11196 */
11197 .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
11198 var authInternalProvider = container.getProvider("auth-internal" /* AUTH_INTERNAL */);
11199 authInternalProvider.initialize();
11200 }));
11201 _registerComponent(new Component("auth-internal" /* AUTH_INTERNAL */, function (container) {
11202 var auth = _castAuth(container.getProvider("auth" /* AUTH */).getImmediate());
11203 return (function (auth) { return new AuthInterop(auth); })(auth);
11204 }, "PRIVATE" /* PRIVATE */).setInstantiationMode("EXPLICIT" /* EXPLICIT */));
11205 registerVersion(name, version, getVersionForPlatform(clientPlatform));
11206 // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
11207 registerVersion(name, version, 'esm5');
11208}
11209
11210/**
11211 * @license
11212 * Copyright 2021 Google LLC
11213 *
11214 * Licensed under the Apache License, Version 2.0 (the "License");
11215 * you may not use this file except in compliance with the License.
11216 * You may obtain a copy of the License at
11217 *
11218 * http://www.apache.org/licenses/LICENSE-2.0
11219 *
11220 * Unless required by applicable law or agreed to in writing, software
11221 * distributed under the License is distributed on an "AS IS" BASIS,
11222 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11223 * See the License for the specific language governing permissions and
11224 * limitations under the License.
11225 */
11226/**
11227 * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
11228 * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
11229 *
11230 * @param app - The Firebase App.
11231 *
11232 * @public
11233 */
11234function getAuth(app) {
11235 if (app === void 0) { app = getApp(); }
11236 var provider = _getProvider(app, 'auth');
11237 if (provider.isInitialized()) {
11238 return provider.getImmediate();
11239 }
11240 return initializeAuth(app, {
11241 popupRedirectResolver: browserPopupRedirectResolver,
11242 persistence: [
11243 indexedDBLocalPersistence,
11244 browserLocalPersistence,
11245 browserSessionPersistence
11246 ]
11247 });
11248}
11249registerAuth("Browser" /* BROWSER */);
11250
11251export { signInWithCustomToken as $, ActionCodeOperation as A, debugErrorMap as B, prodErrorMap as C, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as D, initializeAuth as E, FactorId as F, connectAuthEmulator as G, AuthCredential as H, EmailAuthCredential as I, OAuthCredential as J, PhoneAuthCredential as K, inMemoryPersistence as L, EmailAuthProvider as M, FacebookAuthProvider as N, OperationType as O, PhoneAuthProvider as P, GoogleAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, GithubAuthProvider as T, OAuthProvider as U, SAMLAuthProvider as V, TwitterAuthProvider as W, signInAnonymously as X, signInWithCredential as Y, linkWithCredential as Z, reauthenticateWithCredential as _, browserSessionPersistence as a, sendPasswordResetEmail as a0, confirmPasswordReset as a1, applyActionCode as a2, checkActionCode as a3, verifyPasswordResetCode as a4, createUserWithEmailAndPassword as a5, signInWithEmailAndPassword as a6, sendSignInLinkToEmail as a7, isSignInWithEmailLink as a8, signInWithEmailLink as a9, _persistenceKeyName as aA, _clearRedirectOutcomes as aB, _getRedirectResult as aC, _overrideRedirectResult as aD, _castAuth as aE, UserImpl as aF, AuthImpl as aG, _getClientVersion as aH, _generateEventId as aI, AuthPopup as aJ, FetchProvider as aK, SAMLAuthCredential as aL, fetchSignInMethodsForEmail as aa, sendEmailVerification as ab, verifyBeforeUpdateEmail as ac, ActionCodeURL as ad, parseActionCodeURL as ae, updateProfile as af, updateEmail as ag, updatePassword as ah, getIdToken as ai, getIdTokenResult as aj, unlink as ak, getAdditionalUserInfo as al, reload as am, getMultiFactorResolver as an, multiFactor as ao, _isAndroid as ap, _isIOS7Or8 as aq, _isIOS as ar, _fail as as, _getRedirectUrl as at, debugAssert as au, _getProjectConfig as av, _createError as aw, _assert as ax, AuthEventManager as ay, _getInstance as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, getAuth as n, ProviderId as o, setPersistence as p, onIdTokenChanged as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, beforeAuthStateChanged as t, updatePhoneNumber as u, onAuthStateChanged as v, useDeviceLanguage as w, updateCurrentUser as x, signOut as y, deleteUser as z };
11252//# sourceMappingURL=index-0e5111f4.js.map