{"version":3,"sources":["../../../src/model/enum_maps.ts","../../../src/core/errors.ts","../../../src/core/util/log.ts","../../../src/core/util/assert.ts","../../../src/core/util/instantiator.ts","../../../src/core/auth/initialize.ts","../../../src/core/util/location.ts","../../../src/core/util/navigator.ts","../../../src/core/util/delay.ts","../../../src/core/util/emulator.ts","../../../src/core/util/fetch_provider.ts","../../../src/api/errors.ts","../../../src/api/index.ts","../../../src/api/account_management/account.ts","../../../src/core/util/time.ts","../../../src/core/user/id_token_result.ts","../../../src/core/user/invalidation.ts","../../../src/core/user/proactive_refresh.ts","../../../src/core/user/user_metadata.ts","../../../src/core/user/reload.ts","../../../src/api/authentication/token.ts","../../../src/core/user/token_manager.ts","../../../src/core/user/user_impl.ts","../../../src/core/persistence/in_memory.ts","../../../src/core/persistence/persistence_user_manager.ts","../../../src/core/util/browser.ts","../../../src/core/util/version.ts","../../../src/core/auth/middleware.ts","../../../src/core/auth/auth_impl.ts","../../../src/core/auth/emulator.ts","../../../src/core/credentials/auth_credential.ts","../../../src/api/account_management/email_and_password.ts","../../../src/api/authentication/email_and_password.ts","../../../src/api/authentication/email_link.ts","../../../src/core/credentials/email.ts","../../../src/api/authentication/idp.ts","../../../src/core/credentials/oauth.ts","../../../src/api/authentication/sms.ts","../../../src/core/credentials/phone.ts","../../../src/core/action_code_url.ts","../../../src/core/providers/email.ts","../../../src/core/providers/federated.ts","../../../src/core/providers/oauth.ts","../../../src/core/providers/facebook.ts","../../../src/core/providers/google.ts","../../../src/core/providers/github.ts","../../../src/core/credentials/saml.ts","../../../src/core/providers/saml.ts","../../../src/core/providers/twitter.ts","../../../src/api/authentication/sign_up.ts","../../../src/core/user/user_credential_impl.ts","../../../src/core/strategies/anonymous.ts","../../../src/mfa/mfa_error.ts","../../../src/core/util/providers.ts","../../../src/core/user/link_unlink.ts","../../../src/core/user/reauthenticate.ts","../../../src/core/strategies/credential.ts","../../../src/api/authentication/custom_token.ts","../../../src/core/strategies/custom_token.ts","../../../src/mfa/mfa_info.ts","../../../src/core/strategies/action_code_settings.ts","../../../src/core/strategies/email_and_password.ts","../../../src/core/strategies/email_link.ts","../../../src/api/authentication/create_auth_uri.ts","../../../src/core/strategies/email.ts","../../../src/api/account_management/profile.ts","../../../src/core/user/account_info.ts","../../../src/core/user/additional_user_info.ts","../../../src/core/index.ts","../../../src/mfa/mfa_session.ts","../../../src/mfa/mfa_resolver.ts","../../../src/api/account_management/mfa.ts","../../../src/mfa/mfa_user.ts","../../../src/core/persistence/index.ts","../../../src/platform_browser/persistence/browser.ts","../../../src/platform_browser/persistence/local_storage.ts","../../../src/platform_browser/persistence/session_storage.ts","../../../src/platform_browser/messagechannel/promise.ts","../../../src/platform_browser/messagechannel/receiver.ts","../../../src/core/util/event_id.ts","../../../src/platform_browser/messagechannel/sender.ts","../../../src/platform_browser/auth_window.ts","../../../src/platform_browser/util/worker.ts","../../../src/platform_browser/persistence/indexed_db.ts","../../../src/api/authentication/mfa.ts","../../../src/api/authentication/recaptcha.ts","../../../src/platform_browser/load_js.ts","../../../src/platform_browser/recaptcha/recaptcha_mock.ts","../../../src/platform_browser/recaptcha/recaptcha_loader.ts","../../../src/platform_browser/recaptcha/recaptcha_verifier.ts","../../../src/platform_browser/strategies/phone.ts","../../../src/platform_browser/providers/phone.ts","../../../src/core/util/resolver.ts","../../../src/core/strategies/idp.ts","../../../src/core/strategies/abstract_popup_redirect_operation.ts","../../../src/platform_browser/strategies/popup.ts","../../../src/core/strategies/redirect.ts","../../../src/platform_browser/strategies/redirect.ts","../../../src/core/auth/auth_event_manager.ts","../../../src/api/project_config/get_project_config.ts","../../../src/core/util/validate_origin.ts","../../../src/platform_browser/iframe/gapi.ts","../../../src/platform_browser/iframe/iframe.ts","../../../src/platform_browser/util/popup.ts","../../../src/core/util/handler.ts","../../../src/platform_browser/popup_redirect.ts","../../../src/mfa/mfa_assertion.ts","../../../src/platform_browser/mfa/assertions/phone.ts","../../../src/core/auth/firebase_internal.ts","../../../src/core/auth/register.ts","../../../src/platform_browser/index.ts"],"names":["applyActionCode","sendEmailVerification","sendPasswordResetEmail","sendSignInLinkToEmail","signInWithEmailLink","IDP_REQUEST_URI","signInWithPhoneNumber","linkWithPhoneNumber","_link","signInWithCustomToken","getIdTokenResponse","authentication.sendPasswordResetEmail","account.resetPassword","account.applyActionCode","api.sendSignInLinkToEmail","api.sendEmailVerification","api.verifyAndChangeEmail","updateProfile","apiUpdateProfile","apiUpdateEmailPassword","_POLLING_INTERVAL_MS","jsHelpers._generateCallbackName","jsHelpers._loadJS","_linkUser","js._generateCallbackName","js._loadJS","gapiLoader._loadGapi"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;;AAEH;;;;AAIG;;AACU,YAAQ,GAAG;;EAEtB,KAAK,EAAE;AAFe,CAAX;AAKb;;;;AAIG;;AACU,cAAU,GAAG;;EAExB,QAAQ,EAAE,cAFc;;;EAIxB,MAAM,EAAE,YAJgB;;;EAMxB,MAAM,EAAE,YANgB;;;EAQxB,QAAQ,EAAE,UARc;;;EAUxB,KAAK,EAAE,OAViB;;;EAYxB,OAAO,EAAE;AAZe,CAAb;AAeb;;;;AAIG;;AACU,gBAAY,GAAG;;EAE1B,UAAU,EAAE,WAFc;;;EAI1B,cAAc,EAAE,UAJU;;;EAM1B,QAAQ,EAAE,cANgB;;;EAQ1B,MAAM,EAAE,YARkB;;;EAU1B,MAAM,EAAE,YAVkB;;;EAY1B,KAAK,EAAE,OAZmB;;;EAc1B,OAAO,EAAE;AAdiB,CAAf;AAiBb;;;;AAIG;;AACU,iBAAa,GAAG;;EAE3B,IAAI,EAAE,MAFqB;;;EAI3B,cAAc,EAAE,gBAJW;;;EAM3B,OAAO,EAAE;AANkB,CAAhB;AASb;;;;AAIG;;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D,CAPH,EASC;EAAA;EATD,EASE,oBATF,CASsB;EAAA;EATtB,CADgB,CAAlB;;EAaA,8EAAe,CAAC,IAAD,EAAO,OAAP,EAAgB,qBAAqB,CAAC,cAAD,CAArC,CAAf,CApEyD,C;;EAsEzD,8EAAe,CAAC,IAAD,EAAO,OAAP,EAAgB,SAAhB,CAAf;AACF;AChIA;;;;;;;;;;;;;;;AAeG;;AAaH;;;;;;;AAOG;;;AACa,mBAAmC;EAAA,IAA3B,GAA2B,uEAAR,qEAAM,EAAE;;EACjD,IAAM,QAAQ,GAAG,2EAAY,CAAC,GAAD,EAAM,MAAN,CAA7B;;EAEA,IAAI,QAAQ,CAAC,aAAT,EAAJ,EAA8B;IAC5B,OAAO,QAAQ,CAAC,YAAT,EAAP;EACD;;EAED,OAAO,cAAc,CAAC,GAAD,EAAM;IACzB,qBAAqB,EAAE,4BADE;IAEzB,WAAW,EAAE,CACX,yBADW,EAEX,uBAFW,EAGX,yBAHW;EAFY,CAAN,CAArB;AAQD;;AAED,YAAY;AAAA;AAAA,CAAZ","file":"static/js/vendors~main~6515efb7.3a703ffd.chunk.js","sourcesContent":["/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nexport const FactorId = {\n /** Phone as second factor */\n PHONE: 'phone'\n} as const;\n\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nexport const ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nexport const SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nexport const OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n} as const;\n\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nexport const ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n * \n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_IDP_RESPONSE = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized'\n}\n\nfunction _debugErrorMap(): ErrorMap {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_IDP_RESPONSE]:\n 'The supplied auth credential is malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]: \"Login blocked by user-provided method: {$originalMessage}\",\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap;\n}\n\nfunction _prodErrorMap(): ErrorMap {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: { appName?: AppName, originalMessage?: string };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName = Omit;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): never;\nexport function _fail(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): FirebaseError;\nexport function _createError(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(auth: Auth, code: AuthErrorCode, message: string): FirebaseError {\n const errorMap = {...(prodErrorMap as ErrorMapRetriever)(), [code]: message};\n const factory = new ErrorFactory(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name,\n });\n}\n\nexport function _assertInstanceOf(auth: Auth, object: object, instance: unknown): void {\n const constructorInstance = (instance as { new (...args: unknown[]): unknown });\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(auth, AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`);\n }\n}\n\nfunction createErrorInternal(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams)\n );\n}\n\nexport function _assert(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit,\n ...expected: Array\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\n }\n}\n\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator {\n new (): T;\n}\n\nconst instanceCache: Map = new Map();\n\nexport function _getInstance(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_IDP_RESPONSE,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport { _createError, _errorWithCustomMessage, _fail } from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_PHONE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_PHONE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_PHONE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_PHONE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling(\n auth: Auth,\n customErrorMap: Partial>,\n fetchFn: () => Promise\n): Promise {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout(auth);\n const response: Response = await Promise.race>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n ((serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown) as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED);\n }\n}\n\nexport async function _performSignInRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n const serverResponse = (await _performApiRequest(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nclass NetworkTimeout {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(_createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError('Caught error parsing JWT payload as JSON', e);\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated(\n user: UserInternal,\n promise: Promise,\n bypassAuthState = false\n): Promise {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (e.code === `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nfunction extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n HttpMethod,\n HttpHeader\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum Endpoint {\n TOKEN = '/v1/token'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise {\n const response = await _performFetchWithErrorHandling(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise {\n _assert(\n !this.accessToken || this.refreshToken,\n auth,\n AuthErrorCode.TOKEN_EXPIRED\n );\n\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\n\nimport {\n APIUserInfo,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert } from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n return new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n }\n\n _onReload(callback: NextFn): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise {\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record = {};\n\n async _isAvailable(): Promise {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n this.storage[key] = value;\n }\n\n async _get(key: string): Promise {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise {\n const blob = await this.persistence._get(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return /iphone|ipad|ipod/i.test(ua);\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry =\n (user: User | null): Promise => new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) { /* swallow error */}\n }\n\n throw this.auth._errorFactory.create(\n AuthErrorCode.LOGIN_BLOCKED, { originalMessage: (e as Error)?.message });\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseService, FirebaseApp } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport { _assert } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport { AuthMiddlewareQueue } from './middleware';\n\ninterface AsyncAction {\n (): Promise;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription(this);\n private idTokenSubscription = new Subscription(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory =\n _DEFAULT_AUTH_ERROR_FACTORY;\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) { /* Ignore the error */ }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch(e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () => Promise.reject(e));\n }\n }\n \n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (e.code !== `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise {\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(user: User | null, skipBeforeStateCallbacks: boolean = false): Promise {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise {\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise {\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void,\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => { });\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => { };\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => cb(this.currentUser));\n\n if (typeof nextOrObserver === 'function') {\n return subscription.addObserver(nextOrObserver, error, completed);\n } else {\n return subscription.addObserver(nextOrObserver);\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise> {\n // Additional headers on every request\n const headers: Record = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion,\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider.getImmediate({\n optional: true,\n })?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n return headers;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription {\n private observer: Observer | null = null;\n readonly addObserver: Subscribe = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) { }\n\n get next(): NextFn {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n ) {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { updateEmailPassword } from '../../api/account_management/email_and_password';\nimport { signInWithPassword } from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n return signInWithPassword(auth, {\n returnSecureToken: true,\n email: this._email,\n password: this._password\n });\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n return updateEmailPassword(auth, {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password\n });\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return this._getIdTokenResponse(auth);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n \n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({...params, nonce: params.rawNonce});\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\n/**\n * @public\n */\nexport class SAMLAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n providerId: string,\n private readonly pendingToken: string\n ) {\n super(providerId, providerId);\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): SAMLAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const {\n providerId,\n signInMethod,\n pendingToken\n }: Record = obj;\n if (\n !providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod\n ) {\n return null;\n }\n\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId: string, pendingToken: string): SAMLAuthCredential {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredential } from '../../model/public_types';\nimport { UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { SAMLAuthCredential } from '../credentials/saml';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { FederatedAuthProvider } from './federated';\n\nconst SAML_PROVIDER_PREFIX = 'saml.';\n\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nexport class SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId: string) {\n _assert(\n providerId.startsWith(SAML_PROVIDER_PREFIX),\n AuthErrorCode.ARGUMENT_ERROR\n );\n super(providerId);\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: string | object): AuthCredential {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, AuthErrorCode.ARGUMENT_ERROR);\n return credential;\n }\n\n private static samlCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): SAMLAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { pendingToken, providerId } = tokenResponse as SignInWithIdpResponse;\n\n if (!pendingToken || !providerId) {\n return null;\n }\n\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { UserInternal } from '../../model/user';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport async function signInAnonymously(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser as UserInternal,\n providerId: null,\n operationType: OperationType.SIGN_IN\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response,\n true\n );\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType,\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ProviderAssociatedObject {\n providerId?: string;\n}\n\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nexport function providerDataAsNames(\n providerData: T[]\n): Set {\n return new Set(\n providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid) as string[]\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const { auth } = user;\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if (e?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithCustomTokenRequest {\n token: string;\n returnSecureToken: boolean;\n tenantId?: string;\n}\n\nexport interface SignInWithCustomTokenResponse extends IdTokenResponse {}\n\nexport async function signInWithCustomToken(\n auth: Auth,\n request: SignInWithCustomTokenRequest\n): Promise {\n return _performSignInRequest<\n SignInWithCustomTokenRequest,\n SignInWithCustomTokenResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\n\nimport { signInWithCustomToken as getIdTokenResponse } from '../../api/authentication/custom_token';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nexport async function signInWithCustomToken(\n auth: Auth,\n customToken: string\n): Promise {\n const authInternal = _castAuth(auth);\n const response: IdTokenResponse = await getIdTokenResponse(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(cred.user);\n return cred;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FactorId, MultiFactorInfo, PhoneMultiFactorInfo } from '../model/public_types';\nimport {\n PhoneMfaEnrollment,\n MfaEnrollment\n} from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _fail } from '../core/util/assert';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorInfoImpl implements MultiFactorInfo {\n readonly uid: string;\n readonly displayName?: string | null;\n readonly enrollmentTime: string;\n\n protected constructor(readonly factorId: FactorId, response: MfaEnrollment) {\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n\n static _fromServerResponse(\n auth: AuthInternal,\n enrollment: MfaEnrollment\n ): MultiFactorInfoImpl {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n}\n\nexport class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl implements PhoneMultiFactorInfo {\n readonly phoneNumber: string;\n\n private constructor(response: PhoneMfaEnrollment) {\n super(FactorId.PHONE, response);\n this.phoneNumber = response.phoneInfo;\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): PhoneMultiFactorInfoImpl {\n return new PhoneMultiFactorInfoImpl(enrollment);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeSettings, Auth } from '../../model/public_types';\n\nimport { GetOobCodeRequest } from '../../api/authentication/email_and_password';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\nexport function _setActionCodeSettingsOnRequest(\n auth: Auth,\n request: GetOobCodeRequest,\n actionCodeSettings: ActionCodeSettings\n): void {\n _assert(\n actionCodeSettings.url?.length > 0,\n auth,\n AuthErrorCode.INVALID_CONTINUE_URI\n );\n _assert(\n typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0,\n auth,\n AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN\n );\n\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n\n if (actionCodeSettings.iOS) {\n _assert(\n actionCodeSettings.iOS.bundleId.length > 0,\n auth,\n AuthErrorCode.MISSING_IOS_BUNDLE_ID\n );\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n\n if (actionCodeSettings.android) {\n _assert(\n actionCodeSettings.android.packageName.length > 0,\n auth,\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME\n );\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _assert } from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Sends a password reset email to the given email address.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise {\n const authModular = getModularInstance(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\n }\n\n await authentication.sendPasswordResetEmail(authModular, request);\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise {\n await account.resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n const authInternal = _castAuth(auth);\n const response = await signUp(authInternal, {\n returnSecureToken: true,\n email,\n password\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as api from '../../api/authentication/email_and_password';\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthProvider } from '../providers/email';\nimport { _getCurrentUrl } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n email: string,\n actionCodeSettings: ActionCodeSettings\n): Promise {\n const authModular = getModularInstance(auth);\n const request: api.EmailSignInRequest = {\n requestType: ActionCodeOperation.EMAIL_SIGNIN,\n email\n };\n _assert(\n actionCodeSettings.handleCodeInApp,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\n }\n\n await api.sendSignInLinkToEmail(authModular, request);\n}\n\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport function isSignInWithEmailLink(auth: Auth, emailLink: string): boolean {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === ActionCodeOperation.EMAIL_SIGNIN;\n}\n\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport async function signInWithEmailLink(\n auth: Auth,\n email: string,\n emailLink?: string\n): Promise {\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(\n email,\n emailLink || _getCurrentUrl()\n );\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(\n credential._tenantId === (authModular.tenantId || null),\n authModular,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n return signInWithCredential(authModular, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface CreateAuthUriRequest {\n identifier: string;\n continueUri: string;\n tenantId?: string;\n}\n\nexport interface CreateAuthUriResponse {\n signinMethods: string[];\n}\n\nexport async function createAuthUri(\n auth: Auth,\n request: CreateAuthUriRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.CREATE_AUTH_URI,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n User\n} from '../../model/public_types';\n\nimport {\n createAuthUri,\n CreateAuthUriRequest\n} from '../../api/authentication/create_auth_uri';\nimport * as api from '../../api/authentication/email_and_password';\nimport { UserInternal } from '../../model/user';\nimport { _getCurrentUrl, _isHttpOrHttps } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Gets the list of possible sign in methods for the given email address.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * @public\n */\nexport async function fetchSignInMethodsForEmail(\n auth: Auth,\n email: string\n): Promise {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request: CreateAuthUriRequest = {\n identifier: email,\n continueUri\n };\n\n const { signinMethods } = await createAuthUri(\n getModularInstance(auth),\n request\n );\n\n return signinMethods || [];\n}\n\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendEmailVerification(\n user: User,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_EMAIL,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.sendEmailVerification(userInternal.auth, request);\n\n if (email !== user.email) {\n await user.reload();\n }\n}\n\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function verifyBeforeUpdateEmail(\n user: User,\n newEmail: string,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyAndChangeEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.verifyAndChangeEmail(userInternal.auth, request);\n\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface UpdateProfileRequest {\n idToken: string;\n displayName?: string | null;\n photoUrl?: string | null;\n returnSecureToken: boolean;\n}\n\nexport interface UpdateProfileResponse extends IdTokenResponse {\n displayName?: string | null;\n photoUrl?: string | null;\n}\n\nexport async function updateProfile(\n auth: Auth,\n request: UpdateProfileRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport {\n updateEmailPassword as apiUpdateEmailPassword,\n UpdateEmailPasswordRequest\n} from '../../api/account_management/email_and_password';\nimport { updateProfile as apiUpdateProfile } from '../../api/account_management/profile';\nimport { UserInternal } from '../../model/user';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nexport async function updateProfile(\n user: User,\n {\n displayName,\n photoURL: photoUrl\n }: { displayName?: string | null; photoURL?: string | null }\n): Promise {\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(\n userInternal,\n apiUpdateProfile(userInternal.auth, profileRequest)\n );\n\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(\n ({ providerId }) => providerId === ProviderId.PASSWORD\n );\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n\n await userInternal._updateTokensIfNecessary(response);\n}\n\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * @public\n */\nexport function updateEmail(user: User, newEmail: string): Promise {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n newEmail,\n null\n );\n}\n\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport function updatePassword(user: User, newPassword: string): Promise {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n null,\n newPassword\n );\n}\n\nasync function updateEmailOrPassword(\n user: UserInternal,\n email: string | null,\n password: string | null\n): Promise {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request: UpdateEmailPasswordRequest = {\n idToken,\n returnSecureToken: true\n };\n\n if (email) {\n request.email = email;\n }\n\n if (password) {\n request.password = password;\n }\n\n const response = await _logoutIfInvalidated(\n user,\n apiUpdateEmailPassword(auth, request)\n );\n await user._updateTokensIfNecessary(response, /* reload */ true);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AdditionalUserInfo, UserCredential } from '../../model/public_types';\nimport { IdTokenResponse, IdTokenResponseKind } from '../../model/id_token';\nimport { _parseToken } from './id_token_result';\nimport { UserCredentialInternal } from '../../model/user';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nexport function _fromIdTokenResponse(\n idTokenResponse?: IdTokenResponse\n): AdditionalUserInfo | null {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser =\n idTokenResponse.isNewUser ||\n idTokenResponse.kind === IdTokenResponseKind.SignupNewUser;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.[\n 'sign_in_provider'\n ];\n if (signInProvider) {\n const filteredProviderId =\n signInProvider !== ProviderId.ANONYMOUS &&\n signInProvider !== ProviderId.CUSTOM\n ? (signInProvider as ProviderId)\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case ProviderId.FACEBOOK:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GITHUB:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GOOGLE:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case ProviderId.TWITTER:\n return new TwitterAdditionalUserInfo(\n isNewUser,\n profile,\n idTokenResponse.screenName || null\n );\n case ProviderId.CUSTOM:\n case ProviderId.ANONYMOUS:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\n\nclass GenericAdditionalUserInfo implements AdditionalUserInfo {\n constructor(\n readonly isNewUser: boolean,\n readonly providerId: ProviderId | string | null,\n readonly profile: Record = {}\n ) {}\n}\n\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(\n isNewUser: boolean,\n providerId: ProviderId,\n profile: Record,\n readonly username: string | null\n ) {\n super(isNewUser, providerId, profile);\n }\n}\n\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.FACEBOOK, profile);\n }\n}\n\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser: boolean, profile: Record) {\n super(\n isNewUser,\n ProviderId.GITHUB,\n profile,\n typeof profile?.login === 'string' ? profile?.login : null\n );\n }\n}\n\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.GOOGLE, profile);\n }\n}\n\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(\n isNewUser: boolean,\n profile: Record,\n screenName: string | null\n ) {\n super(isNewUser, ProviderId.TWITTER, profile, screenName);\n }\n}\n\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nexport function getAdditionalUserInfo(\n userCredential: UserCredential\n): AdditionalUserInfo | null {\n const { user, _tokenResponse } = userCredential as UserCredentialInternal;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n\n return _fromIdTokenResponse(_tokenResponse);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\nimport {\n Auth,\n NextOrObserver,\n Persistence,\n User,\n CompleteFn,\n ErrorFn,\n Unsubscribe\n} from '../model/public_types';\n\nexport {\n debugErrorMap,\n prodErrorMap,\n AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes\n} from './errors';\n\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nexport function setPersistence(\n auth: Auth,\n persistence: Persistence\n): Promise {\n return getModularInstance(auth).setPersistence(persistence);\n}\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onIdTokenChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onIdTokenChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\n export function beforeAuthStateChanged(\n auth: Auth,\n callback: (user: User|null) => void | Promise,\n onAbort?: () => void,\n): Unsubscribe {\n return getModularInstance(auth).beforeAuthStateChanged(\n callback,\n onAbort\n );\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onAuthStateChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onAuthStateChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function useDeviceLanguage(auth: Auth): void {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nexport function updateCurrentUser(\n auth: Auth,\n user: User | null\n): Promise {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function signOut(auth: Auth): Promise {\n return getModularInstance(auth).signOut();\n}\n\nexport { initializeAuth } from './auth/initialize';\nexport { connectAuthEmulator } from './auth/emulator';\n\n// credentials\nexport { AuthCredential } from './credentials';\nexport { EmailAuthCredential } from './credentials/email';\nexport { OAuthCredential } from './credentials/oauth';\nexport { PhoneAuthCredential } from './credentials/phone';\n\n// persistence\nexport { inMemoryPersistence } from './persistence/in_memory';\n\n// providers\nexport { EmailAuthProvider } from './providers/email';\nexport { FacebookAuthProvider } from './providers/facebook';\nexport { CustomParameters } from './providers/federated';\nexport { GoogleAuthProvider } from './providers/google';\nexport { GithubAuthProvider } from './providers/github';\nexport { OAuthProvider, OAuthCredentialOptions } from './providers/oauth';\nexport { SAMLAuthProvider } from './providers/saml';\nexport { TwitterAuthProvider } from './providers/twitter';\n\n// strategies\nexport { signInAnonymously } from './strategies/anonymous';\nexport {\n signInWithCredential,\n linkWithCredential,\n reauthenticateWithCredential\n} from './strategies/credential';\nexport { signInWithCustomToken } from './strategies/custom_token';\nexport {\n sendPasswordResetEmail,\n confirmPasswordReset,\n applyActionCode,\n checkActionCode,\n verifyPasswordResetCode,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword\n} from './strategies/email_and_password';\nexport {\n sendSignInLinkToEmail,\n isSignInWithEmailLink,\n signInWithEmailLink\n} from './strategies/email_link';\nexport {\n fetchSignInMethodsForEmail,\n sendEmailVerification,\n verifyBeforeUpdateEmail\n} from './strategies/email';\n\n// core\nexport { ActionCodeURL, parseActionCodeURL } from './action_code_url';\n\n// user\nexport {\n updateProfile,\n updateEmail,\n updatePassword\n} from './user/account_info';\nexport { getIdToken, getIdTokenResult } from './user/id_token_result';\nexport { unlink } from './user/link_unlink';\nexport { getAdditionalUserInfo } from './user/additional_user_info';\n\n// Non-optional user methods.\nexport { reload } from './user/reload';\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function deleteUser(user: User): Promise {\n return getModularInstance(user).delete();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { MultiFactorSession } from '../model/public_types';\n\nexport const enum MultiFactorSessionType {\n ENROLL = 'enroll',\n SIGN_IN = 'signin'\n}\n\ninterface SerializedMultiFactorSession {\n multiFactorSession: {\n idToken?: string;\n pendingCredential?: string;\n };\n}\n\nexport class MultiFactorSessionImpl implements MultiFactorSession {\n private constructor(\n readonly type: MultiFactorSessionType,\n readonly credential: string\n ) {}\n\n static _fromIdtoken(idToken: string): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(MultiFactorSessionType.ENROLL, idToken);\n }\n\n static _fromMfaPendingCredential(\n mfaPendingCredential: string\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.SIGN_IN,\n mfaPendingCredential\n );\n }\n\n toJSON(): SerializedMultiFactorSession {\n const key =\n this.type === MultiFactorSessionType.ENROLL\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n\n static fromJSON(\n obj: Partial\n ): MultiFactorSessionImpl | null {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(\n obj.multiFactorSession.pendingCredential\n );\n } else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(\n obj.multiFactorSession.idToken\n );\n }\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n MultiFactorResolver,\n UserCredential,\n MultiFactorError\n} from '../model/public_types';\n\nimport { _castAuth } from '../core/auth/auth_impl';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserCredentialImpl } from '../core/user/user_credential_impl';\nimport { _assert, _fail } from '../core/util/assert';\nimport { UserCredentialInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorError as MultiFactorErrorInternal } from './mfa_error';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../model/enums';\n\nexport class MultiFactorResolverImpl implements MultiFactorResolver {\n private constructor(\n readonly session: MultiFactorSessionImpl,\n readonly hints: MultiFactorInfoImpl[],\n private readonly signInResolver: (\n assertion: MultiFactorAssertionImpl\n ) => Promise\n ) {}\n\n /** @internal */\n static _fromError(\n authExtern: Auth,\n error: MultiFactorErrorInternal\n ): MultiFactorResolverImpl {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(auth, enrollment)\n );\n\n _assert(\n serverResponse.mfaPendingCredential,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(\n serverResponse.mfaPendingCredential\n );\n\n return new MultiFactorResolverImpl(\n session,\n hints,\n async (\n assertion: MultiFactorAssertionImpl\n ): Promise => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case OperationType.SIGN_IN:\n const userCredential =\n await UserCredentialImpl._fromIdTokenResponse(\n auth,\n error.operationType,\n idTokenResponse\n );\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case OperationType.REAUTHENTICATE:\n _assert(error.user, auth, AuthErrorCode.INTERNAL_ERROR);\n return UserCredentialImpl._forOperation(\n error.user,\n error.operationType,\n idTokenResponse\n );\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n );\n }\n\n async resolveSignIn(\n assertionExtern: MultiFactorAssertionImpl\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n return this.signInResolver(assertion);\n }\n}\n\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nexport function getMultiFactorResolver(\n auth: Auth,\n error: MultiFactorError\n): MultiFactorResolver {\n const authModular = getModularInstance(auth);\n const errorInternal = error as MultiFactorErrorInternal;\n _assert(error.customData.operationType, authModular, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n errorInternal.customData._serverResponse?.mfaPendingCredential,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _addTidIfNecessary, _performApiRequest } from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment is supported\n */\nexport type MfaEnrollment = PhoneMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(auth, HttpMethod.POST, Endpoint.START_PHONE_MFA_ENROLLMENT, _addTidIfNecessary(auth, request));\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(auth, HttpMethod.POST, Endpoint.FINALIZE_PHONE_MFA_ENROLLMENT, _addTidIfNecessary(auth, request));\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise {\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken());\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n try {\n await this.user.reload();\n } catch (e) {\n if (e.code !== `auth/${AuthErrorCode.TOKEN_EXPIRED}`) {\n throw e;\n }\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record;\n\nexport interface Instantiator {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise;\n _set(key: string, value: PersistenceValue): Promise;\n _get(key: string): Promise;\n _remove(key: string): Promise;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get(key: string): Promise {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (event: StorageEvent, poll?: boolean): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get(key: string): Promise {\n const value = await super._get(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult =\n | PromiseFulfilledResult\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled(\n promises: Array>\n): Promise>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\n }\n })\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise {\n const messageEvent = event as MessageEvent>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set> | undefined = this.handlersMap[\n eventType\n ];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe(\n eventType: _EventType,\n eventHandler: ReceiverHandler\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe(\n eventType: _EventType,\n eventHandler?: ReceiverHandler\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Recaptcha } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return (window as unknown) as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? ((self as unknown) as ServiceWorker) : null;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\n *\n */\nclass DBPromise {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise {\n return new Promise((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise {\n const objectStore = getObjectStore(db, true);\n return new DBPromise(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise(request).toPromise();\n}\n\nexport function _openDatabase(): Promise {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries(op: (db: IDBDatabase) => Promise): Promise {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise): Promise {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get(key: string): Promise {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod, _addTidIfNecessary } from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(auth, HttpMethod.POST, Endpoint.START_PHONE_MFA_SIGN_IN, _addTidIfNecessary(auth, request));\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest,\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(auth, HttpMethod.POST, Endpoint.FINALIZE_PHONE_MFA_SIGN_IN, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise {\n return (\n (\n await _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\nimport { _createError } from '../core/util/assert';\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\nexport function _loadJS(url: string): Promise {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport { RecaptchaParameters } from '../../model/public_types';\nimport { Recaptcha } from './recaptcha';\n\nexport const _SOLVE_TIME_MS = 500;\nexport const _EXPIRATION_TIME_MS = 60_000;\nexport const _WIDGET_ID_START = 1_000_000_000_000;\n\nexport interface Widget {\n getResponse: () => string | null;\n delete: () => void;\n execute: () => void;\n}\n\nexport class MockReCaptcha implements Recaptcha {\n private counter = _WIDGET_ID_START;\n _widgets = new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n render(\n container: string | HTMLElement,\n parameters?: RecaptchaParameters\n ): number {\n const id = this.counter;\n this._widgets.set(\n id,\n new MockWidget(container, this.auth.name, parameters || {})\n );\n this.counter++;\n return id;\n }\n\n reset(optWidgetId?: number): void {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n\n getResponse(optWidgetId?: number): string {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n\n async execute(optWidgetId?: number | string): Promise {\n const id: number = (optWidgetId as number) || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\n\nexport class MockWidget {\n private readonly container: HTMLElement;\n private readonly isVisible: boolean;\n private timerId: number | null = null;\n private deleted = false;\n private responseToken: string | null = null;\n private readonly clickHandler = (): void => {\n this.execute();\n };\n\n constructor(\n containerOrId: string | HTMLElement,\n appName: string,\n private readonly params: RecaptchaParameters\n ) {\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, AuthErrorCode.ARGUMENT_ERROR, { appName });\n\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n } else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n\n getResponse(): string | null {\n this.checkIfDeleted();\n return this.responseToken;\n }\n\n delete(): void {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n\n execute(): void {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n } catch (e) {}\n }\n\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n } catch (e) {}\n }\n\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n\n private checkIfDeleted(): void {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\n\nfunction generateRandomAlphaNumericString(len: number): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(\n allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))\n );\n }\n return chars.join('');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha;\n\n load(auth: AuthInternal, hl = ''): Promise {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl)) {\n return Promise.resolve(_window().grecaptcha!);\n }\n return new Promise((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha;\n\n if (!recaptcha) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${RECAPTCHA_BASE}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set();\n private renderPromise: Promise | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @remarks\n * If none is provided, the default Firebase {@link Auth} instance is used. A Firebase {@link Auth} instance\n * must be initialized with an API key, otherwise an error will be thrown.\n */\n constructor(\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n },\n authExtern: Auth\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise {\n let resolver: (() => void) | null = null;\n return new Promise(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise {\n await _link(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if (e.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer {\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise;\n\n execute(): Promise {\n return new Promise(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, debugAssert, _createError, _assertInstanceOf } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay.\n */\nexport const enum _Timeout {\n AUTH_EVENT = 2000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect =\n (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(auth: AuthInternal, result: () => Promise): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport { _assertInstanceOf } from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _signInWithRedirect(auth, provider, resolver) as Promise;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Link using a redirect.\n * await linkWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _linkWithRedirect(user, provider, resolver) as Promise;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns a {@link UserCredential}\n * with a null `user`.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise {\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set = new Set();\n private readonly consumers: Set = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise {\n return new Promise((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js._loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`).catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\n });\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record\n): string {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record = {};\n private readonly iframes: Record = {};\n private readonly originValidationPromises: Record> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n await this._originValidation(auth);\n _setWindowLocation(\n _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)\n );\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver = BrowserPopupRedirectResolver;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FactorId, MultiFactorAssertion } from '../model/public_types';\nimport { debugFail } from '../core/util/assert';\nimport { MultiFactorSessionImpl, MultiFactorSessionType } from './mfa_session';\nimport { FinalizeMfaResponse } from '../api/authentication/mfa';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorAssertionImpl implements MultiFactorAssertion {\n protected constructor(readonly factorId: FactorId) {}\n\n _process(\n auth: AuthInternal,\n session: MultiFactorSessionImpl,\n displayName?: string | null\n ): Promise {\n switch (session.type) {\n case MultiFactorSessionType.ENROLL:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case MultiFactorSessionType.SIGN_IN:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n\n abstract _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise;\n abstract _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n FactorId,\n PhoneMultiFactorAssertion\n} from '../../../model/public_types';\n\nimport { MultiFactorAssertionImpl } from '../../../mfa/mfa_assertion';\nimport { AuthInternal } from '../../../model/auth';\nimport { finalizeEnrollPhoneMfa } from '../../../api/account_management/mfa';\nimport { PhoneAuthCredential } from '../../../core/credentials/phone';\nimport {\n finalizeSignInPhoneMfa,\n FinalizeMfaResponse\n} from '../../../api/authentication/mfa';\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nexport class PhoneMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements PhoneMultiFactorAssertion {\n private constructor(private readonly credential: PhoneAuthCredential) {\n super(FactorId.PHONE);\n }\n\n /** @internal */\n static _fromCredential(\n credential: PhoneAuthCredential\n ): PhoneMultiFactorAssertionImpl {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n\n /** @internal */\n _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nexport class PhoneMultiFactorGenerator {\n private constructor() {}\n\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n\n /**\n * The identifier of the phone second factor: `phone`.\n */\n static FACTOR_ID = 'phone';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map<\n TokenListener,\n Unsubscribe\n > = new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode,\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider = container.getProvider<'heartbeat'>('heartbeat');\n const { apiKey, authDomain } = app.options;\n return ((app, heartbeatServiceProvider) => {\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n // Auth domain is optional if IdP sign in isn't being used\n _assert(!authDomain?.includes(':'), AuthErrorCode.ARGUMENT_ERROR, {\n appName: app.name\n });\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, config);\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n })(app, heartbeatServiceProvider);\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\n\nimport { initializeAuth } from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth } from '../model/public_types';\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n return initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n}\n\nregisterAuth(ClientPlatform.BROWSER);\n"],"sourceRoot":""}