UNPKG

371 kBJavaScriptView Raw
1'use strict';
2
3var tslib = require('tslib');
4var util = require('@firebase/util');
5var app = require('@firebase/app');
6var component = require('@firebase/component');
7var logger = require('@firebase/logger');
8
9/**
10 * @license
11 * Copyright 2020 Google LLC
12 *
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 * http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
24 */
25function _debugErrorMap() {
26 var _a;
27 return _a = {},
28 _a["admin-restricted-operation" /* ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
29 _a["argument-error" /* ARGUMENT_ERROR */] = '',
30 _a["app-not-authorized" /* APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
31 'authorized to use Firebase Authentication with the provided API key. ' +
32 'Review your key configuration in the Google API console.',
33 _a["app-not-installed" /* APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
34 'Android package name or iOS bundle ID) provided is not installed on ' +
35 'this device.',
36 _a["captcha-check-failed" /* CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
37 'already used or the domain associated with it does not match the list ' +
38 'of whitelisted domains.',
39 _a["code-expired" /* CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
40 'again.',
41 _a["cordova-not-ready" /* CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
42 _a["cors-unsupported" /* CORS_UNSUPPORTED */] = 'This browser is not supported.',
43 _a["credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
44 _a["custom-token-mismatch" /* CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
45 _a["requires-recent-login" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
46 'again before retrying this request.',
47 _a["dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
48 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
49 'starting any other Firebase SDK.',
50 _a["dynamic-link-not-activated" /* DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
51 'conditions.',
52 _a["email-change-needs-verification" /* EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
53 _a["email-already-in-use" /* EMAIL_EXISTS */] = 'The email address is already in use by another account.',
54 _a["emulator-config-failed" /* EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
55 'no longer be configured to use the emulator. Try calling ' +
56 '"connectAuthEmulator()" sooner.',
57 _a["expired-action-code" /* EXPIRED_OOB_CODE */] = 'The action code has expired.',
58 _a["cancelled-popup-request" /* EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
59 _a["internal-error" /* INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
60 _a["invalid-app-credential" /* INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
61 ' The reCAPTCHA token response is either invalid or expired.',
62 _a["invalid-app-id" /* INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
63 _a["invalid-user-token" /* INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
64 "if the user's token has been tampered with, or if the user isn't for " +
65 'the project associated with this API key.',
66 _a["invalid-auth-event" /* INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
67 _a["invalid-verification-code" /* INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
68 'invalid. Please resend the verification code sms and be sure to use the ' +
69 'verification code provided by the user.',
70 _a["invalid-continue-uri" /* INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
71 _a["invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
72 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
73 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
74 'cordova-plugin-customurlscheme.',
75 _a["invalid-custom-token" /* INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
76 _a["invalid-dynamic-link-domain" /* INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
77 _a["invalid-email" /* INVALID_EMAIL */] = 'The email address is badly formatted.',
78 _a["invalid-emulator-scheme" /* INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
79 _a["invalid-api-key" /* INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
80 _a["invalid-cert-hash" /* INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
81 _a["invalid-credential" /* INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
82 _a["invalid-message-payload" /* INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
83 'Please fix by going to the Auth email templates section in the Firebase Console.',
84 _a["invalid-multi-factor-session" /* INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
85 _a["invalid-oauth-provider" /* INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
86 'only supports OAuth providers.',
87 _a["invalid-oauth-client-id" /* INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
88 'specified API key.',
89 _a["unauthorized-domain" /* INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
90 'project. Edit the list of authorized domains from the Firebase console.',
91 _a["invalid-action-code" /* INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
92 'expired, or has already been used.',
93 _a["wrong-password" /* INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
94 _a["invalid-persistence-type" /* INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
95 _a["invalid-phone-number" /* INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
96 'phone number in a format that can be parsed into E.164 format. E.164 ' +
97 'phone numbers are written in the format [+][country code][subscriber ' +
98 'number including area code].',
99 _a["invalid-provider-id" /* INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
100 _a["invalid-recipient-email" /* INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
101 'recipient email address is invalid.',
102 _a["invalid-sender" /* INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
103 'Please fix by going to the Auth email templates section in the Firebase Console.',
104 _a["invalid-verification-id" /* INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
105 _a["invalid-tenant-id" /* INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
106 _a["login-blocked" /* LOGIN_BLOCKED */] = "Login blocked by user-provided method: {$originalMessage}",
107 _a["missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
108 _a["auth-domain-config-required" /* MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
109 'by following the instructions in the Firebase console.',
110 _a["missing-app-credential" /* MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
111 'assertion. A reCAPTCHA response token needs to be provided.',
112 _a["missing-verification-code" /* MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
113 _a["missing-continue-uri" /* MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
114 _a["missing-iframe-start" /* MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
115 _a["missing-ios-bundle-id" /* MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
116 _a["missing-or-invalid-nonce" /* MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
117 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
118 'in the ID token payload.',
119 _a["missing-multi-factor-info" /* MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
120 _a["missing-multi-factor-session" /* MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
121 _a["missing-phone-number" /* MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
122 _a["missing-verification-id" /* MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
123 _a["app-deleted" /* MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
124 _a["multi-factor-info-not-found" /* MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
125 _a["multi-factor-auth-required" /* MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
126 _a["account-exists-with-different-credential" /* NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
127 'sign-in credentials. Sign in using a provider associated with this ' +
128 'email address.',
129 _a["network-request-failed" /* NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
130 _a["no-auth-event" /* NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
131 _a["no-such-provider" /* NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
132 _a["null-user" /* NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
133 'requires a non-null user object.',
134 _a["operation-not-allowed" /* OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
135 'Enable it in the Firebase console, under the sign-in method tab of the ' +
136 'Auth section.',
137 _a["operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
138 'running on. "location.protocol" must be http, https or chrome-extension' +
139 ' and web storage must be enabled.',
140 _a["popup-blocked" /* POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
141 _a["popup-closed-by-user" /* POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
142 _a["provider-already-linked" /* PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
143 _a["quota-exceeded" /* QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
144 _a["redirect-cancelled-by-user" /* REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
145 _a["redirect-operation-pending" /* REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
146 _a["rejected-credential" /* REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
147 _a["second-factor-already-in-use" /* SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
148 _a["maximum-second-factor-count-exceeded" /* SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
149 _a["tenant-id-mismatch" /* TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
150 _a["timeout" /* TIMEOUT */] = 'The operation has timed out.',
151 _a["user-token-expired" /* TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
152 _a["too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
153 'Try again later.',
154 _a["unauthorized-continue-uri" /* UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
155 'the domain in the Firebase console.',
156 _a["unsupported-first-factor" /* UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
157 _a["unsupported-persistence-type" /* UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
158 _a["unsupported-tenant-operation" /* UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
159 _a["unverified-email" /* UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
160 _a["user-cancelled" /* USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
161 _a["user-not-found" /* USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
162 'have been deleted.',
163 _a["user-disabled" /* USER_DISABLED */] = 'The user account has been disabled by an administrator.',
164 _a["user-mismatch" /* USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
165 _a["user-signed-out" /* USER_SIGNED_OUT */] = '',
166 _a["weak-password" /* WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
167 _a["web-storage-unsupported" /* WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
168 _a["already-initialized" /* ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
169 'different options. To avoid this error, call initializeAuth() with the ' +
170 'same options as when it was originally called, or call getAuth() to return the' +
171 ' already initialized instance.',
172 _a;
173}
174function _prodErrorMap() {
175 var _a;
176 // We will include this one message in the prod error map since by the very
177 // nature of this error, developers will never be able to see the message
178 // using the debugErrorMap (which is installed during auth initialization).
179 return _a = {},
180 _a["dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
181 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
182 'starting any other Firebase SDK.',
183 _a;
184}
185/**
186 * A verbose error map with detailed descriptions for most error codes.
187 *
188 * See discussion at {@link AuthErrorMap}
189 *
190 * @public
191 */
192var debugErrorMap = _debugErrorMap;
193/**
194 * A minimal error map with all verbose error messages stripped.
195 *
196 * See discussion at {@link AuthErrorMap}
197 *
198 * @public
199 */
200var prodErrorMap = _prodErrorMap;
201var _DEFAULT_AUTH_ERROR_FACTORY = new util.ErrorFactory('auth', 'Firebase', _prodErrorMap());
202/**
203 * A map of potential `Auth` error codes, for easier comparison with errors
204 * thrown by the SDK.
205 *
206 * @remarks
207 * Note that you can't tree-shake individual keys
208 * in the map, so by using the map you might substantially increase your
209 * bundle size.
210 *
211 * @public
212 */
213var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
214 ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
215 ARGUMENT_ERROR: 'auth/argument-error',
216 APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
217 APP_NOT_INSTALLED: 'auth/app-not-installed',
218 CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
219 CODE_EXPIRED: 'auth/code-expired',
220 CORDOVA_NOT_READY: 'auth/cordova-not-ready',
221 CORS_UNSUPPORTED: 'auth/cors-unsupported',
222 CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
223 CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
224 CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
225 DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
226 DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
227 EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
228 EMAIL_EXISTS: 'auth/email-already-in-use',
229 EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
230 EXPIRED_OOB_CODE: 'auth/expired-action-code',
231 EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
232 INTERNAL_ERROR: 'auth/internal-error',
233 INVALID_API_KEY: 'auth/invalid-api-key',
234 INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
235 INVALID_APP_ID: 'auth/invalid-app-id',
236 INVALID_AUTH: 'auth/invalid-user-token',
237 INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
238 INVALID_CERT_HASH: 'auth/invalid-cert-hash',
239 INVALID_CODE: 'auth/invalid-verification-code',
240 INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
241 INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
242 INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
243 INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
244 INVALID_EMAIL: 'auth/invalid-email',
245 INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
246 INVALID_IDP_RESPONSE: 'auth/invalid-credential',
247 INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
248 INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
249 INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
250 INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
251 INVALID_OOB_CODE: 'auth/invalid-action-code',
252 INVALID_ORIGIN: 'auth/unauthorized-domain',
253 INVALID_PASSWORD: 'auth/wrong-password',
254 INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
255 INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
256 INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
257 INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
258 INVALID_SENDER: 'auth/invalid-sender',
259 INVALID_SESSION_INFO: 'auth/invalid-verification-id',
260 INVALID_TENANT_ID: 'auth/invalid-tenant-id',
261 MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
262 MFA_REQUIRED: 'auth/multi-factor-auth-required',
263 MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
264 MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
265 MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
266 MISSING_CODE: 'auth/missing-verification-code',
267 MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
268 MISSING_IFRAME_START: 'auth/missing-iframe-start',
269 MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
270 MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
271 MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
272 MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
273 MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
274 MISSING_SESSION_INFO: 'auth/missing-verification-id',
275 MODULE_DESTROYED: 'auth/app-deleted',
276 NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
277 NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
278 NULL_USER: 'auth/null-user',
279 NO_AUTH_EVENT: 'auth/no-auth-event',
280 NO_SUCH_PROVIDER: 'auth/no-such-provider',
281 OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
282 OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
283 POPUP_BLOCKED: 'auth/popup-blocked',
284 POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
285 PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
286 QUOTA_EXCEEDED: 'auth/quota-exceeded',
287 REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
288 REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
289 REJECTED_CREDENTIAL: 'auth/rejected-credential',
290 SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
291 SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
292 TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
293 TIMEOUT: 'auth/timeout',
294 TOKEN_EXPIRED: 'auth/user-token-expired',
295 TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
296 UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
297 UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
298 UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
299 UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
300 UNVERIFIED_EMAIL: 'auth/unverified-email',
301 USER_CANCELLED: 'auth/user-cancelled',
302 USER_DELETED: 'auth/user-not-found',
303 USER_DISABLED: 'auth/user-disabled',
304 USER_MISMATCH: 'auth/user-mismatch',
305 USER_SIGNED_OUT: 'auth/user-signed-out',
306 WEAK_PASSWORD: 'auth/weak-password',
307 WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
308 ALREADY_INITIALIZED: 'auth/already-initialized'
309};
310
311/**
312 * @license
313 * Copyright 2020 Google LLC
314 *
315 * Licensed under the Apache License, Version 2.0 (the "License");
316 * you may not use this file except in compliance with the License.
317 * You may obtain a copy of the License at
318 *
319 * http://www.apache.org/licenses/LICENSE-2.0
320 *
321 * Unless required by applicable law or agreed to in writing, software
322 * distributed under the License is distributed on an "AS IS" BASIS,
323 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
324 * See the License for the specific language governing permissions and
325 * limitations under the License.
326 */
327var logClient = new logger.Logger('@firebase/auth');
328function _logError(msg) {
329 var args = [];
330 for (var _i = 1; _i < arguments.length; _i++) {
331 args[_i - 1] = arguments[_i];
332 }
333 if (logClient.logLevel <= logger.LogLevel.ERROR) {
334 logClient.error.apply(logClient, tslib.__spreadArray(["Auth (" + app.SDK_VERSION + "): " + msg], args));
335 }
336}
337
338/**
339 * @license
340 * Copyright 2020 Google LLC
341 *
342 * Licensed under the Apache License, Version 2.0 (the "License");
343 * you may not use this file except in compliance with the License.
344 * You may obtain a copy of the License at
345 *
346 * http://www.apache.org/licenses/LICENSE-2.0
347 *
348 * Unless required by applicable law or agreed to in writing, software
349 * distributed under the License is distributed on an "AS IS" BASIS,
350 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
351 * See the License for the specific language governing permissions and
352 * limitations under the License.
353 */
354function _fail(authOrCode) {
355 var rest = [];
356 for (var _i = 1; _i < arguments.length; _i++) {
357 rest[_i - 1] = arguments[_i];
358 }
359 throw createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest));
360}
361function _createError(authOrCode) {
362 var rest = [];
363 for (var _i = 1; _i < arguments.length; _i++) {
364 rest[_i - 1] = arguments[_i];
365 }
366 return createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest));
367}
368function _errorWithCustomMessage(auth, code, message) {
369 var _a;
370 var errorMap = tslib.__assign(tslib.__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
371 var factory = new util.ErrorFactory('auth', 'Firebase', errorMap);
372 return factory.create(code, {
373 appName: auth.name,
374 });
375}
376function _assertInstanceOf(auth, object, instance) {
377 var constructorInstance = instance;
378 if (!(object instanceof constructorInstance)) {
379 if (constructorInstance.name !== object.constructor.name) {
380 _fail(auth, "argument-error" /* ARGUMENT_ERROR */);
381 }
382 throw _errorWithCustomMessage(auth, "argument-error" /* ARGUMENT_ERROR */, "Type of " + object.constructor.name + " does not match expected instance." +
383 "Did you pass a reference from a different Auth SDK?");
384 }
385}
386function createErrorInternal(authOrCode) {
387 var _a;
388 var rest = [];
389 for (var _i = 1; _i < arguments.length; _i++) {
390 rest[_i - 1] = arguments[_i];
391 }
392 if (typeof authOrCode !== 'string') {
393 var code = rest[0];
394 var fullParams = tslib.__spreadArray([], rest.slice(1));
395 if (fullParams[0]) {
396 fullParams[0].appName = authOrCode.name;
397 }
398 return (_a = authOrCode._errorFactory).create.apply(_a, tslib.__spreadArray([code], fullParams));
399 }
400 return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, tslib.__spreadArray([authOrCode], rest));
401}
402function _assert(assertion, authOrCode) {
403 var rest = [];
404 for (var _i = 2; _i < arguments.length; _i++) {
405 rest[_i - 2] = arguments[_i];
406 }
407 if (!assertion) {
408 throw createErrorInternal.apply(void 0, tslib.__spreadArray([authOrCode], rest));
409 }
410}
411/**
412 * Unconditionally fails, throwing an internal error with the given message.
413 *
414 * @param failure type of failure encountered
415 * @throws Error
416 */
417function debugFail(failure) {
418 // Log the failure in addition to throw an exception, just in case the
419 // exception is swallowed.
420 var message = "INTERNAL ASSERTION FAILED: " + failure;
421 _logError(message);
422 // NOTE: We don't use FirebaseError here because these are internal failures
423 // that cannot be handled by the user. (Also it would create a circular
424 // dependency between the error and assert modules which doesn't work.)
425 throw new Error(message);
426}
427/**
428 * Fails if the given assertion condition is false, throwing an Error with the
429 * given message if it did.
430 *
431 * @param assertion
432 * @param message
433 */
434function debugAssert(assertion, message) {
435 if (!assertion) {
436 debugFail(message);
437 }
438}
439
440/**
441 * @license
442 * Copyright 2020 Google LLC
443 *
444 * Licensed under the Apache License, Version 2.0 (the "License");
445 * you may not use this file except in compliance with the License.
446 * You may obtain a copy of the License at
447 *
448 * http://www.apache.org/licenses/LICENSE-2.0
449 *
450 * Unless required by applicable law or agreed to in writing, software
451 * distributed under the License is distributed on an "AS IS" BASIS,
452 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
453 * See the License for the specific language governing permissions and
454 * limitations under the License.
455 */
456var instanceCache = new Map();
457function _getInstance(cls) {
458 debugAssert(cls instanceof Function, 'Expected a class definition');
459 var instance = instanceCache.get(cls);
460 if (instance) {
461 debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
462 return instance;
463 }
464 instance = new cls();
465 instanceCache.set(cls, instance);
466 return instance;
467}
468
469/**
470 * @license
471 * Copyright 2020 Google LLC
472 *
473 * Licensed under the Apache License, Version 2.0 (the "License");
474 * you may not use this file except in compliance with the License.
475 * You may obtain a copy of the License at
476 *
477 * http://www.apache.org/licenses/LICENSE-2.0
478 *
479 * Unless required by applicable law or agreed to in writing, software
480 * distributed under the License is distributed on an "AS IS" BASIS,
481 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
482 * See the License for the specific language governing permissions and
483 * limitations under the License.
484 */
485/**
486 * Initializes an {@link Auth} instance with fine-grained control over
487 * {@link Dependencies}.
488 *
489 * @remarks
490 *
491 * This function allows more control over the {@link Auth} instance than
492 * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
493 * the {@link Dependencies}. In general, `getAuth` is the easiest way to
494 * initialize Auth and works for most use cases. Use `initializeAuth` if you
495 * need control over which persistence layer is used, or to minimize bundle
496 * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
497 *
498 * For example, if your app only uses anonymous accounts and you only want
499 * accounts saved for the current session, initialize `Auth` with:
500 *
501 * ```js
502 * const auth = initializeAuth(app, {
503 * persistence: browserSessionPersistence,
504 * popupRedirectResolver: undefined,
505 * });
506 * ```
507 *
508 * @public
509 */
510function initializeAuth(app$1, deps) {
511 var provider = app._getProvider(app$1, 'auth');
512 if (provider.isInitialized()) {
513 var auth_1 = provider.getImmediate();
514 var initialOptions = provider.getOptions();
515 if (util.deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
516 return auth_1;
517 }
518 else {
519 _fail(auth_1, "already-initialized" /* ALREADY_INITIALIZED */);
520 }
521 }
522 var auth = provider.initialize({ options: deps });
523 return auth;
524}
525function _initializeAuthInstance(auth, deps) {
526 var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
527 var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
528 if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
529 auth._updateErrorMap(deps.errorMap);
530 }
531 // This promise is intended to float; auth initialization happens in the
532 // background, meanwhile the auth object may be used by the app.
533 // eslint-disable-next-line @typescript-eslint/no-floating-promises
534 auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
535}
536
537/**
538 * @license
539 * Copyright 2020 Google LLC
540 *
541 * Licensed under the Apache License, Version 2.0 (the "License");
542 * you may not use this file except in compliance with the License.
543 * You may obtain a copy of the License at
544 *
545 * http://www.apache.org/licenses/LICENSE-2.0
546 *
547 * Unless required by applicable law or agreed to in writing, software
548 * distributed under the License is distributed on an "AS IS" BASIS,
549 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
550 * See the License for the specific language governing permissions and
551 * limitations under the License.
552 */
553function _getCurrentUrl() {
554 var _a;
555 return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
556}
557function _isHttpOrHttps() {
558 return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
559}
560function _getCurrentScheme() {
561 var _a;
562 return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
563}
564
565/**
566 * @license
567 * Copyright 2020 Google LLC
568 *
569 * Licensed under the Apache License, Version 2.0 (the "License");
570 * you may not use this file except in compliance with the License.
571 * You may obtain a copy of the License at
572 *
573 * http://www.apache.org/licenses/LICENSE-2.0
574 *
575 * Unless required by applicable law or agreed to in writing, software
576 * distributed under the License is distributed on an "AS IS" BASIS,
577 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
578 * See the License for the specific language governing permissions and
579 * limitations under the License.
580 */
581/**
582 * Determine whether the browser is working online
583 */
584function _isOnline() {
585 if (typeof navigator !== 'undefined' &&
586 navigator &&
587 'onLine' in navigator &&
588 typeof navigator.onLine === 'boolean' &&
589 // Apply only for traditional web apps and Chrome extensions.
590 // This is especially true for Cordova apps which have unreliable
591 // navigator.onLine behavior unless cordova-plugin-network-information is
592 // installed which overwrites the native navigator.onLine value and
593 // defines navigator.connection.
594 (_isHttpOrHttps() || util.isBrowserExtension() || 'connection' in navigator)) {
595 return navigator.onLine;
596 }
597 // If we can't determine the state, assume it is online.
598 return true;
599}
600function _getUserLanguage() {
601 if (typeof navigator === 'undefined') {
602 return null;
603 }
604 var navigatorLanguage = navigator;
605 return (
606 // Most reliable, but only supported in Chrome/Firefox.
607 (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
608 // Supported in most browsers, but returns the language of the browser
609 // UI, not the language set in browser settings.
610 navigatorLanguage.language ||
611 // Couldn't determine language.
612 null);
613}
614
615/**
616 * @license
617 * Copyright 2020 Google LLC
618 *
619 * Licensed under the Apache License, Version 2.0 (the "License");
620 * you may not use this file except in compliance with the License.
621 * You may obtain a copy of the License at
622 *
623 * http://www.apache.org/licenses/LICENSE-2.0
624 *
625 * Unless required by applicable law or agreed to in writing, software
626 * distributed under the License is distributed on an "AS IS" BASIS,
627 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
628 * See the License for the specific language governing permissions and
629 * limitations under the License.
630 */
631/**
632 * A structure to help pick between a range of long and short delay durations
633 * depending on the current environment. In general, the long delay is used for
634 * mobile environments whereas short delays are used for desktop environments.
635 */
636var Delay = /** @class */ (function () {
637 function Delay(shortDelay, longDelay) {
638 this.shortDelay = shortDelay;
639 this.longDelay = longDelay;
640 // Internal error when improperly initialized.
641 debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
642 this.isMobile = util.isMobileCordova() || util.isReactNative();
643 }
644 Delay.prototype.get = function () {
645 if (!_isOnline()) {
646 // Pick the shorter timeout.
647 return Math.min(5000 /* OFFLINE */, this.shortDelay);
648 }
649 // If running in a mobile environment, return the long delay, otherwise
650 // return the short delay.
651 // This could be improved in the future to dynamically change based on other
652 // variables instead of just reading the current environment.
653 return this.isMobile ? this.longDelay : this.shortDelay;
654 };
655 return Delay;
656}());
657
658/**
659 * @license
660 * Copyright 2020 Google LLC
661 *
662 * Licensed under the Apache License, Version 2.0 (the "License");
663 * you may not use this file except in compliance with the License.
664 * You may obtain a copy of the License at
665 *
666 * http://www.apache.org/licenses/LICENSE-2.0
667 *
668 * Unless required by applicable law or agreed to in writing, software
669 * distributed under the License is distributed on an "AS IS" BASIS,
670 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
671 * See the License for the specific language governing permissions and
672 * limitations under the License.
673 */
674function _emulatorUrl(config, path) {
675 debugAssert(config.emulator, 'Emulator should always be set here');
676 var url = config.emulator.url;
677 if (!path) {
678 return url;
679 }
680 return "" + url + (path.startsWith('/') ? path.slice(1) : path);
681}
682
683/**
684 * @license
685 * Copyright 2020 Google LLC
686 *
687 * Licensed under the Apache License, Version 2.0 (the "License");
688 * you may not use this file except in compliance with the License.
689 * You may obtain a copy of the License at
690 *
691 * http://www.apache.org/licenses/LICENSE-2.0
692 *
693 * Unless required by applicable law or agreed to in writing, software
694 * distributed under the License is distributed on an "AS IS" BASIS,
695 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
696 * See the License for the specific language governing permissions and
697 * limitations under the License.
698 */
699var FetchProvider = /** @class */ (function () {
700 function FetchProvider() {
701 }
702 FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
703 this.fetchImpl = fetchImpl;
704 if (headersImpl) {
705 this.headersImpl = headersImpl;
706 }
707 if (responseImpl) {
708 this.responseImpl = responseImpl;
709 }
710 };
711 FetchProvider.fetch = function () {
712 if (this.fetchImpl) {
713 return this.fetchImpl;
714 }
715 if (typeof self !== 'undefined' && 'fetch' in self) {
716 return self.fetch;
717 }
718 debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
719 };
720 FetchProvider.headers = function () {
721 if (this.headersImpl) {
722 return this.headersImpl;
723 }
724 if (typeof self !== 'undefined' && 'Headers' in self) {
725 return self.Headers;
726 }
727 debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
728 };
729 FetchProvider.response = function () {
730 if (this.responseImpl) {
731 return this.responseImpl;
732 }
733 if (typeof self !== 'undefined' && 'Response' in self) {
734 return self.Response;
735 }
736 debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
737 };
738 return FetchProvider;
739}());
740
741/**
742 * @license
743 * Copyright 2020 Google LLC
744 *
745 * Licensed under the Apache License, Version 2.0 (the "License");
746 * you may not use this file except in compliance with the License.
747 * You may obtain a copy of the License at
748 *
749 * http://www.apache.org/licenses/LICENSE-2.0
750 *
751 * Unless required by applicable law or agreed to in writing, software
752 * distributed under the License is distributed on an "AS IS" BASIS,
753 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
754 * See the License for the specific language governing permissions and
755 * limitations under the License.
756 */
757var _a$1;
758/**
759 * Map from errors returned by the server to errors to developer visible errors
760 */
761var SERVER_ERROR_MAP = (_a$1 = {},
762 // Custom token errors.
763 _a$1["CREDENTIAL_MISMATCH" /* CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* CREDENTIAL_MISMATCH */,
764 // This can only happen if the SDK sends a bad request.
765 _a$1["MISSING_CUSTOM_TOKEN" /* MISSING_CUSTOM_TOKEN */] = "internal-error" /* INTERNAL_ERROR */,
766 // Create Auth URI errors.
767 _a$1["INVALID_IDENTIFIER" /* INVALID_IDENTIFIER */] = "invalid-email" /* INVALID_EMAIL */,
768 // This can only happen if the SDK sends a bad request.
769 _a$1["MISSING_CONTINUE_URI" /* MISSING_CONTINUE_URI */] = "internal-error" /* INTERNAL_ERROR */,
770 // Sign in with email and password errors (some apply to sign up too).
771 _a$1["INVALID_PASSWORD" /* INVALID_PASSWORD */] = "wrong-password" /* INVALID_PASSWORD */,
772 // This can only happen if the SDK sends a bad request.
773 _a$1["MISSING_PASSWORD" /* MISSING_PASSWORD */] = "internal-error" /* INTERNAL_ERROR */,
774 // Sign up with email and password errors.
775 _a$1["EMAIL_EXISTS" /* EMAIL_EXISTS */] = "email-already-in-use" /* EMAIL_EXISTS */,
776 _a$1["PASSWORD_LOGIN_DISABLED" /* PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* OPERATION_NOT_ALLOWED */,
777 // Verify assertion for sign in with credential errors:
778 _a$1["INVALID_IDP_RESPONSE" /* INVALID_IDP_RESPONSE */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
779 _a$1["INVALID_PENDING_TOKEN" /* INVALID_PENDING_TOKEN */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
780 _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */,
781 // This can only happen if the SDK sends a bad request.
782 _a$1["MISSING_REQ_TYPE" /* MISSING_REQ_TYPE */] = "internal-error" /* INTERNAL_ERROR */,
783 // Send Password reset email errors:
784 _a$1["EMAIL_NOT_FOUND" /* EMAIL_NOT_FOUND */] = "user-not-found" /* USER_DELETED */,
785 _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */,
786 _a$1["EXPIRED_OOB_CODE" /* EXPIRED_OOB_CODE */] = "expired-action-code" /* EXPIRED_OOB_CODE */,
787 _a$1["INVALID_OOB_CODE" /* INVALID_OOB_CODE */] = "invalid-action-code" /* INVALID_OOB_CODE */,
788 // This can only happen if the SDK sends a bad request.
789 _a$1["MISSING_OOB_CODE" /* MISSING_OOB_CODE */] = "internal-error" /* INTERNAL_ERROR */,
790 // Operations that require ID token in request:
791 _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
792 _a$1["INVALID_ID_TOKEN" /* INVALID_ID_TOKEN */] = "invalid-user-token" /* INVALID_AUTH */,
793 _a$1["TOKEN_EXPIRED" /* TOKEN_EXPIRED */] = "user-token-expired" /* TOKEN_EXPIRED */,
794 _a$1["USER_NOT_FOUND" /* USER_NOT_FOUND */] = "user-token-expired" /* TOKEN_EXPIRED */,
795 // Other errors.
796 _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */,
797 // Phone Auth related errors.
798 _a$1["INVALID_CODE" /* INVALID_CODE */] = "invalid-verification-code" /* INVALID_CODE */,
799 _a$1["INVALID_SESSION_INFO" /* INVALID_SESSION_INFO */] = "invalid-verification-id" /* INVALID_SESSION_INFO */,
800 _a$1["INVALID_TEMPORARY_PROOF" /* INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
801 _a$1["MISSING_SESSION_INFO" /* MISSING_SESSION_INFO */] = "missing-verification-id" /* MISSING_SESSION_INFO */,
802 _a$1["SESSION_EXPIRED" /* SESSION_EXPIRED */] = "code-expired" /* CODE_EXPIRED */,
803 // Other action code errors when additional settings passed.
804 // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
805 // This is OK as this error will be caught by client side validation.
806 _a$1["MISSING_ANDROID_PACKAGE_NAME" /* MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */,
807 _a$1["UNAUTHORIZED_DOMAIN" /* UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* UNAUTHORIZED_DOMAIN */,
808 // getProjectConfig errors when clientId is passed.
809 _a$1["INVALID_OAUTH_CLIENT_ID" /* INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* INVALID_OAUTH_CLIENT_ID */,
810 // User actions (sign-up or deletion) disabled errors.
811 _a$1["ADMIN_ONLY_OPERATION" /* ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* ADMIN_ONLY_OPERATION */,
812 // Multi factor related errors.
813 _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* INVALID_MFA_SESSION */,
814 _a$1["MFA_ENROLLMENT_NOT_FOUND" /* MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* MFA_INFO_NOT_FOUND */,
815 _a$1["MISSING_MFA_ENROLLMENT_ID" /* MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* MISSING_MFA_INFO */,
816 _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* MISSING_MFA_SESSION */,
817 _a$1["SECOND_FACTOR_EXISTS" /* SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* SECOND_FACTOR_ALREADY_ENROLLED */,
818 _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* SECOND_FACTOR_LIMIT_EXCEEDED */,
819 // Blocking functions related errors.
820 _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* INTERNAL_ERROR */,
821 _a$1);
822
823/**
824 * @license
825 * Copyright 2020 Google LLC
826 *
827 * Licensed under the Apache License, Version 2.0 (the "License");
828 * you may not use this file except in compliance with the License.
829 * You may obtain a copy of the License at
830 *
831 * http://www.apache.org/licenses/LICENSE-2.0
832 *
833 * Unless required by applicable law or agreed to in writing, software
834 * distributed under the License is distributed on an "AS IS" BASIS,
835 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
836 * See the License for the specific language governing permissions and
837 * limitations under the License.
838 */
839var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
840function _addTidIfNecessary(auth, request) {
841 if (auth.tenantId && !request.tenantId) {
842 return tslib.__assign(tslib.__assign({}, request), { tenantId: auth.tenantId });
843 }
844 return request;
845}
846function _performApiRequest(auth, method, path, request, customErrorMap) {
847 if (customErrorMap === void 0) { customErrorMap = {}; }
848 return tslib.__awaiter(this, void 0, void 0, function () {
849 var _this = this;
850 return tslib.__generator(this, function (_a) {
851 return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return tslib.__awaiter(_this, void 0, void 0, function () {
852 var body, params, query, headers;
853 return tslib.__generator(this, function (_a) {
854 switch (_a.label) {
855 case 0:
856 body = {};
857 params = {};
858 if (request) {
859 if (method === "GET" /* GET */) {
860 params = request;
861 }
862 else {
863 body = {
864 body: JSON.stringify(request)
865 };
866 }
867 }
868 query = util.querystring(tslib.__assign({ key: auth.config.apiKey }, params)).slice(1);
869 return [4 /*yield*/, auth._getAdditionalHeaders()];
870 case 1:
871 headers = _a.sent();
872 headers["Content-Type" /* CONTENT_TYPE */] = 'application/json';
873 if (auth.languageCode) {
874 headers["X-Firebase-Locale" /* X_FIREBASE_LOCALE */] = auth.languageCode;
875 }
876 return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), tslib.__assign({ method: method,
877 headers: headers, referrerPolicy: 'no-referrer' }, body))];
878 }
879 });
880 }); })];
881 });
882 });
883}
884function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
885 return tslib.__awaiter(this, void 0, void 0, function () {
886 var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
887 return tslib.__generator(this, function (_b) {
888 switch (_b.label) {
889 case 0:
890 auth._canInitEmulator = false;
891 errorMap = tslib.__assign(tslib.__assign({}, SERVER_ERROR_MAP), customErrorMap);
892 _b.label = 1;
893 case 1:
894 _b.trys.push([1, 4, , 5]);
895 networkTimeout = new NetworkTimeout(auth);
896 return [4 /*yield*/, Promise.race([
897 fetchFn(),
898 networkTimeout.promise
899 ])];
900 case 2:
901 response = _b.sent();
902 // If we've reached this point, the fetch succeeded and the networkTimeout
903 // didn't throw; clear the network timeout delay so that Node won't hang
904 networkTimeout.clearNetworkTimeout();
905 return [4 /*yield*/, response.json()];
906 case 3:
907 json = _b.sent();
908 if ('needConfirmation' in json) {
909 throw _makeTaggedError(auth, "account-exists-with-different-credential" /* NEED_CONFIRMATION */, json);
910 }
911 if (response.ok && !('errorMessage' in json)) {
912 return [2 /*return*/, json];
913 }
914 else {
915 errorMessage = response.ok ? json.errorMessage : json.error.message;
916 _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
917 if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* FEDERATED_USER_ID_ALREADY_LINKED */) {
918 throw _makeTaggedError(auth, "credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */, json);
919 }
920 else if (serverErrorCode === "EMAIL_EXISTS" /* EMAIL_EXISTS */) {
921 throw _makeTaggedError(auth, "email-already-in-use" /* EMAIL_EXISTS */, json);
922 }
923 else if (serverErrorCode === "USER_DISABLED" /* USER_DISABLED */) {
924 throw _makeTaggedError(auth, "user-disabled" /* USER_DISABLED */, json);
925 }
926 authError = errorMap[serverErrorCode] ||
927 serverErrorCode
928 .toLowerCase()
929 .replace(/[_\s]+/g, '-');
930 if (serverErrorMessage) {
931 throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
932 }
933 else {
934 _fail(auth, authError);
935 }
936 }
937 return [3 /*break*/, 5];
938 case 4:
939 e_1 = _b.sent();
940 if (e_1 instanceof util.FirebaseError) {
941 throw e_1;
942 }
943 _fail(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */);
944 return [3 /*break*/, 5];
945 case 5: return [2 /*return*/];
946 }
947 });
948 });
949}
950function _performSignInRequest(auth, method, path, request, customErrorMap) {
951 if (customErrorMap === void 0) { customErrorMap = {}; }
952 return tslib.__awaiter(this, void 0, void 0, function () {
953 var serverResponse;
954 return tslib.__generator(this, function (_a) {
955 switch (_a.label) {
956 case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
957 case 1:
958 serverResponse = (_a.sent());
959 if ('mfaPendingCredential' in serverResponse) {
960 _fail(auth, "multi-factor-auth-required" /* MFA_REQUIRED */, {
961 _serverResponse: serverResponse
962 });
963 }
964 return [2 /*return*/, serverResponse];
965 }
966 });
967 });
968}
969function _getFinalTarget(auth, host, path, query) {
970 var base = "" + host + path + "?" + query;
971 if (!auth.config.emulator) {
972 return auth.config.apiScheme + "://" + base;
973 }
974 return _emulatorUrl(auth.config, base);
975}
976var NetworkTimeout = /** @class */ (function () {
977 function NetworkTimeout(auth) {
978 var _this = this;
979 this.auth = auth;
980 // Node timers and browser timers are fundamentally incompatible, but we
981 // don't care about the value here
982 // eslint-disable-next-line @typescript-eslint/no-explicit-any
983 this.timer = null;
984 this.promise = new Promise(function (_, reject) {
985 _this.timer = setTimeout(function () {
986 return reject(_createError(_this.auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
987 }, DEFAULT_API_TIMEOUT_MS.get());
988 });
989 }
990 NetworkTimeout.prototype.clearNetworkTimeout = function () {
991 clearTimeout(this.timer);
992 };
993 return NetworkTimeout;
994}());
995function _makeTaggedError(auth, code, response) {
996 var errorParams = {
997 appName: auth.name
998 };
999 if (response.email) {
1000 errorParams.email = response.email;
1001 }
1002 if (response.phoneNumber) {
1003 errorParams.phoneNumber = response.phoneNumber;
1004 }
1005 var error = _createError(auth, code, errorParams);
1006 // We know customData is defined on error because errorParams is defined
1007 error.customData._tokenResponse = response;
1008 return error;
1009}
1010
1011/**
1012 * @license
1013 * Copyright 2020 Google LLC
1014 *
1015 * Licensed under the Apache License, Version 2.0 (the "License");
1016 * you may not use this file except in compliance with the License.
1017 * You may obtain a copy of the License at
1018 *
1019 * http://www.apache.org/licenses/LICENSE-2.0
1020 *
1021 * Unless required by applicable law or agreed to in writing, software
1022 * distributed under the License is distributed on an "AS IS" BASIS,
1023 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1024 * See the License for the specific language governing permissions and
1025 * limitations under the License.
1026 */
1027function deleteAccount(auth, request) {
1028 return tslib.__awaiter(this, void 0, void 0, function () {
1029 return tslib.__generator(this, function (_a) {
1030 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:delete" /* DELETE_ACCOUNT */, request)];
1031 });
1032 });
1033}
1034function deleteLinkedAccounts(auth, request) {
1035 return tslib.__awaiter(this, void 0, void 0, function () {
1036 return tslib.__generator(this, function (_a) {
1037 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
1038 });
1039 });
1040}
1041function getAccountInfo(auth, request) {
1042 return tslib.__awaiter(this, void 0, void 0, function () {
1043 return tslib.__generator(this, function (_a) {
1044 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:lookup" /* GET_ACCOUNT_INFO */, request)];
1045 });
1046 });
1047}
1048
1049/**
1050 * @license
1051 * Copyright 2020 Google LLC
1052 *
1053 * Licensed under the Apache License, Version 2.0 (the "License");
1054 * you may not use this file except in compliance with the License.
1055 * You may obtain a copy of the License at
1056 *
1057 * http://www.apache.org/licenses/LICENSE-2.0
1058 *
1059 * Unless required by applicable law or agreed to in writing, software
1060 * distributed under the License is distributed on an "AS IS" BASIS,
1061 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1062 * See the License for the specific language governing permissions and
1063 * limitations under the License.
1064 */
1065function utcTimestampToDateString(utcTimestamp) {
1066 if (!utcTimestamp) {
1067 return undefined;
1068 }
1069 try {
1070 // Convert to date object.
1071 var date = new Date(Number(utcTimestamp));
1072 // Test date is valid.
1073 if (!isNaN(date.getTime())) {
1074 // Convert to UTC date string.
1075 return date.toUTCString();
1076 }
1077 }
1078 catch (e) {
1079 // Do nothing. undefined will be returned.
1080 }
1081 return undefined;
1082}
1083
1084/**
1085 * @license
1086 * Copyright 2020 Google LLC
1087 *
1088 * Licensed under the Apache License, Version 2.0 (the "License");
1089 * you may not use this file except in compliance with the License.
1090 * You may obtain a copy of the License at
1091 *
1092 * http://www.apache.org/licenses/LICENSE-2.0
1093 *
1094 * Unless required by applicable law or agreed to in writing, software
1095 * distributed under the License is distributed on an "AS IS" BASIS,
1096 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1097 * See the License for the specific language governing permissions and
1098 * limitations under the License.
1099 */
1100/**
1101 * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
1102 *
1103 * @remarks
1104 * Returns the current token if it has not expired or if it will not expire in the next five
1105 * minutes. Otherwise, this will refresh the token and return a new one.
1106 *
1107 * @param user - The user.
1108 * @param forceRefresh - Force refresh regardless of token expiration.
1109 *
1110 * @public
1111 */
1112function getIdToken(user, forceRefresh) {
1113 if (forceRefresh === void 0) { forceRefresh = false; }
1114 return util.getModularInstance(user).getIdToken(forceRefresh);
1115}
1116/**
1117 * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
1118 *
1119 * @remarks
1120 * Returns the current token if it has not expired or if it will not expire in the next five
1121 * minutes. Otherwise, this will refresh the token and return a new one.
1122 *
1123 * @param user - The user.
1124 * @param forceRefresh - Force refresh regardless of token expiration.
1125 *
1126 * @public
1127 */
1128function getIdTokenResult(user, forceRefresh) {
1129 if (forceRefresh === void 0) { forceRefresh = false; }
1130 return tslib.__awaiter(this, void 0, void 0, function () {
1131 var userInternal, token, claims, firebase, signInProvider;
1132 return tslib.__generator(this, function (_a) {
1133 switch (_a.label) {
1134 case 0:
1135 userInternal = util.getModularInstance(user);
1136 return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
1137 case 1:
1138 token = _a.sent();
1139 claims = _parseToken(token);
1140 _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* INTERNAL_ERROR */);
1141 firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
1142 signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
1143 return [2 /*return*/, {
1144 claims: claims,
1145 token: token,
1146 authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
1147 issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
1148 expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
1149 signInProvider: signInProvider || null,
1150 signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
1151 }];
1152 }
1153 });
1154 });
1155}
1156function secondsStringToMilliseconds(seconds) {
1157 return Number(seconds) * 1000;
1158}
1159function _parseToken(token) {
1160 var _a;
1161 var _b = token.split('.'), algorithm = _b[0], payload = _b[1], signature = _b[2];
1162 if (algorithm === undefined ||
1163 payload === undefined ||
1164 signature === undefined) {
1165 _logError('JWT malformed, contained fewer than 3 sections');
1166 return null;
1167 }
1168 try {
1169 var decoded = util.base64Decode(payload);
1170 if (!decoded) {
1171 _logError('Failed to decode base64 JWT payload');
1172 return null;
1173 }
1174 return JSON.parse(decoded);
1175 }
1176 catch (e) {
1177 _logError('Caught error parsing JWT payload as JSON', (_a = e) === null || _a === void 0 ? void 0 : _a.toString());
1178 return null;
1179 }
1180}
1181/**
1182 * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
1183 */
1184function _tokenExpiresIn(token) {
1185 var parsedToken = _parseToken(token);
1186 _assert(parsedToken, "internal-error" /* INTERNAL_ERROR */);
1187 _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1188 _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1189 return Number(parsedToken.exp) - Number(parsedToken.iat);
1190}
1191
1192/**
1193 * @license
1194 * Copyright 2020 Google LLC
1195 *
1196 * Licensed under the Apache License, Version 2.0 (the "License");
1197 * you may not use this file except in compliance with the License.
1198 * You may obtain a copy of the License at
1199 *
1200 * http://www.apache.org/licenses/LICENSE-2.0
1201 *
1202 * Unless required by applicable law or agreed to in writing, software
1203 * distributed under the License is distributed on an "AS IS" BASIS,
1204 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1205 * See the License for the specific language governing permissions and
1206 * limitations under the License.
1207 */
1208function _logoutIfInvalidated(user, promise, bypassAuthState) {
1209 if (bypassAuthState === void 0) { bypassAuthState = false; }
1210 return tslib.__awaiter(this, void 0, void 0, function () {
1211 var e_1;
1212 return tslib.__generator(this, function (_a) {
1213 switch (_a.label) {
1214 case 0:
1215 if (bypassAuthState) {
1216 return [2 /*return*/, promise];
1217 }
1218 _a.label = 1;
1219 case 1:
1220 _a.trys.push([1, 3, , 6]);
1221 return [4 /*yield*/, promise];
1222 case 2: return [2 /*return*/, _a.sent()];
1223 case 3:
1224 e_1 = _a.sent();
1225 if (!(e_1 instanceof util.FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
1226 if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
1227 return [4 /*yield*/, user.auth.signOut()];
1228 case 4:
1229 _a.sent();
1230 _a.label = 5;
1231 case 5: throw e_1;
1232 case 6: return [2 /*return*/];
1233 }
1234 });
1235 });
1236}
1237function isUserInvalidated(_a) {
1238 var code = _a.code;
1239 return (code === "auth/" + "user-disabled" /* USER_DISABLED */ ||
1240 code === "auth/" + "user-token-expired" /* TOKEN_EXPIRED */);
1241}
1242
1243/**
1244 * @license
1245 * Copyright 2020 Google LLC
1246 *
1247 * Licensed under the Apache License, Version 2.0 (the "License");
1248 * you may not use this file except in compliance with the License.
1249 * You may obtain a copy of the License at
1250 *
1251 * http://www.apache.org/licenses/LICENSE-2.0
1252 *
1253 * Unless required by applicable law or agreed to in writing, software
1254 * distributed under the License is distributed on an "AS IS" BASIS,
1255 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1256 * See the License for the specific language governing permissions and
1257 * limitations under the License.
1258 */
1259var ProactiveRefresh = /** @class */ (function () {
1260 function ProactiveRefresh(user) {
1261 this.user = user;
1262 this.isRunning = false;
1263 // Node timers and browser timers return fundamentally different types.
1264 // We don't actually care what the value is but TS won't accept unknown and
1265 // we can't cast properly in both environments.
1266 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1267 this.timerId = null;
1268 this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;
1269 }
1270 ProactiveRefresh.prototype._start = function () {
1271 if (this.isRunning) {
1272 return;
1273 }
1274 this.isRunning = true;
1275 this.schedule();
1276 };
1277 ProactiveRefresh.prototype._stop = function () {
1278 if (!this.isRunning) {
1279 return;
1280 }
1281 this.isRunning = false;
1282 if (this.timerId !== null) {
1283 clearTimeout(this.timerId);
1284 }
1285 };
1286 ProactiveRefresh.prototype.getInterval = function (wasError) {
1287 var _a;
1288 if (wasError) {
1289 var interval = this.errorBackoff;
1290 this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* RETRY_BACKOFF_MAX */);
1291 return interval;
1292 }
1293 else {
1294 // Reset the error backoff
1295 this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;
1296 var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
1297 var interval = expTime - Date.now() - 300000 /* OFFSET */;
1298 return Math.max(0, interval);
1299 }
1300 };
1301 ProactiveRefresh.prototype.schedule = function (wasError) {
1302 var _this = this;
1303 if (wasError === void 0) { wasError = false; }
1304 if (!this.isRunning) {
1305 // Just in case...
1306 return;
1307 }
1308 var interval = this.getInterval(wasError);
1309 this.timerId = setTimeout(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
1310 return tslib.__generator(this, function (_a) {
1311 switch (_a.label) {
1312 case 0: return [4 /*yield*/, this.iteration()];
1313 case 1:
1314 _a.sent();
1315 return [2 /*return*/];
1316 }
1317 });
1318 }); }, interval);
1319 };
1320 ProactiveRefresh.prototype.iteration = function () {
1321 var _a;
1322 return tslib.__awaiter(this, void 0, void 0, function () {
1323 var e_1;
1324 return tslib.__generator(this, function (_b) {
1325 switch (_b.label) {
1326 case 0:
1327 _b.trys.push([0, 2, , 3]);
1328 return [4 /*yield*/, this.user.getIdToken(true)];
1329 case 1:
1330 _b.sent();
1331 return [3 /*break*/, 3];
1332 case 2:
1333 e_1 = _b.sent();
1334 // Only retry on network errors
1335 if (((_a = e_1) === null || _a === void 0 ? void 0 : _a.code) === "auth/" + "network-request-failed" /* NETWORK_REQUEST_FAILED */) {
1336 this.schedule(/* wasError */ true);
1337 }
1338 return [2 /*return*/];
1339 case 3:
1340 this.schedule();
1341 return [2 /*return*/];
1342 }
1343 });
1344 });
1345 };
1346 return ProactiveRefresh;
1347}());
1348
1349/**
1350 * @license
1351 * Copyright 2020 Google LLC
1352 *
1353 * Licensed under the Apache License, Version 2.0 (the "License");
1354 * you may not use this file except in compliance with the License.
1355 * You may obtain a copy of the License at
1356 *
1357 * http://www.apache.org/licenses/LICENSE-2.0
1358 *
1359 * Unless required by applicable law or agreed to in writing, software
1360 * distributed under the License is distributed on an "AS IS" BASIS,
1361 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1362 * See the License for the specific language governing permissions and
1363 * limitations under the License.
1364 */
1365var UserMetadata = /** @class */ (function () {
1366 function UserMetadata(createdAt, lastLoginAt) {
1367 this.createdAt = createdAt;
1368 this.lastLoginAt = lastLoginAt;
1369 this._initializeTime();
1370 }
1371 UserMetadata.prototype._initializeTime = function () {
1372 this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
1373 this.creationTime = utcTimestampToDateString(this.createdAt);
1374 };
1375 UserMetadata.prototype._copy = function (metadata) {
1376 this.createdAt = metadata.createdAt;
1377 this.lastLoginAt = metadata.lastLoginAt;
1378 this._initializeTime();
1379 };
1380 UserMetadata.prototype.toJSON = function () {
1381 return {
1382 createdAt: this.createdAt,
1383 lastLoginAt: this.lastLoginAt
1384 };
1385 };
1386 return UserMetadata;
1387}());
1388
1389/**
1390 * @license
1391 * Copyright 2019 Google LLC
1392 *
1393 * Licensed under the Apache License, Version 2.0 (the "License");
1394 * you may not use this file except in compliance with the License.
1395 * You may obtain a copy of the License at
1396 *
1397 * http://www.apache.org/licenses/LICENSE-2.0
1398 *
1399 * Unless required by applicable law or agreed to in writing, software
1400 * distributed under the License is distributed on an "AS IS" BASIS,
1401 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1402 * See the License for the specific language governing permissions and
1403 * limitations under the License.
1404 */
1405function _reloadWithoutSaving(user) {
1406 var _a;
1407 return tslib.__awaiter(this, void 0, void 0, function () {
1408 var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
1409 return tslib.__generator(this, function (_b) {
1410 switch (_b.label) {
1411 case 0:
1412 auth = user.auth;
1413 return [4 /*yield*/, user.getIdToken()];
1414 case 1:
1415 idToken = _b.sent();
1416 return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
1417 case 2:
1418 response = _b.sent();
1419 _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* INTERNAL_ERROR */);
1420 coreAccount = response.users[0];
1421 user._notifyReloadListener(coreAccount);
1422 newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
1423 ? extractProviderData(coreAccount.providerUserInfo)
1424 : [];
1425 providerData = mergeProviderData(user.providerData, newProviderData);
1426 oldIsAnonymous = user.isAnonymous;
1427 newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
1428 isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
1429 updates = {
1430 uid: coreAccount.localId,
1431 displayName: coreAccount.displayName || null,
1432 photoURL: coreAccount.photoUrl || null,
1433 email: coreAccount.email || null,
1434 emailVerified: coreAccount.emailVerified || false,
1435 phoneNumber: coreAccount.phoneNumber || null,
1436 tenantId: coreAccount.tenantId || null,
1437 providerData: providerData,
1438 metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
1439 isAnonymous: isAnonymous
1440 };
1441 Object.assign(user, updates);
1442 return [2 /*return*/];
1443 }
1444 });
1445 });
1446}
1447/**
1448 * Reloads user account data, if signed in.
1449 *
1450 * @param user - The user.
1451 *
1452 * @public
1453 */
1454function reload(user) {
1455 return tslib.__awaiter(this, void 0, void 0, function () {
1456 var userInternal;
1457 return tslib.__generator(this, function (_a) {
1458 switch (_a.label) {
1459 case 0:
1460 userInternal = util.getModularInstance(user);
1461 return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
1462 case 1:
1463 _a.sent();
1464 // Even though the current user hasn't changed, update
1465 // current user will trigger a persistence update w/ the
1466 // new info.
1467 return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
1468 case 2:
1469 // Even though the current user hasn't changed, update
1470 // current user will trigger a persistence update w/ the
1471 // new info.
1472 _a.sent();
1473 userInternal.auth._notifyListenersIfCurrent(userInternal);
1474 return [2 /*return*/];
1475 }
1476 });
1477 });
1478}
1479function mergeProviderData(original, newData) {
1480 var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
1481 return tslib.__spreadArray(tslib.__spreadArray([], deduped), newData);
1482}
1483function extractProviderData(providers) {
1484 return providers.map(function (_a) {
1485 var providerId = _a.providerId, provider = tslib.__rest(_a, ["providerId"]);
1486 return {
1487 providerId: providerId,
1488 uid: provider.rawId || '',
1489 displayName: provider.displayName || null,
1490 email: provider.email || null,
1491 phoneNumber: provider.phoneNumber || null,
1492 photoURL: provider.photoUrl || null
1493 };
1494 });
1495}
1496
1497/**
1498 * @license
1499 * Copyright 2020 Google LLC
1500 *
1501 * Licensed under the Apache License, Version 2.0 (the "License");
1502 * you may not use this file except in compliance with the License.
1503 * You may obtain a copy of the License at
1504 *
1505 * http://www.apache.org/licenses/LICENSE-2.0
1506 *
1507 * Unless required by applicable law or agreed to in writing, software
1508 * distributed under the License is distributed on an "AS IS" BASIS,
1509 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1510 * See the License for the specific language governing permissions and
1511 * limitations under the License.
1512 */
1513function requestStsToken(auth, refreshToken) {
1514 return tslib.__awaiter(this, void 0, void 0, function () {
1515 var response;
1516 var _this = this;
1517 return tslib.__generator(this, function (_a) {
1518 switch (_a.label) {
1519 case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return tslib.__awaiter(_this, void 0, void 0, function () {
1520 var body, _a, tokenApiHost, apiKey, url, headers;
1521 return tslib.__generator(this, function (_b) {
1522 switch (_b.label) {
1523 case 0:
1524 body = util.querystring({
1525 'grant_type': 'refresh_token',
1526 'refresh_token': refreshToken
1527 }).slice(1);
1528 _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
1529 url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* TOKEN */, "key=" + apiKey);
1530 return [4 /*yield*/, auth._getAdditionalHeaders()];
1531 case 1:
1532 headers = _b.sent();
1533 headers["Content-Type" /* CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
1534 return [2 /*return*/, FetchProvider.fetch()(url, {
1535 method: "POST" /* POST */,
1536 headers: headers,
1537 body: body
1538 })];
1539 }
1540 });
1541 }); })];
1542 case 1:
1543 response = _a.sent();
1544 // The response comes back in snake_case. Convert to camel:
1545 return [2 /*return*/, {
1546 accessToken: response.access_token,
1547 expiresIn: response.expires_in,
1548 refreshToken: response.refresh_token
1549 }];
1550 }
1551 });
1552 });
1553}
1554
1555/**
1556 * @license
1557 * Copyright 2020 Google LLC
1558 *
1559 * Licensed under the Apache License, Version 2.0 (the "License");
1560 * you may not use this file except in compliance with the License.
1561 * You may obtain a copy of the License at
1562 *
1563 * http://www.apache.org/licenses/LICENSE-2.0
1564 *
1565 * Unless required by applicable law or agreed to in writing, software
1566 * distributed under the License is distributed on an "AS IS" BASIS,
1567 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1568 * See the License for the specific language governing permissions and
1569 * limitations under the License.
1570 */
1571/**
1572 * We need to mark this class as internal explicitly to exclude it in the public typings, because
1573 * it references AuthInternal which has a circular dependency with UserInternal.
1574 *
1575 * @internal
1576 */
1577var StsTokenManager = /** @class */ (function () {
1578 function StsTokenManager() {
1579 this.refreshToken = null;
1580 this.accessToken = null;
1581 this.expirationTime = null;
1582 }
1583 Object.defineProperty(StsTokenManager.prototype, "isExpired", {
1584 get: function () {
1585 return (!this.expirationTime ||
1586 Date.now() > this.expirationTime - 30000 /* TOKEN_REFRESH */);
1587 },
1588 enumerable: false,
1589 configurable: true
1590 });
1591 StsTokenManager.prototype.updateFromServerResponse = function (response) {
1592 _assert(response.idToken, "internal-error" /* INTERNAL_ERROR */);
1593 _assert(typeof response.idToken !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1594 _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
1595 var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
1596 ? Number(response.expiresIn)
1597 : _tokenExpiresIn(response.idToken);
1598 this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
1599 };
1600 StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
1601 if (forceRefresh === void 0) { forceRefresh = false; }
1602 return tslib.__awaiter(this, void 0, void 0, function () {
1603 return tslib.__generator(this, function (_a) {
1604 switch (_a.label) {
1605 case 0:
1606 _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* TOKEN_EXPIRED */);
1607 if (!forceRefresh && this.accessToken && !this.isExpired) {
1608 return [2 /*return*/, this.accessToken];
1609 }
1610 if (!this.refreshToken) return [3 /*break*/, 2];
1611 return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
1612 case 1:
1613 _a.sent();
1614 return [2 /*return*/, this.accessToken];
1615 case 2: return [2 /*return*/, null];
1616 }
1617 });
1618 });
1619 };
1620 StsTokenManager.prototype.clearRefreshToken = function () {
1621 this.refreshToken = null;
1622 };
1623 StsTokenManager.prototype.refresh = function (auth, oldToken) {
1624 return tslib.__awaiter(this, void 0, void 0, function () {
1625 var _a, accessToken, refreshToken, expiresIn;
1626 return tslib.__generator(this, function (_b) {
1627 switch (_b.label) {
1628 case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
1629 case 1:
1630 _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
1631 this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
1632 return [2 /*return*/];
1633 }
1634 });
1635 });
1636 };
1637 StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
1638 this.refreshToken = refreshToken || null;
1639 this.accessToken = accessToken || null;
1640 this.expirationTime = Date.now() + expiresInSec * 1000;
1641 };
1642 StsTokenManager.fromJSON = function (appName, object) {
1643 var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
1644 var manager = new StsTokenManager();
1645 if (refreshToken) {
1646 _assert(typeof refreshToken === 'string', "internal-error" /* INTERNAL_ERROR */, {
1647 appName: appName
1648 });
1649 manager.refreshToken = refreshToken;
1650 }
1651 if (accessToken) {
1652 _assert(typeof accessToken === 'string', "internal-error" /* INTERNAL_ERROR */, {
1653 appName: appName
1654 });
1655 manager.accessToken = accessToken;
1656 }
1657 if (expirationTime) {
1658 _assert(typeof expirationTime === 'number', "internal-error" /* INTERNAL_ERROR */, {
1659 appName: appName
1660 });
1661 manager.expirationTime = expirationTime;
1662 }
1663 return manager;
1664 };
1665 StsTokenManager.prototype.toJSON = function () {
1666 return {
1667 refreshToken: this.refreshToken,
1668 accessToken: this.accessToken,
1669 expirationTime: this.expirationTime
1670 };
1671 };
1672 StsTokenManager.prototype._assign = function (stsTokenManager) {
1673 this.accessToken = stsTokenManager.accessToken;
1674 this.refreshToken = stsTokenManager.refreshToken;
1675 this.expirationTime = stsTokenManager.expirationTime;
1676 };
1677 StsTokenManager.prototype._clone = function () {
1678 return Object.assign(new StsTokenManager(), this.toJSON());
1679 };
1680 StsTokenManager.prototype._performRefresh = function () {
1681 return debugFail('not implemented');
1682 };
1683 return StsTokenManager;
1684}());
1685
1686/**
1687 * @license
1688 * Copyright 2020 Google LLC
1689 *
1690 * Licensed under the Apache License, Version 2.0 (the "License");
1691 * you may not use this file except in compliance with the License.
1692 * You may obtain a copy of the License at
1693 *
1694 * http://www.apache.org/licenses/LICENSE-2.0
1695 *
1696 * Unless required by applicable law or agreed to in writing, software
1697 * distributed under the License is distributed on an "AS IS" BASIS,
1698 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1699 * See the License for the specific language governing permissions and
1700 * limitations under the License.
1701 */
1702function assertStringOrUndefined(assertion, appName) {
1703 _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* INTERNAL_ERROR */, { appName: appName });
1704}
1705var UserImpl = /** @class */ (function () {
1706 function UserImpl(_a) {
1707 var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = tslib.__rest(_a, ["uid", "auth", "stsTokenManager"]);
1708 // For the user object, provider is always Firebase.
1709 this.providerId = "firebase" /* FIREBASE */;
1710 this.proactiveRefresh = new ProactiveRefresh(this);
1711 this.reloadUserInfo = null;
1712 this.reloadListener = null;
1713 this.uid = uid;
1714 this.auth = auth;
1715 this.stsTokenManager = stsTokenManager;
1716 this.accessToken = stsTokenManager.accessToken;
1717 this.displayName = opt.displayName || null;
1718 this.email = opt.email || null;
1719 this.emailVerified = opt.emailVerified || false;
1720 this.phoneNumber = opt.phoneNumber || null;
1721 this.photoURL = opt.photoURL || null;
1722 this.isAnonymous = opt.isAnonymous || false;
1723 this.tenantId = opt.tenantId || null;
1724 this.providerData = opt.providerData ? tslib.__spreadArray([], opt.providerData) : [];
1725 this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
1726 }
1727 UserImpl.prototype.getIdToken = function (forceRefresh) {
1728 return tslib.__awaiter(this, void 0, void 0, function () {
1729 var accessToken;
1730 return tslib.__generator(this, function (_a) {
1731 switch (_a.label) {
1732 case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
1733 case 1:
1734 accessToken = _a.sent();
1735 _assert(accessToken, this.auth, "internal-error" /* INTERNAL_ERROR */);
1736 if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
1737 this.accessToken = accessToken;
1738 return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
1739 case 2:
1740 _a.sent();
1741 this.auth._notifyListenersIfCurrent(this);
1742 _a.label = 3;
1743 case 3: return [2 /*return*/, accessToken];
1744 }
1745 });
1746 });
1747 };
1748 UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
1749 return getIdTokenResult(this, forceRefresh);
1750 };
1751 UserImpl.prototype.reload = function () {
1752 return reload(this);
1753 };
1754 UserImpl.prototype._assign = function (user) {
1755 if (this === user) {
1756 return;
1757 }
1758 _assert(this.uid === user.uid, this.auth, "internal-error" /* INTERNAL_ERROR */);
1759 this.displayName = user.displayName;
1760 this.photoURL = user.photoURL;
1761 this.email = user.email;
1762 this.emailVerified = user.emailVerified;
1763 this.phoneNumber = user.phoneNumber;
1764 this.isAnonymous = user.isAnonymous;
1765 this.tenantId = user.tenantId;
1766 this.providerData = user.providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); });
1767 this.metadata._copy(user.metadata);
1768 this.stsTokenManager._assign(user.stsTokenManager);
1769 };
1770 UserImpl.prototype._clone = function (auth) {
1771 return new UserImpl(tslib.__assign(tslib.__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
1772 };
1773 UserImpl.prototype._onReload = function (callback) {
1774 // There should only ever be one listener, and that is a single instance of MultiFactorUser
1775 _assert(!this.reloadListener, this.auth, "internal-error" /* INTERNAL_ERROR */);
1776 this.reloadListener = callback;
1777 if (this.reloadUserInfo) {
1778 this._notifyReloadListener(this.reloadUserInfo);
1779 this.reloadUserInfo = null;
1780 }
1781 };
1782 UserImpl.prototype._notifyReloadListener = function (userInfo) {
1783 if (this.reloadListener) {
1784 this.reloadListener(userInfo);
1785 }
1786 else {
1787 // If no listener is subscribed yet, save the result so it's available when they do subscribe
1788 this.reloadUserInfo = userInfo;
1789 }
1790 };
1791 UserImpl.prototype._startProactiveRefresh = function () {
1792 this.proactiveRefresh._start();
1793 };
1794 UserImpl.prototype._stopProactiveRefresh = function () {
1795 this.proactiveRefresh._stop();
1796 };
1797 UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
1798 if (reload === void 0) { reload = false; }
1799 return tslib.__awaiter(this, void 0, void 0, function () {
1800 var tokensRefreshed;
1801 return tslib.__generator(this, function (_a) {
1802 switch (_a.label) {
1803 case 0:
1804 tokensRefreshed = false;
1805 if (response.idToken &&
1806 response.idToken !== this.stsTokenManager.accessToken) {
1807 this.stsTokenManager.updateFromServerResponse(response);
1808 tokensRefreshed = true;
1809 }
1810 if (!reload) return [3 /*break*/, 2];
1811 return [4 /*yield*/, _reloadWithoutSaving(this)];
1812 case 1:
1813 _a.sent();
1814 _a.label = 2;
1815 case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
1816 case 3:
1817 _a.sent();
1818 if (tokensRefreshed) {
1819 this.auth._notifyListenersIfCurrent(this);
1820 }
1821 return [2 /*return*/];
1822 }
1823 });
1824 });
1825 };
1826 UserImpl.prototype.delete = function () {
1827 return tslib.__awaiter(this, void 0, void 0, function () {
1828 var idToken;
1829 return tslib.__generator(this, function (_a) {
1830 switch (_a.label) {
1831 case 0: return [4 /*yield*/, this.getIdToken()];
1832 case 1:
1833 idToken = _a.sent();
1834 return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
1835 case 2:
1836 _a.sent();
1837 this.stsTokenManager.clearRefreshToken();
1838 // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
1839 // cancels pending actions...
1840 return [2 /*return*/, this.auth.signOut()];
1841 }
1842 });
1843 });
1844 };
1845 UserImpl.prototype.toJSON = function () {
1846 return tslib.__assign(tslib.__assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
1847 // Redirect event ID must be maintained in case there is a pending
1848 // redirect event.
1849 _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
1850 // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
1851 apiKey: this.auth.config.apiKey, appName: this.auth.name });
1852 };
1853 Object.defineProperty(UserImpl.prototype, "refreshToken", {
1854 get: function () {
1855 return this.stsTokenManager.refreshToken || '';
1856 },
1857 enumerable: false,
1858 configurable: true
1859 });
1860 UserImpl._fromJSON = function (auth, object) {
1861 var _a, _b, _c, _d, _e, _f, _g, _h;
1862 var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
1863 var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
1864 var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
1865 var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
1866 var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
1867 var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
1868 var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
1869 var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
1870 var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
1871 _assert(uid && plainObjectTokenManager, auth, "internal-error" /* INTERNAL_ERROR */);
1872 var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
1873 _assert(typeof uid === 'string', auth, "internal-error" /* INTERNAL_ERROR */);
1874 assertStringOrUndefined(displayName, auth.name);
1875 assertStringOrUndefined(email, auth.name);
1876 _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* INTERNAL_ERROR */);
1877 _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* INTERNAL_ERROR */);
1878 assertStringOrUndefined(phoneNumber, auth.name);
1879 assertStringOrUndefined(photoURL, auth.name);
1880 assertStringOrUndefined(tenantId, auth.name);
1881 assertStringOrUndefined(_redirectEventId, auth.name);
1882 assertStringOrUndefined(createdAt, auth.name);
1883 assertStringOrUndefined(lastLoginAt, auth.name);
1884 var user = new UserImpl({
1885 uid: uid,
1886 auth: auth,
1887 email: email,
1888 emailVerified: emailVerified,
1889 displayName: displayName,
1890 isAnonymous: isAnonymous,
1891 photoURL: photoURL,
1892 phoneNumber: phoneNumber,
1893 tenantId: tenantId,
1894 stsTokenManager: stsTokenManager,
1895 createdAt: createdAt,
1896 lastLoginAt: lastLoginAt
1897 });
1898 if (providerData && Array.isArray(providerData)) {
1899 user.providerData = providerData.map(function (userInfo) { return (tslib.__assign({}, userInfo)); });
1900 }
1901 if (_redirectEventId) {
1902 user._redirectEventId = _redirectEventId;
1903 }
1904 return user;
1905 };
1906 /**
1907 * Initialize a User from an idToken server response
1908 * @param auth
1909 * @param idTokenResponse
1910 */
1911 UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
1912 if (isAnonymous === void 0) { isAnonymous = false; }
1913 return tslib.__awaiter(this, void 0, void 0, function () {
1914 var stsTokenManager, user;
1915 return tslib.__generator(this, function (_a) {
1916 switch (_a.label) {
1917 case 0:
1918 stsTokenManager = new StsTokenManager();
1919 stsTokenManager.updateFromServerResponse(idTokenResponse);
1920 user = new UserImpl({
1921 uid: idTokenResponse.localId,
1922 auth: auth,
1923 stsTokenManager: stsTokenManager,
1924 isAnonymous: isAnonymous
1925 });
1926 // Updates the user info and data and resolves with a user instance.
1927 return [4 /*yield*/, _reloadWithoutSaving(user)];
1928 case 1:
1929 // Updates the user info and data and resolves with a user instance.
1930 _a.sent();
1931 return [2 /*return*/, user];
1932 }
1933 });
1934 });
1935 };
1936 return UserImpl;
1937}());
1938
1939/**
1940 * @license
1941 * Copyright 2019 Google LLC
1942 *
1943 * Licensed under the Apache License, Version 2.0 (the "License");
1944 * you may not use this file except in compliance with the License.
1945 * You may obtain a copy of the License at
1946 *
1947 * http://www.apache.org/licenses/LICENSE-2.0
1948 *
1949 * Unless required by applicable law or agreed to in writing, software
1950 * distributed under the License is distributed on an "AS IS" BASIS,
1951 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1952 * See the License for the specific language governing permissions and
1953 * limitations under the License.
1954 */
1955var InMemoryPersistence = /** @class */ (function () {
1956 function InMemoryPersistence() {
1957 this.type = "NONE" /* NONE */;
1958 this.storage = {};
1959 }
1960 InMemoryPersistence.prototype._isAvailable = function () {
1961 return tslib.__awaiter(this, void 0, void 0, function () {
1962 return tslib.__generator(this, function (_a) {
1963 return [2 /*return*/, true];
1964 });
1965 });
1966 };
1967 InMemoryPersistence.prototype._set = function (key, value) {
1968 return tslib.__awaiter(this, void 0, void 0, function () {
1969 return tslib.__generator(this, function (_a) {
1970 this.storage[key] = value;
1971 return [2 /*return*/];
1972 });
1973 });
1974 };
1975 InMemoryPersistence.prototype._get = function (key) {
1976 return tslib.__awaiter(this, void 0, void 0, function () {
1977 var value;
1978 return tslib.__generator(this, function (_a) {
1979 value = this.storage[key];
1980 return [2 /*return*/, value === undefined ? null : value];
1981 });
1982 });
1983 };
1984 InMemoryPersistence.prototype._remove = function (key) {
1985 return tslib.__awaiter(this, void 0, void 0, function () {
1986 return tslib.__generator(this, function (_a) {
1987 delete this.storage[key];
1988 return [2 /*return*/];
1989 });
1990 });
1991 };
1992 InMemoryPersistence.prototype._addListener = function (_key, _listener) {
1993 // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
1994 return;
1995 };
1996 InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
1997 // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
1998 return;
1999 };
2000 InMemoryPersistence.type = 'NONE';
2001 return InMemoryPersistence;
2002}());
2003/**
2004 * An implementation of {@link Persistence} of type 'NONE'.
2005 *
2006 * @public
2007 */
2008var inMemoryPersistence = InMemoryPersistence;
2009
2010/**
2011 * @license
2012 * Copyright 2019 Google LLC
2013 *
2014 * Licensed under the Apache License, Version 2.0 (the "License");
2015 * you may not use this file except in compliance with the License.
2016 * You may obtain a copy of the License at
2017 *
2018 * http://www.apache.org/licenses/LICENSE-2.0
2019 *
2020 * Unless required by applicable law or agreed to in writing, software
2021 * distributed under the License is distributed on an "AS IS" BASIS,
2022 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2023 * See the License for the specific language governing permissions and
2024 * limitations under the License.
2025 */
2026function _persistenceKeyName(key, apiKey, appName) {
2027 return "firebase" /* PERSISTENCE */ + ":" + key + ":" + apiKey + ":" + appName;
2028}
2029var PersistenceUserManager = /** @class */ (function () {
2030 function PersistenceUserManager(persistence, auth, userKey) {
2031 this.persistence = persistence;
2032 this.auth = auth;
2033 this.userKey = userKey;
2034 var _a = this.auth, config = _a.config, name = _a.name;
2035 this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
2036 this.fullPersistenceKey = _persistenceKeyName("persistence" /* PERSISTENCE_USER */, config.apiKey, name);
2037 this.boundEventHandler = auth._onStorageEvent.bind(auth);
2038 this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
2039 }
2040 PersistenceUserManager.prototype.setCurrentUser = function (user) {
2041 return this.persistence._set(this.fullUserKey, user.toJSON());
2042 };
2043 PersistenceUserManager.prototype.getCurrentUser = function () {
2044 return tslib.__awaiter(this, void 0, void 0, function () {
2045 var blob;
2046 return tslib.__generator(this, function (_a) {
2047 switch (_a.label) {
2048 case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
2049 case 1:
2050 blob = _a.sent();
2051 return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
2052 }
2053 });
2054 });
2055 };
2056 PersistenceUserManager.prototype.removeCurrentUser = function () {
2057 return this.persistence._remove(this.fullUserKey);
2058 };
2059 PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
2060 return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
2061 };
2062 PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
2063 return tslib.__awaiter(this, void 0, void 0, function () {
2064 var currentUser;
2065 return tslib.__generator(this, function (_a) {
2066 switch (_a.label) {
2067 case 0:
2068 if (this.persistence === newPersistence) {
2069 return [2 /*return*/];
2070 }
2071 return [4 /*yield*/, this.getCurrentUser()];
2072 case 1:
2073 currentUser = _a.sent();
2074 return [4 /*yield*/, this.removeCurrentUser()];
2075 case 2:
2076 _a.sent();
2077 this.persistence = newPersistence;
2078 if (currentUser) {
2079 return [2 /*return*/, this.setCurrentUser(currentUser)];
2080 }
2081 return [2 /*return*/];
2082 }
2083 });
2084 });
2085 };
2086 PersistenceUserManager.prototype.delete = function () {
2087 this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
2088 };
2089 PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
2090 if (userKey === void 0) { userKey = "authUser" /* AUTH_USER */; }
2091 return tslib.__awaiter(this, void 0, void 0, function () {
2092 var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
2093 var _this = this;
2094 return tslib.__generator(this, function (_b) {
2095 switch (_b.label) {
2096 case 0:
2097 if (!persistenceHierarchy.length) {
2098 return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
2099 }
2100 return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return tslib.__awaiter(_this, void 0, void 0, function () {
2101 return tslib.__generator(this, function (_a) {
2102 switch (_a.label) {
2103 case 0: return [4 /*yield*/, persistence._isAvailable()];
2104 case 1:
2105 if (_a.sent()) {
2106 return [2 /*return*/, persistence];
2107 }
2108 return [2 /*return*/, undefined];
2109 }
2110 });
2111 }); }))];
2112 case 1:
2113 availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
2114 selectedPersistence = availablePersistences[0] ||
2115 _getInstance(inMemoryPersistence);
2116 key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
2117 userToMigrate = null;
2118 _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
2119 _b.label = 2;
2120 case 2:
2121 if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
2122 persistence = persistenceHierarchy_1[_i];
2123 _b.label = 3;
2124 case 3:
2125 _b.trys.push([3, 5, , 6]);
2126 return [4 /*yield*/, persistence._get(key)];
2127 case 4:
2128 blob = _b.sent();
2129 if (blob) {
2130 user = UserImpl._fromJSON(auth, blob);
2131 if (persistence !== selectedPersistence) {
2132 userToMigrate = user;
2133 }
2134 selectedPersistence = persistence;
2135 return [3 /*break*/, 7];
2136 }
2137 return [3 /*break*/, 6];
2138 case 5:
2139 _b.sent();
2140 return [3 /*break*/, 6];
2141 case 6:
2142 _i++;
2143 return [3 /*break*/, 2];
2144 case 7:
2145 migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
2146 // If the persistence does _not_ allow migration, just finish off here
2147 if (!selectedPersistence._shouldAllowMigration ||
2148 !migrationHierarchy.length) {
2149 return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
2150 }
2151 selectedPersistence = migrationHierarchy[0];
2152 if (!userToMigrate) return [3 /*break*/, 9];
2153 // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
2154 // we'll just let it bubble to surface the error.
2155 return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
2156 case 8:
2157 // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
2158 // we'll just let it bubble to surface the error.
2159 _b.sent();
2160 _b.label = 9;
2161 case 9:
2162 // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
2163 // such as users getting stuck with a previous account after signing out and refreshing the tab.
2164 return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return tslib.__awaiter(_this, void 0, void 0, function () {
2165 return tslib.__generator(this, function (_b) {
2166 switch (_b.label) {
2167 case 0:
2168 if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
2169 _b.label = 1;
2170 case 1:
2171 _b.trys.push([1, 3, , 4]);
2172 return [4 /*yield*/, persistence._remove(key)];
2173 case 2:
2174 _b.sent();
2175 return [3 /*break*/, 4];
2176 case 3:
2177 _b.sent();
2178 return [3 /*break*/, 4];
2179 case 4: return [2 /*return*/];
2180 }
2181 });
2182 }); }))];
2183 case 10:
2184 // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
2185 // such as users getting stuck with a previous account after signing out and refreshing the tab.
2186 _b.sent();
2187 return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
2188 }
2189 });
2190 });
2191 };
2192 return PersistenceUserManager;
2193}());
2194
2195/**
2196 * @license
2197 * Copyright 2020 Google LLC
2198 *
2199 * Licensed under the Apache License, Version 2.0 (the "License");
2200 * you may not use this file except in compliance with the License.
2201 * You may obtain a copy of the License at
2202 *
2203 * http://www.apache.org/licenses/LICENSE-2.0
2204 *
2205 * Unless required by applicable law or agreed to in writing, software
2206 * distributed under the License is distributed on an "AS IS" BASIS,
2207 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2208 * See the License for the specific language governing permissions and
2209 * limitations under the License.
2210 */
2211/**
2212 * Determine the browser for the purposes of reporting usage to the API
2213 */
2214function _getBrowserName(userAgent) {
2215 var ua = userAgent.toLowerCase();
2216 if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
2217 return "Opera" /* OPERA */;
2218 }
2219 else if (_isIEMobile(ua)) {
2220 // Windows phone IEMobile browser.
2221 return "IEMobile" /* IEMOBILE */;
2222 }
2223 else if (ua.includes('msie') || ua.includes('trident/')) {
2224 return "IE" /* IE */;
2225 }
2226 else if (ua.includes('edge/')) {
2227 return "Edge" /* EDGE */;
2228 }
2229 else if (_isFirefox(ua)) {
2230 return "Firefox" /* FIREFOX */;
2231 }
2232 else if (ua.includes('silk/')) {
2233 return "Silk" /* SILK */;
2234 }
2235 else if (_isBlackBerry(ua)) {
2236 // Blackberry browser.
2237 return "Blackberry" /* BLACKBERRY */;
2238 }
2239 else if (_isWebOS(ua)) {
2240 // WebOS default browser.
2241 return "Webos" /* WEBOS */;
2242 }
2243 else if (_isSafari(ua)) {
2244 return "Safari" /* SAFARI */;
2245 }
2246 else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
2247 !ua.includes('edge/')) {
2248 return "Chrome" /* CHROME */;
2249 }
2250 else if (_isAndroid(ua)) {
2251 // Android stock browser.
2252 return "Android" /* ANDROID */;
2253 }
2254 else {
2255 // Most modern browsers have name/version at end of user agent string.
2256 var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
2257 var matches = userAgent.match(re);
2258 if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
2259 return matches[1];
2260 }
2261 }
2262 return "Other" /* OTHER */;
2263}
2264function _isFirefox(ua) {
2265 if (ua === void 0) { ua = util.getUA(); }
2266 return /firefox\//i.test(ua);
2267}
2268function _isSafari(userAgent) {
2269 if (userAgent === void 0) { userAgent = util.getUA(); }
2270 var ua = userAgent.toLowerCase();
2271 return (ua.includes('safari/') &&
2272 !ua.includes('chrome/') &&
2273 !ua.includes('crios/') &&
2274 !ua.includes('android'));
2275}
2276function _isChromeIOS(ua) {
2277 if (ua === void 0) { ua = util.getUA(); }
2278 return /crios\//i.test(ua);
2279}
2280function _isIEMobile(ua) {
2281 if (ua === void 0) { ua = util.getUA(); }
2282 return /iemobile/i.test(ua);
2283}
2284function _isAndroid(ua) {
2285 if (ua === void 0) { ua = util.getUA(); }
2286 return /android/i.test(ua);
2287}
2288function _isBlackBerry(ua) {
2289 if (ua === void 0) { ua = util.getUA(); }
2290 return /blackberry/i.test(ua);
2291}
2292function _isWebOS(ua) {
2293 if (ua === void 0) { ua = util.getUA(); }
2294 return /webos/i.test(ua);
2295}
2296function _isIOS(ua) {
2297 if (ua === void 0) { ua = util.getUA(); }
2298 return /iphone|ipad|ipod/i.test(ua) ||
2299 (/macintosh/i.test(ua) && /mobile/i.test(ua));
2300}
2301function _isIOS7Or8(ua) {
2302 if (ua === void 0) { ua = util.getUA(); }
2303 return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
2304 /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
2305}
2306function _isIOSStandalone(ua) {
2307 var _a;
2308 if (ua === void 0) { ua = util.getUA(); }
2309 return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
2310}
2311function _isIE10() {
2312 return util.isIE() && document.documentMode === 10;
2313}
2314function _isMobileBrowser(ua) {
2315 if (ua === void 0) { ua = util.getUA(); }
2316 // TODO: implement getBrowserName equivalent for OS.
2317 return (_isIOS(ua) ||
2318 _isAndroid(ua) ||
2319 _isWebOS(ua) ||
2320 _isBlackBerry(ua) ||
2321 /windows phone/i.test(ua) ||
2322 _isIEMobile(ua));
2323}
2324function _isIframe() {
2325 try {
2326 // Check that the current window is not the top window.
2327 // If so, return true.
2328 return !!(window && window !== window.top);
2329 }
2330 catch (e) {
2331 return false;
2332 }
2333}
2334
2335/**
2336 * @license
2337 * Copyright 2020 Google LLC
2338 *
2339 * Licensed under the Apache License, Version 2.0 (the "License");
2340 * you may not use this file except in compliance with the License.
2341 * You may obtain a copy of the License at
2342 *
2343 * http://www.apache.org/licenses/LICENSE-2.0
2344 *
2345 * Unless required by applicable law or agreed to in writing, software
2346 * distributed under the License is distributed on an "AS IS" BASIS,
2347 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2348 * See the License for the specific language governing permissions and
2349 * limitations under the License.
2350 */
2351/*
2352 * Determine the SDK version string
2353 */
2354function _getClientVersion(clientPlatform, frameworks) {
2355 if (frameworks === void 0) { frameworks = []; }
2356 var reportedPlatform;
2357 switch (clientPlatform) {
2358 case "Browser" /* BROWSER */:
2359 // In a browser environment, report the browser name.
2360 reportedPlatform = _getBrowserName(util.getUA());
2361 break;
2362 case "Worker" /* WORKER */:
2363 // Technically a worker runs from a browser but we need to differentiate a
2364 // worker from a browser.
2365 // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
2366 reportedPlatform = _getBrowserName(util.getUA()) + "-" + clientPlatform;
2367 break;
2368 default:
2369 reportedPlatform = clientPlatform;
2370 }
2371 var reportedFrameworks = frameworks.length
2372 ? frameworks.join(',')
2373 : 'FirebaseCore-web'; /* default value if no other framework is used */
2374 return reportedPlatform + "/" + "JsCore" /* CORE */ + "/" + app.SDK_VERSION + "/" + reportedFrameworks;
2375}
2376
2377/**
2378 * @license
2379 * Copyright 2022 Google LLC
2380 *
2381 * Licensed under the Apache License, Version 2.0 (the "License");
2382 * you may not use this file except in compliance with the License.
2383 * You may obtain a copy of the License at
2384 *
2385 * http://www.apache.org/licenses/LICENSE-2.0
2386 *
2387 * Unless required by applicable law or agreed to in writing, software
2388 * distributed under the License is distributed on an "AS IS" BASIS,
2389 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2390 * See the License for the specific language governing permissions and
2391 * limitations under the License.
2392 */
2393var AuthMiddlewareQueue = /** @class */ (function () {
2394 function AuthMiddlewareQueue(auth) {
2395 this.auth = auth;
2396 this.queue = [];
2397 }
2398 AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
2399 var _this = this;
2400 // The callback could be sync or async. Wrap it into a
2401 // function that is always async.
2402 var wrappedCallback = function (user) { return new Promise(function (resolve, reject) {
2403 try {
2404 var result = callback(user);
2405 // Either resolve with existing promise or wrap a non-promise
2406 // return value into a promise.
2407 resolve(result);
2408 }
2409 catch (e) {
2410 // Sync callback throws.
2411 reject(e);
2412 }
2413 }); };
2414 // Attach the onAbort if present
2415 wrappedCallback.onAbort = onAbort;
2416 this.queue.push(wrappedCallback);
2417 var index = this.queue.length - 1;
2418 return function () {
2419 // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
2420 // indexing of other elements.
2421 _this.queue[index] = function () { return Promise.resolve(); };
2422 };
2423 };
2424 AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
2425 var _a;
2426 return tslib.__awaiter(this, void 0, void 0, function () {
2427 var onAbortStack, _i, _b, beforeStateCallback, e_1, _c, onAbortStack_1, onAbort;
2428 return tslib.__generator(this, function (_d) {
2429 switch (_d.label) {
2430 case 0:
2431 if (this.auth.currentUser === nextUser) {
2432 return [2 /*return*/];
2433 }
2434 onAbortStack = [];
2435 _d.label = 1;
2436 case 1:
2437 _d.trys.push([1, 6, , 7]);
2438 _i = 0, _b = this.queue;
2439 _d.label = 2;
2440 case 2:
2441 if (!(_i < _b.length)) return [3 /*break*/, 5];
2442 beforeStateCallback = _b[_i];
2443 return [4 /*yield*/, beforeStateCallback(nextUser)];
2444 case 3:
2445 _d.sent();
2446 // Only push the onAbort if the callback succeeds
2447 if (beforeStateCallback.onAbort) {
2448 onAbortStack.push(beforeStateCallback.onAbort);
2449 }
2450 _d.label = 4;
2451 case 4:
2452 _i++;
2453 return [3 /*break*/, 2];
2454 case 5: return [3 /*break*/, 7];
2455 case 6:
2456 e_1 = _d.sent();
2457 // Run all onAbort, with separate try/catch to ignore any errors and
2458 // continue
2459 onAbortStack.reverse();
2460 for (_c = 0, onAbortStack_1 = onAbortStack; _c < onAbortStack_1.length; _c++) {
2461 onAbort = onAbortStack_1[_c];
2462 try {
2463 onAbort();
2464 }
2465 catch (_) { /* swallow error */ }
2466 }
2467 throw this.auth._errorFactory.create("login-blocked" /* LOGIN_BLOCKED */, { originalMessage: (_a = e_1) === null || _a === void 0 ? void 0 : _a.message });
2468 case 7: return [2 /*return*/];
2469 }
2470 });
2471 });
2472 };
2473 return AuthMiddlewareQueue;
2474}());
2475
2476/**
2477 * @license
2478 * Copyright 2020 Google LLC
2479 *
2480 * Licensed under the Apache License, Version 2.0 (the "License");
2481 * you may not use this file except in compliance with the License.
2482 * You may obtain a copy of the License at
2483 *
2484 * http://www.apache.org/licenses/LICENSE-2.0
2485 *
2486 * Unless required by applicable law or agreed to in writing, software
2487 * distributed under the License is distributed on an "AS IS" BASIS,
2488 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2489 * See the License for the specific language governing permissions and
2490 * limitations under the License.
2491 */
2492var AuthImpl = /** @class */ (function () {
2493 function AuthImpl(app, heartbeatServiceProvider, config) {
2494 this.app = app;
2495 this.heartbeatServiceProvider = heartbeatServiceProvider;
2496 this.config = config;
2497 this.currentUser = null;
2498 this.emulatorConfig = null;
2499 this.operations = Promise.resolve();
2500 this.authStateSubscription = new Subscription(this);
2501 this.idTokenSubscription = new Subscription(this);
2502 this.beforeStateQueue = new AuthMiddlewareQueue(this);
2503 this.redirectUser = null;
2504 this.isProactiveRefreshEnabled = false;
2505 // Any network calls will set this to true and prevent subsequent emulator
2506 // initialization
2507 this._canInitEmulator = true;
2508 this._isInitialized = false;
2509 this._deleted = false;
2510 this._initializationPromise = null;
2511 this._popupRedirectResolver = null;
2512 this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
2513 // Tracks the last notified UID for state change listeners to prevent
2514 // repeated calls to the callbacks. Undefined means it's never been
2515 // called, whereas null means it's been called with a signed out user
2516 this.lastNotifiedUid = undefined;
2517 this.languageCode = null;
2518 this.tenantId = null;
2519 this.settings = { appVerificationDisabledForTesting: false };
2520 this.frameworks = [];
2521 this.name = app.name;
2522 this.clientVersion = config.sdkClientVersion;
2523 }
2524 AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
2525 var _this = this;
2526 if (popupRedirectResolver) {
2527 this._popupRedirectResolver = _getInstance(popupRedirectResolver);
2528 }
2529 // Have to check for app deletion throughout initialization (after each
2530 // promise resolution)
2531 this._initializationPromise = this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
2532 var _a;
2533 var _b, _c;
2534 return tslib.__generator(this, function (_d) {
2535 switch (_d.label) {
2536 case 0:
2537 if (this._deleted) {
2538 return [2 /*return*/];
2539 }
2540 _a = this;
2541 return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
2542 case 1:
2543 _a.persistenceManager = _d.sent();
2544 if (this._deleted) {
2545 return [2 /*return*/];
2546 }
2547 if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
2548 _d.label = 2;
2549 case 2:
2550 _d.trys.push([2, 4, , 5]);
2551 return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
2552 case 3:
2553 _d.sent();
2554 return [3 /*break*/, 5];
2555 case 4:
2556 _d.sent();
2557 return [3 /*break*/, 5];
2558 case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
2559 case 6:
2560 _d.sent();
2561 this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
2562 if (this._deleted) {
2563 return [2 /*return*/];
2564 }
2565 this._isInitialized = true;
2566 return [2 /*return*/];
2567 }
2568 });
2569 }); });
2570 return this._initializationPromise;
2571 };
2572 /**
2573 * If the persistence is changed in another window, the user manager will let us know
2574 */
2575 AuthImpl.prototype._onStorageEvent = function () {
2576 return tslib.__awaiter(this, void 0, void 0, function () {
2577 var user;
2578 return tslib.__generator(this, function (_a) {
2579 switch (_a.label) {
2580 case 0:
2581 if (this._deleted) {
2582 return [2 /*return*/];
2583 }
2584 return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
2585 case 1:
2586 user = _a.sent();
2587 if (!this.currentUser && !user) {
2588 // No change, do nothing (was signed out and remained signed out).
2589 return [2 /*return*/];
2590 }
2591 if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
2592 // Data update, simply copy data changes.
2593 this._currentUser._assign(user);
2594 // If tokens changed from previous user tokens, this will trigger
2595 // notifyAuthListeners_.
2596 return [4 /*yield*/, this.currentUser.getIdToken()];
2597 case 2:
2598 // If tokens changed from previous user tokens, this will trigger
2599 // notifyAuthListeners_.
2600 _a.sent();
2601 return [2 /*return*/];
2602 case 3:
2603 // Update current Auth state. Either a new login or logout.
2604 // Skip blocking callbacks, they should not apply to a change in another tab.
2605 return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
2606 case 4:
2607 // Update current Auth state. Either a new login or logout.
2608 // Skip blocking callbacks, they should not apply to a change in another tab.
2609 _a.sent();
2610 return [2 /*return*/];
2611 }
2612 });
2613 });
2614 };
2615 AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
2616 var _a;
2617 return tslib.__awaiter(this, void 0, void 0, function () {
2618 var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
2619 return tslib.__generator(this, function (_b) {
2620 switch (_b.label) {
2621 case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
2622 case 1:
2623 previouslyStoredUser = (_b.sent());
2624 futureCurrentUser = previouslyStoredUser;
2625 needsTocheckMiddleware = false;
2626 if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
2627 return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
2628 case 2:
2629 _b.sent();
2630 redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
2631 storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
2632 return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
2633 case 3:
2634 result = _b.sent();
2635 // If the stored user (i.e. the old "currentUser") has a redirectId that
2636 // matches the redirect user, then we want to initially sign in with the
2637 // new user object from result.
2638 // TODO(samgho): More thoroughly test all of this
2639 if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
2640 (result === null || result === void 0 ? void 0 : result.user)) {
2641 futureCurrentUser = result.user;
2642 needsTocheckMiddleware = true;
2643 }
2644 _b.label = 4;
2645 case 4:
2646 // If no user in persistence, there is no current user. Set to null.
2647 if (!futureCurrentUser) {
2648 return [2 /*return*/, this.directlySetCurrentUser(null)];
2649 }
2650 if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
2651 if (!needsTocheckMiddleware) return [3 /*break*/, 8];
2652 _b.label = 5;
2653 case 5:
2654 _b.trys.push([5, 7, , 8]);
2655 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
2656 case 6:
2657 _b.sent();
2658 return [3 /*break*/, 8];
2659 case 7:
2660 e_2 = _b.sent();
2661 futureCurrentUser = previouslyStoredUser;
2662 // We know this is available since the bit is only set when the
2663 // resolver is available
2664 this._popupRedirectResolver._overrideRedirectResult(this, function () { return Promise.reject(e_2); });
2665 return [3 /*break*/, 8];
2666 case 8:
2667 if (futureCurrentUser) {
2668 return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
2669 }
2670 else {
2671 return [2 /*return*/, this.directlySetCurrentUser(null)];
2672 }
2673 case 9:
2674 _assert(this._popupRedirectResolver, this, "argument-error" /* ARGUMENT_ERROR */);
2675 return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
2676 case 10:
2677 _b.sent();
2678 // If the redirect user's event ID matches the current user's event ID,
2679 // DO NOT reload the current user, otherwise they'll be cleared from storage.
2680 // This is important for the reauthenticateWithRedirect() flow.
2681 if (this.redirectUser &&
2682 this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
2683 return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
2684 }
2685 return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
2686 }
2687 });
2688 });
2689 };
2690 AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
2691 return tslib.__awaiter(this, void 0, void 0, function () {
2692 var result;
2693 return tslib.__generator(this, function (_a) {
2694 switch (_a.label) {
2695 case 0:
2696 result = null;
2697 _a.label = 1;
2698 case 1:
2699 _a.trys.push([1, 3, , 5]);
2700 return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
2701 case 2:
2702 // We know this._popupRedirectResolver is set since redirectResolver
2703 // is passed in. The _completeRedirectFn expects the unwrapped extern.
2704 result = _a.sent();
2705 return [3 /*break*/, 5];
2706 case 3:
2707 _a.sent();
2708 // Swallow any errors here; the code can retrieve them in
2709 // getRedirectResult().
2710 return [4 /*yield*/, this._setRedirectUser(null)];
2711 case 4:
2712 // Swallow any errors here; the code can retrieve them in
2713 // getRedirectResult().
2714 _a.sent();
2715 return [3 /*break*/, 5];
2716 case 5: return [2 /*return*/, result];
2717 }
2718 });
2719 });
2720 };
2721 AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
2722 var _a;
2723 return tslib.__awaiter(this, void 0, void 0, function () {
2724 var e_4;
2725 return tslib.__generator(this, function (_b) {
2726 switch (_b.label) {
2727 case 0:
2728 _b.trys.push([0, 2, , 3]);
2729 return [4 /*yield*/, _reloadWithoutSaving(user)];
2730 case 1:
2731 _b.sent();
2732 return [3 /*break*/, 3];
2733 case 2:
2734 e_4 = _b.sent();
2735 if (((_a = e_4) === null || _a === void 0 ? void 0 : _a.code) !== "auth/" + "network-request-failed" /* NETWORK_REQUEST_FAILED */) {
2736 // Something's wrong with the user's token. Log them out and remove
2737 // them from storage
2738 return [2 /*return*/, this.directlySetCurrentUser(null)];
2739 }
2740 return [3 /*break*/, 3];
2741 case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
2742 }
2743 });
2744 });
2745 };
2746 AuthImpl.prototype.useDeviceLanguage = function () {
2747 this.languageCode = _getUserLanguage();
2748 };
2749 AuthImpl.prototype._delete = function () {
2750 return tslib.__awaiter(this, void 0, void 0, function () {
2751 return tslib.__generator(this, function (_a) {
2752 this._deleted = true;
2753 return [2 /*return*/];
2754 });
2755 });
2756 };
2757 AuthImpl.prototype.updateCurrentUser = function (userExtern) {
2758 return tslib.__awaiter(this, void 0, void 0, function () {
2759 var user;
2760 return tslib.__generator(this, function (_a) {
2761 user = userExtern
2762 ? util.getModularInstance(userExtern)
2763 : null;
2764 if (user) {
2765 _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* INVALID_AUTH */);
2766 }
2767 return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
2768 });
2769 });
2770 };
2771 AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
2772 if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
2773 return tslib.__awaiter(this, void 0, void 0, function () {
2774 var _this = this;
2775 return tslib.__generator(this, function (_a) {
2776 switch (_a.label) {
2777 case 0:
2778 if (this._deleted) {
2779 return [2 /*return*/];
2780 }
2781 if (user) {
2782 _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* TENANT_ID_MISMATCH */);
2783 }
2784 if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
2785 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
2786 case 1:
2787 _a.sent();
2788 _a.label = 2;
2789 case 2: return [2 /*return*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
2790 return tslib.__generator(this, function (_a) {
2791 switch (_a.label) {
2792 case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
2793 case 1:
2794 _a.sent();
2795 this.notifyAuthListeners();
2796 return [2 /*return*/];
2797 }
2798 });
2799 }); })];
2800 }
2801 });
2802 });
2803 };
2804 AuthImpl.prototype.signOut = function () {
2805 return tslib.__awaiter(this, void 0, void 0, function () {
2806 return tslib.__generator(this, function (_a) {
2807 switch (_a.label) {
2808 case 0:
2809 // Run first, to block _setRedirectUser() if any callbacks fail.
2810 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
2811 case 1:
2812 // Run first, to block _setRedirectUser() if any callbacks fail.
2813 _a.sent();
2814 if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
2815 return [4 /*yield*/, this._setRedirectUser(null)];
2816 case 2:
2817 _a.sent();
2818 _a.label = 3;
2819 case 3:
2820 // Prevent callbacks from being called again in _updateCurrentUser, as
2821 // they were already called in the first line.
2822 return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
2823 }
2824 });
2825 });
2826 };
2827 AuthImpl.prototype.setPersistence = function (persistence) {
2828 var _this = this;
2829 return this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
2830 return tslib.__generator(this, function (_a) {
2831 switch (_a.label) {
2832 case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
2833 case 1:
2834 _a.sent();
2835 return [2 /*return*/];
2836 }
2837 });
2838 }); });
2839 };
2840 AuthImpl.prototype._getPersistence = function () {
2841 return this.assertedPersistence.persistence.type;
2842 };
2843 AuthImpl.prototype._updateErrorMap = function (errorMap) {
2844 this._errorFactory = new util.ErrorFactory('auth', 'Firebase', errorMap());
2845 };
2846 AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
2847 return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
2848 };
2849 AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
2850 return this.beforeStateQueue.pushCallback(callback, onAbort);
2851 };
2852 AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
2853 return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
2854 };
2855 AuthImpl.prototype.toJSON = function () {
2856 var _a;
2857 return {
2858 apiKey: this.config.apiKey,
2859 authDomain: this.config.authDomain,
2860 appName: this.name,
2861 currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
2862 };
2863 };
2864 AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
2865 return tslib.__awaiter(this, void 0, void 0, function () {
2866 var redirectManager;
2867 return tslib.__generator(this, function (_a) {
2868 switch (_a.label) {
2869 case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
2870 case 1:
2871 redirectManager = _a.sent();
2872 return [2 /*return*/, user === null
2873 ? redirectManager.removeCurrentUser()
2874 : redirectManager.setCurrentUser(user)];
2875 }
2876 });
2877 });
2878 };
2879 AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
2880 return tslib.__awaiter(this, void 0, void 0, function () {
2881 var resolver, _a, _b;
2882 return tslib.__generator(this, function (_c) {
2883 switch (_c.label) {
2884 case 0:
2885 if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
2886 resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
2887 this._popupRedirectResolver;
2888 _assert(resolver, this, "argument-error" /* ARGUMENT_ERROR */);
2889 _a = this;
2890 return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* REDIRECT_USER */)];
2891 case 1:
2892 _a.redirectPersistenceManager = _c.sent();
2893 _b = this;
2894 return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
2895 case 2:
2896 _b.redirectUser =
2897 _c.sent();
2898 _c.label = 3;
2899 case 3: return [2 /*return*/, this.redirectPersistenceManager];
2900 }
2901 });
2902 });
2903 };
2904 AuthImpl.prototype._redirectUserForId = function (id) {
2905 var _a, _b;
2906 return tslib.__awaiter(this, void 0, void 0, function () {
2907 var _this = this;
2908 return tslib.__generator(this, function (_c) {
2909 switch (_c.label) {
2910 case 0:
2911 if (!this._isInitialized) return [3 /*break*/, 2];
2912 return [4 /*yield*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
2913 return [2 /*return*/];
2914 }); }); })];
2915 case 1:
2916 _c.sent();
2917 _c.label = 2;
2918 case 2:
2919 if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
2920 return [2 /*return*/, this._currentUser];
2921 }
2922 if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
2923 return [2 /*return*/, this.redirectUser];
2924 }
2925 return [2 /*return*/, null];
2926 }
2927 });
2928 });
2929 };
2930 AuthImpl.prototype._persistUserIfCurrent = function (user) {
2931 return tslib.__awaiter(this, void 0, void 0, function () {
2932 var _this = this;
2933 return tslib.__generator(this, function (_a) {
2934 if (user === this.currentUser) {
2935 return [2 /*return*/, this.queue(function () { return tslib.__awaiter(_this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
2936 return [2 /*return*/, this.directlySetCurrentUser(user)];
2937 }); }); })];
2938 }
2939 return [2 /*return*/];
2940 });
2941 });
2942 };
2943 /** Notifies listeners only if the user is current */
2944 AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
2945 if (user === this.currentUser) {
2946 this.notifyAuthListeners();
2947 }
2948 };
2949 AuthImpl.prototype._key = function () {
2950 return this.config.authDomain + ":" + this.config.apiKey + ":" + this.name;
2951 };
2952 AuthImpl.prototype._startProactiveRefresh = function () {
2953 this.isProactiveRefreshEnabled = true;
2954 if (this.currentUser) {
2955 this._currentUser._startProactiveRefresh();
2956 }
2957 };
2958 AuthImpl.prototype._stopProactiveRefresh = function () {
2959 this.isProactiveRefreshEnabled = false;
2960 if (this.currentUser) {
2961 this._currentUser._stopProactiveRefresh();
2962 }
2963 };
2964 Object.defineProperty(AuthImpl.prototype, "_currentUser", {
2965 /** Returns the current user cast as the internal type */
2966 get: function () {
2967 return this.currentUser;
2968 },
2969 enumerable: false,
2970 configurable: true
2971 });
2972 AuthImpl.prototype.notifyAuthListeners = function () {
2973 var _a, _b;
2974 if (!this._isInitialized) {
2975 return;
2976 }
2977 this.idTokenSubscription.next(this.currentUser);
2978 var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
2979 if (this.lastNotifiedUid !== currentUid) {
2980 this.lastNotifiedUid = currentUid;
2981 this.authStateSubscription.next(this.currentUser);
2982 }
2983 };
2984 AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
2985 var _this = this;
2986 if (this._deleted) {
2987 return function () { };
2988 }
2989 var cb = typeof nextOrObserver === 'function'
2990 ? nextOrObserver
2991 : nextOrObserver.next.bind(nextOrObserver);
2992 var promise = this._isInitialized
2993 ? Promise.resolve()
2994 : this._initializationPromise;
2995 _assert(promise, this, "internal-error" /* INTERNAL_ERROR */);
2996 // The callback needs to be called asynchronously per the spec.
2997 // eslint-disable-next-line @typescript-eslint/no-floating-promises
2998 promise.then(function () { return cb(_this.currentUser); });
2999 if (typeof nextOrObserver === 'function') {
3000 return subscription.addObserver(nextOrObserver, error, completed);
3001 }
3002 else {
3003 return subscription.addObserver(nextOrObserver);
3004 }
3005 };
3006 /**
3007 * Unprotected (from race conditions) method to set the current user. This
3008 * should only be called from within a queued callback. This is necessary
3009 * because the queue shouldn't rely on another queued callback.
3010 */
3011 AuthImpl.prototype.directlySetCurrentUser = function (user) {
3012 return tslib.__awaiter(this, void 0, void 0, function () {
3013 return tslib.__generator(this, function (_a) {
3014 switch (_a.label) {
3015 case 0:
3016 if (this.currentUser && this.currentUser !== user) {
3017 this._currentUser._stopProactiveRefresh();
3018 if (user && this.isProactiveRefreshEnabled) {
3019 user._startProactiveRefresh();
3020 }
3021 }
3022 this.currentUser = user;
3023 if (!user) return [3 /*break*/, 2];
3024 return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
3025 case 1:
3026 _a.sent();
3027 return [3 /*break*/, 4];
3028 case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
3029 case 3:
3030 _a.sent();
3031 _a.label = 4;
3032 case 4: return [2 /*return*/];
3033 }
3034 });
3035 });
3036 };
3037 AuthImpl.prototype.queue = function (action) {
3038 // In case something errors, the callback still should be called in order
3039 // to keep the promise chain alive
3040 this.operations = this.operations.then(action, action);
3041 return this.operations;
3042 };
3043 Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
3044 get: function () {
3045 _assert(this.persistenceManager, this, "internal-error" /* INTERNAL_ERROR */);
3046 return this.persistenceManager;
3047 },
3048 enumerable: false,
3049 configurable: true
3050 });
3051 AuthImpl.prototype._logFramework = function (framework) {
3052 if (!framework || this.frameworks.includes(framework)) {
3053 return;
3054 }
3055 this.frameworks.push(framework);
3056 // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
3057 // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
3058 this.frameworks.sort();
3059 this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
3060 };
3061 AuthImpl.prototype._getFrameworks = function () {
3062 return this.frameworks;
3063 };
3064 AuthImpl.prototype._getAdditionalHeaders = function () {
3065 var _a;
3066 return tslib.__awaiter(this, void 0, void 0, function () {
3067 var headers, heartbeatsHeader;
3068 var _b;
3069 return tslib.__generator(this, function (_c) {
3070 switch (_c.label) {
3071 case 0:
3072 headers = (_b = {},
3073 _b["X-Client-Version" /* X_CLIENT_VERSION */] = this.clientVersion,
3074 _b);
3075 if (this.app.options.appId) {
3076 headers["X-Firebase-gmpid" /* X_FIREBASE_GMPID */] = this.app.options.appId;
3077 }
3078 return [4 /*yield*/, ((_a = this.heartbeatServiceProvider.getImmediate({
3079 optional: true,
3080 })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
3081 case 1:
3082 heartbeatsHeader = _c.sent();
3083 if (heartbeatsHeader) {
3084 headers["X-Firebase-Client" /* X_FIREBASE_CLIENT */] = heartbeatsHeader;
3085 }
3086 return [2 /*return*/, headers];
3087 }
3088 });
3089 });
3090 };
3091 return AuthImpl;
3092}());
3093/**
3094 * Method to be used to cast down to our private implmentation of Auth.
3095 * It will also handle unwrapping from the compat type if necessary
3096 *
3097 * @param auth Auth object passed in from developer
3098 */
3099function _castAuth(auth) {
3100 return util.getModularInstance(auth);
3101}
3102/** Helper class to wrap subscriber logic */
3103var Subscription = /** @class */ (function () {
3104 function Subscription(auth) {
3105 var _this = this;
3106 this.auth = auth;
3107 this.observer = null;
3108 this.addObserver = util.createSubscribe(function (observer) { return (_this.observer = observer); });
3109 }
3110 Object.defineProperty(Subscription.prototype, "next", {
3111 get: function () {
3112 _assert(this.observer, this.auth, "internal-error" /* INTERNAL_ERROR */);
3113 return this.observer.next.bind(this.observer);
3114 },
3115 enumerable: false,
3116 configurable: true
3117 });
3118 return Subscription;
3119}());
3120
3121/**
3122 * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
3123 * Firebase Auth services.
3124 *
3125 * @remarks
3126 * This must be called synchronously immediately following the first call to
3127 * {@link initializeAuth}. Do not use with production credentials as emulator
3128 * traffic is not encrypted.
3129 *
3130 *
3131 * @example
3132 * ```javascript
3133 * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
3134 * ```
3135 *
3136 * @param auth - The {@link Auth} instance.
3137 * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
3138 * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
3139 * `true` to disable the warning banner attached to the DOM.
3140 *
3141 * @public
3142 */
3143function connectAuthEmulator(auth, url, options) {
3144 var authInternal = _castAuth(auth);
3145 _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* EMULATOR_CONFIG_FAILED */);
3146 _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* INVALID_EMULATOR_SCHEME */);
3147 var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
3148 var protocol = extractProtocol(url);
3149 var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
3150 var portStr = port === null ? '' : ":" + port;
3151 // Always replace path with "/" (even if input url had no path at all, or had a different one).
3152 authInternal.config.emulator = { url: protocol + "//" + host + portStr + "/" };
3153 authInternal.settings.appVerificationDisabledForTesting = true;
3154 authInternal.emulatorConfig = Object.freeze({
3155 host: host,
3156 port: port,
3157 protocol: protocol.replace(':', ''),
3158 options: Object.freeze({ disableWarnings: disableWarnings })
3159 });
3160 if (!disableWarnings) {
3161 emitEmulatorWarning();
3162 }
3163}
3164function extractProtocol(url) {
3165 var protocolEnd = url.indexOf(':');
3166 return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
3167}
3168function extractHostAndPort(url) {
3169 var protocol = extractProtocol(url);
3170 var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
3171 if (!authority) {
3172 return { host: '', port: null };
3173 }
3174 var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
3175 var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
3176 if (bracketedIPv6) {
3177 var host = bracketedIPv6[1];
3178 return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
3179 }
3180 else {
3181 var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
3182 return { host: host, port: parsePort(port) };
3183 }
3184}
3185function parsePort(portStr) {
3186 if (!portStr) {
3187 return null;
3188 }
3189 var port = Number(portStr);
3190 if (isNaN(port)) {
3191 return null;
3192 }
3193 return port;
3194}
3195function emitEmulatorWarning() {
3196 function attachBanner() {
3197 var el = document.createElement('p');
3198 var sty = el.style;
3199 el.innerText =
3200 'Running in emulator mode. Do not use with production credentials.';
3201 sty.position = 'fixed';
3202 sty.width = '100%';
3203 sty.backgroundColor = '#ffffff';
3204 sty.border = '.1em solid #000000';
3205 sty.color = '#b50000';
3206 sty.bottom = '0px';
3207 sty.left = '0px';
3208 sty.margin = '0px';
3209 sty.zIndex = '10000';
3210 sty.textAlign = 'center';
3211 el.classList.add('firebase-emulator-warning');
3212 document.body.appendChild(el);
3213 }
3214 if (typeof console !== 'undefined' && typeof console.info === 'function') {
3215 console.info('WARNING: You are using the Auth Emulator,' +
3216 ' which is intended for local testing only. Do not use with' +
3217 ' production credentials.');
3218 }
3219 if (typeof window !== 'undefined' &&
3220 typeof document !== 'undefined') {
3221 if (document.readyState === 'loading') {
3222 window.addEventListener('DOMContentLoaded', attachBanner);
3223 }
3224 else {
3225 attachBanner();
3226 }
3227 }
3228}
3229
3230/**
3231 * @license
3232 * Copyright 2020 Google LLC
3233 *
3234 * Licensed under the Apache License, Version 2.0 (the "License");
3235 * you may not use this file except in compliance with the License.
3236 * You may obtain a copy of the License at
3237 *
3238 * http://www.apache.org/licenses/LICENSE-2.0
3239 *
3240 * Unless required by applicable law or agreed to in writing, software
3241 * distributed under the License is distributed on an "AS IS" BASIS,
3242 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3243 * See the License for the specific language governing permissions and
3244 * limitations under the License.
3245 */
3246/**
3247 * Interface that represents the credentials returned by an {@link AuthProvider}.
3248 *
3249 * @remarks
3250 * Implementations specify the details about each auth provider's credential requirements.
3251 *
3252 * @public
3253 */
3254var AuthCredential = /** @class */ (function () {
3255 /** @internal */
3256 function AuthCredential(
3257 /**
3258 * The authentication provider ID for the credential.
3259 *
3260 * @remarks
3261 * For example, 'facebook.com', or 'google.com'.
3262 */
3263 providerId,
3264 /**
3265 * The authentication sign in method for the credential.
3266 *
3267 * @remarks
3268 * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
3269 * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
3270 * identifier as returned in {@link fetchSignInMethodsForEmail}.
3271 */
3272 signInMethod) {
3273 this.providerId = providerId;
3274 this.signInMethod = signInMethod;
3275 }
3276 /**
3277 * Returns a JSON-serializable representation of this object.
3278 *
3279 * @returns a JSON-serializable representation of this object.
3280 */
3281 AuthCredential.prototype.toJSON = function () {
3282 return debugFail('not implemented');
3283 };
3284 /** @internal */
3285 AuthCredential.prototype._getIdTokenResponse = function (_auth) {
3286 return debugFail('not implemented');
3287 };
3288 /** @internal */
3289 AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
3290 return debugFail('not implemented');
3291 };
3292 /** @internal */
3293 AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
3294 return debugFail('not implemented');
3295 };
3296 return AuthCredential;
3297}());
3298
3299/**
3300 * @license
3301 * Copyright 2020 Google LLC
3302 *
3303 * Licensed under the Apache License, Version 2.0 (the "License");
3304 * you may not use this file except in compliance with the License.
3305 * You may obtain a copy of the License at
3306 *
3307 * http://www.apache.org/licenses/LICENSE-2.0
3308 *
3309 * Unless required by applicable law or agreed to in writing, software
3310 * distributed under the License is distributed on an "AS IS" BASIS,
3311 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3312 * See the License for the specific language governing permissions and
3313 * limitations under the License.
3314 */
3315function resetPassword(auth, request) {
3316 return tslib.__awaiter(this, void 0, void 0, function () {
3317 return tslib.__generator(this, function (_a) {
3318 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:resetPassword" /* RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
3319 });
3320 });
3321}
3322function updateEmailPassword(auth, request) {
3323 return tslib.__awaiter(this, void 0, void 0, function () {
3324 return tslib.__generator(this, function (_a) {
3325 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
3326 });
3327 });
3328}
3329function applyActionCode$1(auth, request) {
3330 return tslib.__awaiter(this, void 0, void 0, function () {
3331 return tslib.__generator(this, function (_a) {
3332 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
3333 });
3334 });
3335}
3336
3337/**
3338 * @license
3339 * Copyright 2020 Google LLC
3340 *
3341 * Licensed under the Apache License, Version 2.0 (the "License");
3342 * you may not use this file except in compliance with the License.
3343 * You may obtain a copy of the License at
3344 *
3345 * http://www.apache.org/licenses/LICENSE-2.0
3346 *
3347 * Unless required by applicable law or agreed to in writing, software
3348 * distributed under the License is distributed on an "AS IS" BASIS,
3349 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3350 * See the License for the specific language governing permissions and
3351 * limitations under the License.
3352 */
3353function signInWithPassword(auth, request) {
3354 return tslib.__awaiter(this, void 0, void 0, function () {
3355 return tslib.__generator(this, function (_a) {
3356 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPassword" /* SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
3357 });
3358 });
3359}
3360function sendOobCode(auth, request) {
3361 return tslib.__awaiter(this, void 0, void 0, function () {
3362 return tslib.__generator(this, function (_a) {
3363 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:sendOobCode" /* SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
3364 });
3365 });
3366}
3367function sendEmailVerification$1(auth, request) {
3368 return tslib.__awaiter(this, void 0, void 0, function () {
3369 return tslib.__generator(this, function (_a) {
3370 return [2 /*return*/, sendOobCode(auth, request)];
3371 });
3372 });
3373}
3374function sendPasswordResetEmail$1(auth, request) {
3375 return tslib.__awaiter(this, void 0, void 0, function () {
3376 return tslib.__generator(this, function (_a) {
3377 return [2 /*return*/, sendOobCode(auth, request)];
3378 });
3379 });
3380}
3381function sendSignInLinkToEmail$1(auth, request) {
3382 return tslib.__awaiter(this, void 0, void 0, function () {
3383 return tslib.__generator(this, function (_a) {
3384 return [2 /*return*/, sendOobCode(auth, request)];
3385 });
3386 });
3387}
3388function verifyAndChangeEmail(auth, request) {
3389 return tslib.__awaiter(this, void 0, void 0, function () {
3390 return tslib.__generator(this, function (_a) {
3391 return [2 /*return*/, sendOobCode(auth, request)];
3392 });
3393 });
3394}
3395
3396/**
3397 * @license
3398 * Copyright 2020 Google LLC
3399 *
3400 * Licensed under the Apache License, Version 2.0 (the "License");
3401 * you may not use this file except in compliance with the License.
3402 * You may obtain a copy of the License at
3403 *
3404 * http://www.apache.org/licenses/LICENSE-2.0
3405 *
3406 * Unless required by applicable law or agreed to in writing, software
3407 * distributed under the License is distributed on an "AS IS" BASIS,
3408 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3409 * See the License for the specific language governing permissions and
3410 * limitations under the License.
3411 */
3412function signInWithEmailLink$1(auth, request) {
3413 return tslib.__awaiter(this, void 0, void 0, function () {
3414 return tslib.__generator(this, function (_a) {
3415 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithEmailLink" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
3416 });
3417 });
3418}
3419function signInWithEmailLinkForLinking(auth, request) {
3420 return tslib.__awaiter(this, void 0, void 0, function () {
3421 return tslib.__generator(this, function (_a) {
3422 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithEmailLink" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
3423 });
3424 });
3425}
3426
3427/**
3428 * @license
3429 * Copyright 2020 Google LLC
3430 *
3431 * Licensed under the Apache License, Version 2.0 (the "License");
3432 * you may not use this file except in compliance with the License.
3433 * You may obtain a copy of the License at
3434 *
3435 * http://www.apache.org/licenses/LICENSE-2.0
3436 *
3437 * Unless required by applicable law or agreed to in writing, software
3438 * distributed under the License is distributed on an "AS IS" BASIS,
3439 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3440 * See the License for the specific language governing permissions and
3441 * limitations under the License.
3442 */
3443/**
3444 * Interface that represents the credentials returned by {@link EmailAuthProvider} for
3445 * {@link ProviderId}.PASSWORD
3446 *
3447 * @remarks
3448 * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
3449 * {@link SignInMethod}.EMAIL_LINK.
3450 *
3451 * @public
3452 */
3453var EmailAuthCredential = /** @class */ (function (_super) {
3454 tslib.__extends(EmailAuthCredential, _super);
3455 /** @internal */
3456 function EmailAuthCredential(
3457 /** @internal */
3458 _email,
3459 /** @internal */
3460 _password, signInMethod,
3461 /** @internal */
3462 _tenantId) {
3463 if (_tenantId === void 0) { _tenantId = null; }
3464 var _this = _super.call(this, "password" /* PASSWORD */, signInMethod) || this;
3465 _this._email = _email;
3466 _this._password = _password;
3467 _this._tenantId = _tenantId;
3468 return _this;
3469 }
3470 /** @internal */
3471 EmailAuthCredential._fromEmailAndPassword = function (email, password) {
3472 return new EmailAuthCredential(email, password, "password" /* EMAIL_PASSWORD */);
3473 };
3474 /** @internal */
3475 EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
3476 if (tenantId === void 0) { tenantId = null; }
3477 return new EmailAuthCredential(email, oobCode, "emailLink" /* EMAIL_LINK */, tenantId);
3478 };
3479 /** {@inheritdoc AuthCredential.toJSON} */
3480 EmailAuthCredential.prototype.toJSON = function () {
3481 return {
3482 email: this._email,
3483 password: this._password,
3484 signInMethod: this.signInMethod,
3485 tenantId: this._tenantId
3486 };
3487 };
3488 /**
3489 * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
3490 *
3491 * @param json - Either `object` or the stringified representation of the object. When string is
3492 * provided, `JSON.parse` would be called first.
3493 *
3494 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
3495 */
3496 EmailAuthCredential.fromJSON = function (json) {
3497 var obj = typeof json === 'string' ? JSON.parse(json) : json;
3498 if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
3499 if (obj.signInMethod === "password" /* EMAIL_PASSWORD */) {
3500 return this._fromEmailAndPassword(obj.email, obj.password);
3501 }
3502 else if (obj.signInMethod === "emailLink" /* EMAIL_LINK */) {
3503 return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
3504 }
3505 }
3506 return null;
3507 };
3508 /** @internal */
3509 EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
3510 return tslib.__awaiter(this, void 0, void 0, function () {
3511 return tslib.__generator(this, function (_a) {
3512 switch (this.signInMethod) {
3513 case "password" /* EMAIL_PASSWORD */:
3514 return [2 /*return*/, signInWithPassword(auth, {
3515 returnSecureToken: true,
3516 email: this._email,
3517 password: this._password
3518 })];
3519 case "emailLink" /* EMAIL_LINK */:
3520 return [2 /*return*/, signInWithEmailLink$1(auth, {
3521 email: this._email,
3522 oobCode: this._password
3523 })];
3524 default:
3525 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
3526 }
3527 return [2 /*return*/];
3528 });
3529 });
3530 };
3531 /** @internal */
3532 EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
3533 return tslib.__awaiter(this, void 0, void 0, function () {
3534 return tslib.__generator(this, function (_a) {
3535 switch (this.signInMethod) {
3536 case "password" /* EMAIL_PASSWORD */:
3537 return [2 /*return*/, updateEmailPassword(auth, {
3538 idToken: idToken,
3539 returnSecureToken: true,
3540 email: this._email,
3541 password: this._password
3542 })];
3543 case "emailLink" /* EMAIL_LINK */:
3544 return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
3545 idToken: idToken,
3546 email: this._email,
3547 oobCode: this._password
3548 })];
3549 default:
3550 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
3551 }
3552 return [2 /*return*/];
3553 });
3554 });
3555 };
3556 /** @internal */
3557 EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
3558 return this._getIdTokenResponse(auth);
3559 };
3560 return EmailAuthCredential;
3561}(AuthCredential));
3562
3563/**
3564 * @license
3565 * Copyright 2020 Google LLC
3566 *
3567 * Licensed under the Apache License, Version 2.0 (the "License");
3568 * you may not use this file except in compliance with the License.
3569 * You may obtain a copy of the License at
3570 *
3571 * http://www.apache.org/licenses/LICENSE-2.0
3572 *
3573 * Unless required by applicable law or agreed to in writing, software
3574 * distributed under the License is distributed on an "AS IS" BASIS,
3575 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3576 * See the License for the specific language governing permissions and
3577 * limitations under the License.
3578 */
3579function signInWithIdp(auth, request) {
3580 return tslib.__awaiter(this, void 0, void 0, function () {
3581 return tslib.__generator(this, function (_a) {
3582 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithIdp" /* SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
3583 });
3584 });
3585}
3586
3587/**
3588 * @license
3589 * Copyright 2020 Google LLC
3590 *
3591 * Licensed under the Apache License, Version 2.0 (the "License");
3592 * you may not use this file except in compliance with the License.
3593 * You may obtain a copy of the License at
3594 *
3595 * http://www.apache.org/licenses/LICENSE-2.0
3596 *
3597 * Unless required by applicable law or agreed to in writing, software
3598 * distributed under the License is distributed on an "AS IS" BASIS,
3599 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3600 * See the License for the specific language governing permissions and
3601 * limitations under the License.
3602 */
3603var IDP_REQUEST_URI$1 = 'http://localhost';
3604/**
3605 * Represents the OAuth credentials returned by an {@link OAuthProvider}.
3606 *
3607 * @remarks
3608 * Implementations specify the details about each auth provider's credential requirements.
3609 *
3610 * @public
3611 */
3612var OAuthCredential = /** @class */ (function (_super) {
3613 tslib.__extends(OAuthCredential, _super);
3614 function OAuthCredential() {
3615 var _this = _super !== null && _super.apply(this, arguments) || this;
3616 _this.pendingToken = null;
3617 return _this;
3618 }
3619 /** @internal */
3620 OAuthCredential._fromParams = function (params) {
3621 var cred = new OAuthCredential(params.providerId, params.signInMethod);
3622 if (params.idToken || params.accessToken) {
3623 // OAuth 2 and either ID token or access token.
3624 if (params.idToken) {
3625 cred.idToken = params.idToken;
3626 }
3627 if (params.accessToken) {
3628 cred.accessToken = params.accessToken;
3629 }
3630 // Add nonce if available and no pendingToken is present.
3631 if (params.nonce && !params.pendingToken) {
3632 cred.nonce = params.nonce;
3633 }
3634 if (params.pendingToken) {
3635 cred.pendingToken = params.pendingToken;
3636 }
3637 }
3638 else if (params.oauthToken && params.oauthTokenSecret) {
3639 // OAuth 1 and OAuth token with token secret
3640 cred.accessToken = params.oauthToken;
3641 cred.secret = params.oauthTokenSecret;
3642 }
3643 else {
3644 _fail("argument-error" /* ARGUMENT_ERROR */);
3645 }
3646 return cred;
3647 };
3648 /** {@inheritdoc AuthCredential.toJSON} */
3649 OAuthCredential.prototype.toJSON = function () {
3650 return {
3651 idToken: this.idToken,
3652 accessToken: this.accessToken,
3653 secret: this.secret,
3654 nonce: this.nonce,
3655 pendingToken: this.pendingToken,
3656 providerId: this.providerId,
3657 signInMethod: this.signInMethod
3658 };
3659 };
3660 /**
3661 * Static method to deserialize a JSON representation of an object into an
3662 * {@link AuthCredential}.
3663 *
3664 * @param json - Input can be either Object or the stringified representation of the object.
3665 * When string is provided, JSON.parse would be called first.
3666 *
3667 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
3668 */
3669 OAuthCredential.fromJSON = function (json) {
3670 var obj = typeof json === 'string' ? JSON.parse(json) : json;
3671 var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = tslib.__rest(obj, ["providerId", "signInMethod"]);
3672 if (!providerId || !signInMethod) {
3673 return null;
3674 }
3675 var cred = new OAuthCredential(providerId, signInMethod);
3676 cred.idToken = rest.idToken || undefined;
3677 cred.accessToken = rest.accessToken || undefined;
3678 cred.secret = rest.secret;
3679 cred.nonce = rest.nonce;
3680 cred.pendingToken = rest.pendingToken || null;
3681 return cred;
3682 };
3683 /** @internal */
3684 OAuthCredential.prototype._getIdTokenResponse = function (auth) {
3685 var request = this.buildRequest();
3686 return signInWithIdp(auth, request);
3687 };
3688 /** @internal */
3689 OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
3690 var request = this.buildRequest();
3691 request.idToken = idToken;
3692 return signInWithIdp(auth, request);
3693 };
3694 /** @internal */
3695 OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
3696 var request = this.buildRequest();
3697 request.autoCreate = false;
3698 return signInWithIdp(auth, request);
3699 };
3700 OAuthCredential.prototype.buildRequest = function () {
3701 var request = {
3702 requestUri: IDP_REQUEST_URI$1,
3703 returnSecureToken: true
3704 };
3705 if (this.pendingToken) {
3706 request.pendingToken = this.pendingToken;
3707 }
3708 else {
3709 var postBody = {};
3710 if (this.idToken) {
3711 postBody['id_token'] = this.idToken;
3712 }
3713 if (this.accessToken) {
3714 postBody['access_token'] = this.accessToken;
3715 }
3716 if (this.secret) {
3717 postBody['oauth_token_secret'] = this.secret;
3718 }
3719 postBody['providerId'] = this.providerId;
3720 if (this.nonce && !this.pendingToken) {
3721 postBody['nonce'] = this.nonce;
3722 }
3723 request.postBody = util.querystring(postBody);
3724 }
3725 return request;
3726 };
3727 return OAuthCredential;
3728}(AuthCredential));
3729
3730/**
3731 * @license
3732 * Copyright 2020 Google LLC
3733 *
3734 * Licensed under the Apache License, Version 2.0 (the "License");
3735 * you may not use this file except in compliance with the License.
3736 * You may obtain a copy of the License at
3737 *
3738 * http://www.apache.org/licenses/LICENSE-2.0
3739 *
3740 * Unless required by applicable law or agreed to in writing, software
3741 * distributed under the License is distributed on an "AS IS" BASIS,
3742 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3743 * See the License for the specific language governing permissions and
3744 * limitations under the License.
3745 */
3746var _a;
3747function sendPhoneVerificationCode(auth, request) {
3748 return tslib.__awaiter(this, void 0, void 0, function () {
3749 return tslib.__generator(this, function (_a) {
3750 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:sendVerificationCode" /* SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request))];
3751 });
3752 });
3753}
3754function signInWithPhoneNumber$1(auth, request) {
3755 return tslib.__awaiter(this, void 0, void 0, function () {
3756 return tslib.__generator(this, function (_a) {
3757 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
3758 });
3759 });
3760}
3761function linkWithPhoneNumber$1(auth, request) {
3762 return tslib.__awaiter(this, void 0, void 0, function () {
3763 var response;
3764 return tslib.__generator(this, function (_a) {
3765 switch (_a.label) {
3766 case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
3767 case 1:
3768 response = _a.sent();
3769 if (response.temporaryProof) {
3770 throw _makeTaggedError(auth, "account-exists-with-different-credential" /* NEED_CONFIRMATION */, response);
3771 }
3772 return [2 /*return*/, response];
3773 }
3774 });
3775 });
3776}
3777var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
3778 _a["USER_NOT_FOUND" /* USER_NOT_FOUND */] = "user-not-found" /* USER_DELETED */,
3779 _a);
3780function verifyPhoneNumberForExisting(auth, request) {
3781 return tslib.__awaiter(this, void 0, void 0, function () {
3782 var apiRequest;
3783 return tslib.__generator(this, function (_a) {
3784 apiRequest = tslib.__assign(tslib.__assign({}, request), { operation: 'REAUTH' });
3785 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_)];
3786 });
3787 });
3788}
3789
3790/**
3791 * @license
3792 * Copyright 2020 Google LLC
3793 *
3794 * Licensed under the Apache License, Version 2.0 (the "License");
3795 * you may not use this file except in compliance with the License.
3796 * You may obtain a copy of the License at
3797 *
3798 * http://www.apache.org/licenses/LICENSE-2.0
3799 *
3800 * Unless required by applicable law or agreed to in writing, software
3801 * distributed under the License is distributed on an "AS IS" BASIS,
3802 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3803 * See the License for the specific language governing permissions and
3804 * limitations under the License.
3805 */
3806/**
3807 * Represents the credentials returned by {@link PhoneAuthProvider}.
3808 *
3809 * @public
3810 */
3811var PhoneAuthCredential = /** @class */ (function (_super) {
3812 tslib.__extends(PhoneAuthCredential, _super);
3813 function PhoneAuthCredential(params) {
3814 var _this = _super.call(this, "phone" /* PHONE */, "phone" /* PHONE */) || this;
3815 _this.params = params;
3816 return _this;
3817 }
3818 /** @internal */
3819 PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
3820 return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
3821 };
3822 /** @internal */
3823 PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
3824 return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
3825 };
3826 /** @internal */
3827 PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
3828 return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
3829 };
3830 /** @internal */
3831 PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
3832 return linkWithPhoneNumber$1(auth, tslib.__assign({ idToken: idToken }, this._makeVerificationRequest()));
3833 };
3834 /** @internal */
3835 PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
3836 return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
3837 };
3838 /** @internal */
3839 PhoneAuthCredential.prototype._makeVerificationRequest = function () {
3840 var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
3841 if (temporaryProof && phoneNumber) {
3842 return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
3843 }
3844 return {
3845 sessionInfo: verificationId,
3846 code: verificationCode
3847 };
3848 };
3849 /** {@inheritdoc AuthCredential.toJSON} */
3850 PhoneAuthCredential.prototype.toJSON = function () {
3851 var obj = {
3852 providerId: this.providerId
3853 };
3854 if (this.params.phoneNumber) {
3855 obj.phoneNumber = this.params.phoneNumber;
3856 }
3857 if (this.params.temporaryProof) {
3858 obj.temporaryProof = this.params.temporaryProof;
3859 }
3860 if (this.params.verificationCode) {
3861 obj.verificationCode = this.params.verificationCode;
3862 }
3863 if (this.params.verificationId) {
3864 obj.verificationId = this.params.verificationId;
3865 }
3866 return obj;
3867 };
3868 /** Generates a phone credential based on a plain object or a JSON string. */
3869 PhoneAuthCredential.fromJSON = function (json) {
3870 if (typeof json === 'string') {
3871 json = JSON.parse(json);
3872 }
3873 var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
3874 if (!verificationCode &&
3875 !verificationId &&
3876 !phoneNumber &&
3877 !temporaryProof) {
3878 return null;
3879 }
3880 return new PhoneAuthCredential({
3881 verificationId: verificationId,
3882 verificationCode: verificationCode,
3883 phoneNumber: phoneNumber,
3884 temporaryProof: temporaryProof
3885 });
3886 };
3887 return PhoneAuthCredential;
3888}(AuthCredential));
3889
3890/**
3891 * @license
3892 * Copyright 2020 Google LLC
3893 *
3894 * Licensed under the Apache License, Version 2.0 (the "License");
3895 * you may not use this file except in compliance with the License.
3896 * You may obtain a copy of the License at
3897 *
3898 * http://www.apache.org/licenses/LICENSE-2.0
3899 *
3900 * Unless required by applicable law or agreed to in writing, software
3901 * distributed under the License is distributed on an "AS IS" BASIS,
3902 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3903 * See the License for the specific language governing permissions and
3904 * limitations under the License.
3905 */
3906/**
3907 * Maps the mode string in action code URL to Action Code Info operation.
3908 *
3909 * @param mode
3910 */
3911function parseMode(mode) {
3912 switch (mode) {
3913 case 'recoverEmail':
3914 return "RECOVER_EMAIL" /* RECOVER_EMAIL */;
3915 case 'resetPassword':
3916 return "PASSWORD_RESET" /* PASSWORD_RESET */;
3917 case 'signIn':
3918 return "EMAIL_SIGNIN" /* EMAIL_SIGNIN */;
3919 case 'verifyEmail':
3920 return "VERIFY_EMAIL" /* VERIFY_EMAIL */;
3921 case 'verifyAndChangeEmail':
3922 return "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */;
3923 case 'revertSecondFactorAddition':
3924 return "REVERT_SECOND_FACTOR_ADDITION" /* REVERT_SECOND_FACTOR_ADDITION */;
3925 default:
3926 return null;
3927 }
3928}
3929/**
3930 * Helper to parse FDL links
3931 *
3932 * @param url
3933 */
3934function parseDeepLink(url) {
3935 var link = util.querystringDecode(util.extractQuerystring(url))['link'];
3936 // Double link case (automatic redirect).
3937 var doubleDeepLink = link
3938 ? util.querystringDecode(util.extractQuerystring(link))['deep_link_id']
3939 : null;
3940 // iOS custom scheme links.
3941 var iOSDeepLink = util.querystringDecode(util.extractQuerystring(url))['deep_link_id'];
3942 var iOSDoubleDeepLink = iOSDeepLink
3943 ? util.querystringDecode(util.extractQuerystring(iOSDeepLink))['link']
3944 : null;
3945 return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
3946}
3947/**
3948 * A utility class to parse email action URLs such as password reset, email verification,
3949 * email link sign in, etc.
3950 *
3951 * @public
3952 */
3953var ActionCodeURL = /** @class */ (function () {
3954 /**
3955 * @param actionLink - The link from which to extract the URL.
3956 * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
3957 *
3958 * @internal
3959 */
3960 function ActionCodeURL(actionLink) {
3961 var _a, _b, _c, _d, _e, _f;
3962 var searchParams = util.querystringDecode(util.extractQuerystring(actionLink));
3963 var apiKey = (_a = searchParams["apiKey" /* API_KEY */]) !== null && _a !== void 0 ? _a : null;
3964 var code = (_b = searchParams["oobCode" /* CODE */]) !== null && _b !== void 0 ? _b : null;
3965 var operation = parseMode((_c = searchParams["mode" /* MODE */]) !== null && _c !== void 0 ? _c : null);
3966 // Validate API key, code and mode.
3967 _assert(apiKey && code && operation, "argument-error" /* ARGUMENT_ERROR */);
3968 this.apiKey = apiKey;
3969 this.operation = operation;
3970 this.code = code;
3971 this.continueUrl = (_d = searchParams["continueUrl" /* CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
3972 this.languageCode = (_e = searchParams["languageCode" /* LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
3973 this.tenantId = (_f = searchParams["tenantId" /* TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
3974 }
3975 /**
3976 * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
3977 * otherwise returns null.
3978 *
3979 * @param link - The email action link string.
3980 * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
3981 *
3982 * @public
3983 */
3984 ActionCodeURL.parseLink = function (link) {
3985 var actionLink = parseDeepLink(link);
3986 try {
3987 return new ActionCodeURL(actionLink);
3988 }
3989 catch (_a) {
3990 return null;
3991 }
3992 };
3993 return ActionCodeURL;
3994}());
3995/**
3996 * Parses the email action link string and returns an {@link ActionCodeURL} if
3997 * the link is valid, otherwise returns null.
3998 *
3999 * @public
4000 */
4001function parseActionCodeURL(link) {
4002 return ActionCodeURL.parseLink(link);
4003}
4004
4005/**
4006 * @license
4007 * Copyright 2020 Google LLC
4008 *
4009 * Licensed under the Apache License, Version 2.0 (the "License");
4010 * you may not use this file except in compliance with the License.
4011 * You may obtain a copy of the License at
4012 *
4013 * http://www.apache.org/licenses/LICENSE-2.0
4014 *
4015 * Unless required by applicable law or agreed to in writing, software
4016 * distributed under the License is distributed on an "AS IS" BASIS,
4017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4018 * See the License for the specific language governing permissions and
4019 * limitations under the License.
4020 */
4021/**
4022 * Provider for generating {@link EmailAuthCredential}.
4023 *
4024 * @public
4025 */
4026var EmailAuthProvider = /** @class */ (function () {
4027 function EmailAuthProvider() {
4028 /**
4029 * Always set to {@link ProviderId}.PASSWORD, even for email link.
4030 */
4031 this.providerId = EmailAuthProvider.PROVIDER_ID;
4032 }
4033 /**
4034 * Initialize an {@link AuthCredential} using an email and password.
4035 *
4036 * @example
4037 * ```javascript
4038 * const authCredential = EmailAuthProvider.credential(email, password);
4039 * const userCredential = await signInWithCredential(auth, authCredential);
4040 * ```
4041 *
4042 * @example
4043 * ```javascript
4044 * const userCredential = await signInWithEmailAndPassword(auth, email, password);
4045 * ```
4046 *
4047 * @param email - Email address.
4048 * @param password - User account password.
4049 * @returns The auth provider credential.
4050 */
4051 EmailAuthProvider.credential = function (email, password) {
4052 return EmailAuthCredential._fromEmailAndPassword(email, password);
4053 };
4054 /**
4055 * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
4056 * email link operation.
4057 *
4058 * @example
4059 * ```javascript
4060 * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
4061 * const userCredential = await signInWithCredential(auth, authCredential);
4062 * ```
4063 *
4064 * @example
4065 * ```javascript
4066 * await sendSignInLinkToEmail(auth, email);
4067 * // Obtain emailLink from user.
4068 * const userCredential = await signInWithEmailLink(auth, email, emailLink);
4069 * ```
4070 *
4071 * @param auth - The {@link Auth} instance used to verify the link.
4072 * @param email - Email address.
4073 * @param emailLink - Sign-in email link.
4074 * @returns - The auth provider credential.
4075 */
4076 EmailAuthProvider.credentialWithLink = function (email, emailLink) {
4077 var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
4078 _assert(actionCodeUrl, "argument-error" /* ARGUMENT_ERROR */);
4079 return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
4080 };
4081 /**
4082 * Always set to {@link ProviderId}.PASSWORD, even for email link.
4083 */
4084 EmailAuthProvider.PROVIDER_ID = "password" /* PASSWORD */;
4085 /**
4086 * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
4087 */
4088 EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* EMAIL_PASSWORD */;
4089 /**
4090 * Always set to {@link SignInMethod}.EMAIL_LINK.
4091 */
4092 EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* EMAIL_LINK */;
4093 return EmailAuthProvider;
4094}());
4095
4096/**
4097 * @license
4098 * Copyright 2020 Google LLC
4099 *
4100 * Licensed under the Apache License, Version 2.0 (the "License");
4101 * you may not use this file except in compliance with the License.
4102 * You may obtain a copy of the License at
4103 *
4104 * http://www.apache.org/licenses/LICENSE-2.0
4105 *
4106 * Unless required by applicable law or agreed to in writing, software
4107 * distributed under the License is distributed on an "AS IS" BASIS,
4108 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4109 * See the License for the specific language governing permissions and
4110 * limitations under the License.
4111 */
4112/**
4113 * The base class for all Federated providers (OAuth (including OIDC), SAML).
4114 *
4115 * This class is not meant to be instantiated directly.
4116 *
4117 * @public
4118 */
4119var FederatedAuthProvider = /** @class */ (function () {
4120 /**
4121 * Constructor for generic OAuth providers.
4122 *
4123 * @param providerId - Provider for which credentials should be generated.
4124 */
4125 function FederatedAuthProvider(providerId) {
4126 this.providerId = providerId;
4127 /** @internal */
4128 this.defaultLanguageCode = null;
4129 /** @internal */
4130 this.customParameters = {};
4131 }
4132 /**
4133 * Set the language gode.
4134 *
4135 * @param languageCode - language code
4136 */
4137 FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
4138 this.defaultLanguageCode = languageCode;
4139 };
4140 /**
4141 * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
4142 * operations.
4143 *
4144 * @remarks
4145 * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
4146 * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
4147 *
4148 * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
4149 */
4150 FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
4151 this.customParameters = customOAuthParameters;
4152 return this;
4153 };
4154 /**
4155 * Retrieve the current list of {@link CustomParameters}.
4156 */
4157 FederatedAuthProvider.prototype.getCustomParameters = function () {
4158 return this.customParameters;
4159 };
4160 return FederatedAuthProvider;
4161}());
4162
4163/**
4164 * @license
4165 * Copyright 2019 Google LLC
4166 *
4167 * Licensed under the Apache License, Version 2.0 (the "License");
4168 * you may not use this file except in compliance with the License.
4169 * You may obtain a copy of the License at
4170 *
4171 * http://www.apache.org/licenses/LICENSE-2.0
4172 *
4173 * Unless required by applicable law or agreed to in writing, software
4174 * distributed under the License is distributed on an "AS IS" BASIS,
4175 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4176 * See the License for the specific language governing permissions and
4177 * limitations under the License.
4178 */
4179/**
4180 * Common code to all OAuth providers. This is separate from the
4181 * {@link OAuthProvider} so that child providers (like
4182 * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
4183 * Instead, they rely on a static `credential` method.
4184 */
4185var BaseOAuthProvider = /** @class */ (function (_super) {
4186 tslib.__extends(BaseOAuthProvider, _super);
4187 function BaseOAuthProvider() {
4188 var _this = _super !== null && _super.apply(this, arguments) || this;
4189 /** @internal */
4190 _this.scopes = [];
4191 return _this;
4192 }
4193 /**
4194 * Add an OAuth scope to the credential.
4195 *
4196 * @param scope - Provider OAuth scope to add.
4197 */
4198 BaseOAuthProvider.prototype.addScope = function (scope) {
4199 // If not already added, add scope to list.
4200 if (!this.scopes.includes(scope)) {
4201 this.scopes.push(scope);
4202 }
4203 return this;
4204 };
4205 /**
4206 * Retrieve the current list of OAuth scopes.
4207 */
4208 BaseOAuthProvider.prototype.getScopes = function () {
4209 return tslib.__spreadArray([], this.scopes);
4210 };
4211 return BaseOAuthProvider;
4212}(FederatedAuthProvider));
4213/**
4214 * Provider for generating generic {@link OAuthCredential}.
4215 *
4216 * @example
4217 * ```javascript
4218 * // Sign in using a redirect.
4219 * const provider = new OAuthProvider('google.com');
4220 * // Start a sign in process for an unauthenticated user.
4221 * provider.addScope('profile');
4222 * provider.addScope('email');
4223 * await signInWithRedirect(auth, provider);
4224 * // This will trigger a full page redirect away from your app
4225 *
4226 * // After returning from the redirect when your app initializes you can obtain the result
4227 * const result = await getRedirectResult(auth);
4228 * if (result) {
4229 * // This is the signed-in user
4230 * const user = result.user;
4231 * // This gives you a OAuth Access Token for the provider.
4232 * const credential = provider.credentialFromResult(auth, result);
4233 * const token = credential.accessToken;
4234 * }
4235 * ```
4236 *
4237 * @example
4238 * ```javascript
4239 * // Sign in using a popup.
4240 * const provider = new OAuthProvider('google.com');
4241 * provider.addScope('profile');
4242 * provider.addScope('email');
4243 * const result = await signInWithPopup(auth, provider);
4244 *
4245 * // The signed-in user info.
4246 * const user = result.user;
4247 * // This gives you a OAuth Access Token for the provider.
4248 * const credential = provider.credentialFromResult(auth, result);
4249 * const token = credential.accessToken;
4250 * ```
4251 * @public
4252 */
4253var OAuthProvider = /** @class */ (function (_super) {
4254 tslib.__extends(OAuthProvider, _super);
4255 function OAuthProvider() {
4256 return _super !== null && _super.apply(this, arguments) || this;
4257 }
4258 /**
4259 * Creates an {@link OAuthCredential} from a JSON string or a plain object.
4260 * @param json - A plain object or a JSON string
4261 */
4262 OAuthProvider.credentialFromJSON = function (json) {
4263 var obj = typeof json === 'string' ? JSON.parse(json) : json;
4264 _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* ARGUMENT_ERROR */);
4265 return OAuthCredential._fromParams(obj);
4266 };
4267 /**
4268 * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
4269 *
4270 * @remarks
4271 * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
4272 * the raw nonce must match the nonce field in the ID token.
4273 *
4274 * @example
4275 * ```javascript
4276 * // `googleUser` from the onsuccess Google Sign In callback.
4277 * // Initialize a generate OAuth provider with a `google.com` providerId.
4278 * const provider = new OAuthProvider('google.com');
4279 * const credential = provider.credential({
4280 * idToken: googleUser.getAuthResponse().id_token,
4281 * });
4282 * const result = await signInWithCredential(credential);
4283 * ```
4284 *
4285 * @param params - Either the options object containing the ID token, access token and raw nonce
4286 * or the ID token string.
4287 */
4288 OAuthProvider.prototype.credential = function (params) {
4289 return this._credential(tslib.__assign(tslib.__assign({}, params), { nonce: params.rawNonce }));
4290 };
4291 /** An internal credential method that accepts more permissive options */
4292 OAuthProvider.prototype._credential = function (params) {
4293 _assert(params.idToken || params.accessToken, "argument-error" /* ARGUMENT_ERROR */);
4294 // For OAuthCredential, sign in method is same as providerId.
4295 return OAuthCredential._fromParams(tslib.__assign(tslib.__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
4296 };
4297 /**
4298 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4299 *
4300 * @param userCredential - The user credential.
4301 */
4302 OAuthProvider.credentialFromResult = function (userCredential) {
4303 return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
4304 };
4305 /**
4306 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4307 * thrown during a sign-in, link, or reauthenticate operation.
4308 *
4309 * @param userCredential - The user credential.
4310 */
4311 OAuthProvider.credentialFromError = function (error) {
4312 return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
4313 };
4314 OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
4315 var tokenResponse = _a._tokenResponse;
4316 if (!tokenResponse) {
4317 return null;
4318 }
4319 var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
4320 if (!oauthAccessToken &&
4321 !oauthTokenSecret &&
4322 !oauthIdToken &&
4323 !pendingToken) {
4324 return null;
4325 }
4326 if (!providerId) {
4327 return null;
4328 }
4329 try {
4330 return new OAuthProvider(providerId)._credential({
4331 idToken: oauthIdToken,
4332 accessToken: oauthAccessToken,
4333 nonce: nonce,
4334 pendingToken: pendingToken
4335 });
4336 }
4337 catch (e) {
4338 return null;
4339 }
4340 };
4341 return OAuthProvider;
4342}(BaseOAuthProvider));
4343
4344/**
4345 * @license
4346 * Copyright 2020 Google LLC
4347 *
4348 * Licensed under the Apache License, Version 2.0 (the "License");
4349 * you may not use this file except in compliance with the License.
4350 * You may obtain a copy of the License at
4351 *
4352 * http://www.apache.org/licenses/LICENSE-2.0
4353 *
4354 * Unless required by applicable law or agreed to in writing, software
4355 * distributed under the License is distributed on an "AS IS" BASIS,
4356 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4357 * See the License for the specific language governing permissions and
4358 * limitations under the License.
4359 */
4360/**
4361 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
4362 *
4363 * @example
4364 * ```javascript
4365 * // Sign in using a redirect.
4366 * const provider = new FacebookAuthProvider();
4367 * // Start a sign in process for an unauthenticated user.
4368 * provider.addScope('user_birthday');
4369 * await signInWithRedirect(auth, provider);
4370 * // This will trigger a full page redirect away from your app
4371 *
4372 * // After returning from the redirect when your app initializes you can obtain the result
4373 * const result = await getRedirectResult(auth);
4374 * if (result) {
4375 * // This is the signed-in user
4376 * const user = result.user;
4377 * // This gives you a Facebook Access Token.
4378 * const credential = FacebookAuthProvider.credentialFromResult(result);
4379 * const token = credential.accessToken;
4380 * }
4381 * ```
4382 *
4383 * @example
4384 * ```javascript
4385 * // Sign in using a popup.
4386 * const provider = new FacebookAuthProvider();
4387 * provider.addScope('user_birthday');
4388 * const result = await signInWithPopup(auth, provider);
4389 *
4390 * // The signed-in user info.
4391 * const user = result.user;
4392 * // This gives you a Facebook Access Token.
4393 * const credential = FacebookAuthProvider.credentialFromResult(result);
4394 * const token = credential.accessToken;
4395 * ```
4396 *
4397 * @public
4398 */
4399var FacebookAuthProvider = /** @class */ (function (_super) {
4400 tslib.__extends(FacebookAuthProvider, _super);
4401 function FacebookAuthProvider() {
4402 return _super.call(this, "facebook.com" /* FACEBOOK */) || this;
4403 }
4404 /**
4405 * Creates a credential for Facebook.
4406 *
4407 * @example
4408 * ```javascript
4409 * // `event` from the Facebook auth.authResponseChange callback.
4410 * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
4411 * const result = await signInWithCredential(credential);
4412 * ```
4413 *
4414 * @param accessToken - Facebook access token.
4415 */
4416 FacebookAuthProvider.credential = function (accessToken) {
4417 return OAuthCredential._fromParams({
4418 providerId: FacebookAuthProvider.PROVIDER_ID,
4419 signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
4420 accessToken: accessToken
4421 });
4422 };
4423 /**
4424 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4425 *
4426 * @param userCredential - The user credential.
4427 */
4428 FacebookAuthProvider.credentialFromResult = function (userCredential) {
4429 return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
4430 };
4431 /**
4432 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4433 * thrown during a sign-in, link, or reauthenticate operation.
4434 *
4435 * @param userCredential - The user credential.
4436 */
4437 FacebookAuthProvider.credentialFromError = function (error) {
4438 return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
4439 };
4440 FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
4441 var tokenResponse = _a._tokenResponse;
4442 if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
4443 return null;
4444 }
4445 if (!tokenResponse.oauthAccessToken) {
4446 return null;
4447 }
4448 try {
4449 return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
4450 }
4451 catch (_b) {
4452 return null;
4453 }
4454 };
4455 /** Always set to {@link SignInMethod}.FACEBOOK. */
4456 FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* FACEBOOK */;
4457 /** Always set to {@link ProviderId}.FACEBOOK. */
4458 FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* FACEBOOK */;
4459 return FacebookAuthProvider;
4460}(BaseOAuthProvider));
4461
4462/**
4463 * @license
4464 * Copyright 2020 Google LLC
4465 *
4466 * Licensed under the Apache License, Version 2.0 (the "License");
4467 * you may not use this file except in compliance with the License.
4468 * You may obtain a copy of the License at
4469 *
4470 * http://www.apache.org/licenses/LICENSE-2.0
4471 *
4472 * Unless required by applicable law or agreed to in writing, software
4473 * distributed under the License is distributed on an "AS IS" BASIS,
4474 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4475 * See the License for the specific language governing permissions and
4476 * limitations under the License.
4477 */
4478/**
4479 * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
4480 *
4481 * @example
4482 * ```javascript
4483 * // Sign in using a redirect.
4484 * const provider = new GoogleAuthProvider();
4485 * // Start a sign in process for an unauthenticated user.
4486 * provider.addScope('profile');
4487 * provider.addScope('email');
4488 * await signInWithRedirect(auth, provider);
4489 * // This will trigger a full page redirect away from your app
4490 *
4491 * // After returning from the redirect when your app initializes you can obtain the result
4492 * const result = await getRedirectResult(auth);
4493 * if (result) {
4494 * // This is the signed-in user
4495 * const user = result.user;
4496 * // This gives you a Google Access Token.
4497 * const credential = GoogleAuthProvider.credentialFromResult(result);
4498 * const token = credential.accessToken;
4499 * }
4500 * ```
4501 *
4502 * @example
4503 * ```javascript
4504 * // Sign in using a popup.
4505 * const provider = new GoogleAuthProvider();
4506 * provider.addScope('profile');
4507 * provider.addScope('email');
4508 * const result = await signInWithPopup(auth, provider);
4509 *
4510 * // The signed-in user info.
4511 * const user = result.user;
4512 * // This gives you a Google Access Token.
4513 * const credential = GoogleAuthProvider.credentialFromResult(result);
4514 * const token = credential.accessToken;
4515 * ```
4516 *
4517 * @public
4518 */
4519var GoogleAuthProvider = /** @class */ (function (_super) {
4520 tslib.__extends(GoogleAuthProvider, _super);
4521 function GoogleAuthProvider() {
4522 var _this = _super.call(this, "google.com" /* GOOGLE */) || this;
4523 _this.addScope('profile');
4524 return _this;
4525 }
4526 /**
4527 * Creates a credential for Google. At least one of ID token and access token is required.
4528 *
4529 * @example
4530 * ```javascript
4531 * // \`googleUser\` from the onsuccess Google Sign In callback.
4532 * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
4533 * const result = await signInWithCredential(credential);
4534 * ```
4535 *
4536 * @param idToken - Google ID token.
4537 * @param accessToken - Google access token.
4538 */
4539 GoogleAuthProvider.credential = function (idToken, accessToken) {
4540 return OAuthCredential._fromParams({
4541 providerId: GoogleAuthProvider.PROVIDER_ID,
4542 signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
4543 idToken: idToken,
4544 accessToken: accessToken
4545 });
4546 };
4547 /**
4548 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4549 *
4550 * @param userCredential - The user credential.
4551 */
4552 GoogleAuthProvider.credentialFromResult = function (userCredential) {
4553 return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
4554 };
4555 /**
4556 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4557 * thrown during a sign-in, link, or reauthenticate operation.
4558 *
4559 * @param userCredential - The user credential.
4560 */
4561 GoogleAuthProvider.credentialFromError = function (error) {
4562 return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
4563 };
4564 GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
4565 var tokenResponse = _a._tokenResponse;
4566 if (!tokenResponse) {
4567 return null;
4568 }
4569 var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
4570 if (!oauthIdToken && !oauthAccessToken) {
4571 // This could be an oauth 1 credential or a phone credential
4572 return null;
4573 }
4574 try {
4575 return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
4576 }
4577 catch (_c) {
4578 return null;
4579 }
4580 };
4581 /** Always set to {@link SignInMethod}.GOOGLE. */
4582 GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* GOOGLE */;
4583 /** Always set to {@link ProviderId}.GOOGLE. */
4584 GoogleAuthProvider.PROVIDER_ID = "google.com" /* GOOGLE */;
4585 return GoogleAuthProvider;
4586}(BaseOAuthProvider));
4587
4588/**
4589 * @license
4590 * Copyright 2020 Google LLC
4591 *
4592 * Licensed under the Apache License, Version 2.0 (the "License");
4593 * you may not use this file except in compliance with the License.
4594 * You may obtain a copy of the License at
4595 *
4596 * http://www.apache.org/licenses/LICENSE-2.0
4597 *
4598 * Unless required by applicable law or agreed to in writing, software
4599 * distributed under the License is distributed on an "AS IS" BASIS,
4600 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4601 * See the License for the specific language governing permissions and
4602 * limitations under the License.
4603 */
4604/**
4605 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
4606 *
4607 * @remarks
4608 * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
4609 * the {@link signInWithPopup} handler:
4610 *
4611 * @example
4612 * ```javascript
4613 * // Sign in using a redirect.
4614 * const provider = new GithubAuthProvider();
4615 * // Start a sign in process for an unauthenticated user.
4616 * provider.addScope('repo');
4617 * await signInWithRedirect(auth, provider);
4618 * // This will trigger a full page redirect away from your app
4619 *
4620 * // After returning from the redirect when your app initializes you can obtain the result
4621 * const result = await getRedirectResult(auth);
4622 * if (result) {
4623 * // This is the signed-in user
4624 * const user = result.user;
4625 * // This gives you a Github Access Token.
4626 * const credential = GithubAuthProvider.credentialFromResult(result);
4627 * const token = credential.accessToken;
4628 * }
4629 * ```
4630 *
4631 * @example
4632 * ```javascript
4633 * // Sign in using a popup.
4634 * const provider = new GithubAuthProvider();
4635 * provider.addScope('repo');
4636 * const result = await signInWithPopup(auth, provider);
4637 *
4638 * // The signed-in user info.
4639 * const user = result.user;
4640 * // This gives you a Github Access Token.
4641 * const credential = GithubAuthProvider.credentialFromResult(result);
4642 * const token = credential.accessToken;
4643 * ```
4644 * @public
4645 */
4646var GithubAuthProvider = /** @class */ (function (_super) {
4647 tslib.__extends(GithubAuthProvider, _super);
4648 function GithubAuthProvider() {
4649 return _super.call(this, "github.com" /* GITHUB */) || this;
4650 }
4651 /**
4652 * Creates a credential for Github.
4653 *
4654 * @param accessToken - Github access token.
4655 */
4656 GithubAuthProvider.credential = function (accessToken) {
4657 return OAuthCredential._fromParams({
4658 providerId: GithubAuthProvider.PROVIDER_ID,
4659 signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
4660 accessToken: accessToken
4661 });
4662 };
4663 /**
4664 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4665 *
4666 * @param userCredential - The user credential.
4667 */
4668 GithubAuthProvider.credentialFromResult = function (userCredential) {
4669 return GithubAuthProvider.credentialFromTaggedObject(userCredential);
4670 };
4671 /**
4672 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4673 * thrown during a sign-in, link, or reauthenticate operation.
4674 *
4675 * @param userCredential - The user credential.
4676 */
4677 GithubAuthProvider.credentialFromError = function (error) {
4678 return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
4679 };
4680 GithubAuthProvider.credentialFromTaggedObject = function (_a) {
4681 var tokenResponse = _a._tokenResponse;
4682 if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
4683 return null;
4684 }
4685 if (!tokenResponse.oauthAccessToken) {
4686 return null;
4687 }
4688 try {
4689 return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
4690 }
4691 catch (_b) {
4692 return null;
4693 }
4694 };
4695 /** Always set to {@link SignInMethod}.GITHUB. */
4696 GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* GITHUB */;
4697 /** Always set to {@link ProviderId}.GITHUB. */
4698 GithubAuthProvider.PROVIDER_ID = "github.com" /* GITHUB */;
4699 return GithubAuthProvider;
4700}(BaseOAuthProvider));
4701
4702/**
4703 * @license
4704 * Copyright 2020 Google LLC
4705 *
4706 * Licensed under the Apache License, Version 2.0 (the "License");
4707 * you may not use this file except in compliance with the License.
4708 * You may obtain a copy of the License at
4709 *
4710 * http://www.apache.org/licenses/LICENSE-2.0
4711 *
4712 * Unless required by applicable law or agreed to in writing, software
4713 * distributed under the License is distributed on an "AS IS" BASIS,
4714 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4715 * See the License for the specific language governing permissions and
4716 * limitations under the License.
4717 */
4718var IDP_REQUEST_URI = 'http://localhost';
4719/**
4720 * @public
4721 */
4722var SAMLAuthCredential = /** @class */ (function (_super) {
4723 tslib.__extends(SAMLAuthCredential, _super);
4724 /** @internal */
4725 function SAMLAuthCredential(providerId, pendingToken) {
4726 var _this = _super.call(this, providerId, providerId) || this;
4727 _this.pendingToken = pendingToken;
4728 return _this;
4729 }
4730 /** @internal */
4731 SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
4732 var request = this.buildRequest();
4733 return signInWithIdp(auth, request);
4734 };
4735 /** @internal */
4736 SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
4737 var request = this.buildRequest();
4738 request.idToken = idToken;
4739 return signInWithIdp(auth, request);
4740 };
4741 /** @internal */
4742 SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
4743 var request = this.buildRequest();
4744 request.autoCreate = false;
4745 return signInWithIdp(auth, request);
4746 };
4747 /** {@inheritdoc AuthCredential.toJSON} */
4748 SAMLAuthCredential.prototype.toJSON = function () {
4749 return {
4750 signInMethod: this.signInMethod,
4751 providerId: this.providerId,
4752 pendingToken: this.pendingToken
4753 };
4754 };
4755 /**
4756 * Static method to deserialize a JSON representation of an object into an
4757 * {@link AuthCredential}.
4758 *
4759 * @param json - Input can be either Object or the stringified representation of the object.
4760 * When string is provided, JSON.parse would be called first.
4761 *
4762 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
4763 */
4764 SAMLAuthCredential.fromJSON = function (json) {
4765 var obj = typeof json === 'string' ? JSON.parse(json) : json;
4766 var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
4767 if (!providerId ||
4768 !signInMethod ||
4769 !pendingToken ||
4770 providerId !== signInMethod) {
4771 return null;
4772 }
4773 return new SAMLAuthCredential(providerId, pendingToken);
4774 };
4775 /**
4776 * Helper static method to avoid exposing the constructor to end users.
4777 *
4778 * @internal
4779 */
4780 SAMLAuthCredential._create = function (providerId, pendingToken) {
4781 return new SAMLAuthCredential(providerId, pendingToken);
4782 };
4783 SAMLAuthCredential.prototype.buildRequest = function () {
4784 return {
4785 requestUri: IDP_REQUEST_URI,
4786 returnSecureToken: true,
4787 pendingToken: this.pendingToken
4788 };
4789 };
4790 return SAMLAuthCredential;
4791}(AuthCredential));
4792
4793/**
4794 * @license
4795 * Copyright 2020 Google LLC
4796 *
4797 * Licensed under the Apache License, Version 2.0 (the "License");
4798 * you may not use this file except in compliance with the License.
4799 * You may obtain a copy of the License at
4800 *
4801 * http://www.apache.org/licenses/LICENSE-2.0
4802 *
4803 * Unless required by applicable law or agreed to in writing, software
4804 * distributed under the License is distributed on an "AS IS" BASIS,
4805 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4806 * See the License for the specific language governing permissions and
4807 * limitations under the License.
4808 */
4809var SAML_PROVIDER_PREFIX = 'saml.';
4810/**
4811 * An {@link AuthProvider} for SAML.
4812 *
4813 * @public
4814 */
4815var SAMLAuthProvider = /** @class */ (function (_super) {
4816 tslib.__extends(SAMLAuthProvider, _super);
4817 /**
4818 * Constructor. The providerId must start with "saml."
4819 * @param providerId - SAML provider ID.
4820 */
4821 function SAMLAuthProvider(providerId) {
4822 var _this = this;
4823 _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* ARGUMENT_ERROR */);
4824 _this = _super.call(this, providerId) || this;
4825 return _this;
4826 }
4827 /**
4828 * Generates an {@link AuthCredential} from a {@link UserCredential} after a
4829 * successful SAML flow completes.
4830 *
4831 * @remarks
4832 *
4833 * For example, to get an {@link AuthCredential}, you could write the
4834 * following code:
4835 *
4836 * ```js
4837 * const userCredential = await signInWithPopup(auth, samlProvider);
4838 * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
4839 * ```
4840 *
4841 * @param userCredential - The user credential.
4842 */
4843 SAMLAuthProvider.credentialFromResult = function (userCredential) {
4844 return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
4845 };
4846 /**
4847 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4848 * thrown during a sign-in, link, or reauthenticate operation.
4849 *
4850 * @param userCredential - The user credential.
4851 */
4852 SAMLAuthProvider.credentialFromError = function (error) {
4853 return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
4854 };
4855 /**
4856 * Creates an {@link AuthCredential} from a JSON string or a plain object.
4857 * @param json - A plain object or a JSON string
4858 */
4859 SAMLAuthProvider.credentialFromJSON = function (json) {
4860 var credential = SAMLAuthCredential.fromJSON(json);
4861 _assert(credential, "argument-error" /* ARGUMENT_ERROR */);
4862 return credential;
4863 };
4864 SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
4865 var tokenResponse = _a._tokenResponse;
4866 if (!tokenResponse) {
4867 return null;
4868 }
4869 var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
4870 if (!pendingToken || !providerId) {
4871 return null;
4872 }
4873 try {
4874 return SAMLAuthCredential._create(providerId, pendingToken);
4875 }
4876 catch (e) {
4877 return null;
4878 }
4879 };
4880 return SAMLAuthProvider;
4881}(FederatedAuthProvider));
4882
4883/**
4884 * @license
4885 * Copyright 2020 Google LLC
4886 *
4887 * Licensed under the Apache License, Version 2.0 (the "License");
4888 * you may not use this file except in compliance with the License.
4889 * You may obtain a copy of the License at
4890 *
4891 * http://www.apache.org/licenses/LICENSE-2.0
4892 *
4893 * Unless required by applicable law or agreed to in writing, software
4894 * distributed under the License is distributed on an "AS IS" BASIS,
4895 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4896 * See the License for the specific language governing permissions and
4897 * limitations under the License.
4898 */
4899/**
4900 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
4901 *
4902 * @example
4903 * ```javascript
4904 * // Sign in using a redirect.
4905 * const provider = new TwitterAuthProvider();
4906 * // Start a sign in process for an unauthenticated user.
4907 * await signInWithRedirect(auth, provider);
4908 * // This will trigger a full page redirect away from your app
4909 *
4910 * // After returning from the redirect when your app initializes you can obtain the result
4911 * const result = await getRedirectResult(auth);
4912 * if (result) {
4913 * // This is the signed-in user
4914 * const user = result.user;
4915 * // This gives you a Twitter Access Token and Secret.
4916 * const credential = TwitterAuthProvider.credentialFromResult(result);
4917 * const token = credential.accessToken;
4918 * const secret = credential.secret;
4919 * }
4920 * ```
4921 *
4922 * @example
4923 * ```javascript
4924 * // Sign in using a popup.
4925 * const provider = new TwitterAuthProvider();
4926 * const result = await signInWithPopup(auth, provider);
4927 *
4928 * // The signed-in user info.
4929 * const user = result.user;
4930 * // This gives you a Twitter Access Token and Secret.
4931 * const credential = TwitterAuthProvider.credentialFromResult(result);
4932 * const token = credential.accessToken;
4933 * const secret = credential.secret;
4934 * ```
4935 *
4936 * @public
4937 */
4938var TwitterAuthProvider = /** @class */ (function (_super) {
4939 tslib.__extends(TwitterAuthProvider, _super);
4940 function TwitterAuthProvider() {
4941 return _super.call(this, "twitter.com" /* TWITTER */) || this;
4942 }
4943 /**
4944 * Creates a credential for Twitter.
4945 *
4946 * @param token - Twitter access token.
4947 * @param secret - Twitter secret.
4948 */
4949 TwitterAuthProvider.credential = function (token, secret) {
4950 return OAuthCredential._fromParams({
4951 providerId: TwitterAuthProvider.PROVIDER_ID,
4952 signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
4953 oauthToken: token,
4954 oauthTokenSecret: secret
4955 });
4956 };
4957 /**
4958 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
4959 *
4960 * @param userCredential - The user credential.
4961 */
4962 TwitterAuthProvider.credentialFromResult = function (userCredential) {
4963 return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
4964 };
4965 /**
4966 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
4967 * thrown during a sign-in, link, or reauthenticate operation.
4968 *
4969 * @param userCredential - The user credential.
4970 */
4971 TwitterAuthProvider.credentialFromError = function (error) {
4972 return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
4973 };
4974 TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
4975 var tokenResponse = _a._tokenResponse;
4976 if (!tokenResponse) {
4977 return null;
4978 }
4979 var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
4980 if (!oauthAccessToken || !oauthTokenSecret) {
4981 return null;
4982 }
4983 try {
4984 return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
4985 }
4986 catch (_c) {
4987 return null;
4988 }
4989 };
4990 /** Always set to {@link SignInMethod}.TWITTER. */
4991 TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* TWITTER */;
4992 /** Always set to {@link ProviderId}.TWITTER. */
4993 TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* TWITTER */;
4994 return TwitterAuthProvider;
4995}(BaseOAuthProvider));
4996
4997/**
4998 * @license
4999 * Copyright 2020 Google LLC
5000 *
5001 * Licensed under the Apache License, Version 2.0 (the "License");
5002 * you may not use this file except in compliance with the License.
5003 * You may obtain a copy of the License at
5004 *
5005 * http://www.apache.org/licenses/LICENSE-2.0
5006 *
5007 * Unless required by applicable law or agreed to in writing, software
5008 * distributed under the License is distributed on an "AS IS" BASIS,
5009 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5010 * See the License for the specific language governing permissions and
5011 * limitations under the License.
5012 */
5013function signUp(auth, request) {
5014 return tslib.__awaiter(this, void 0, void 0, function () {
5015 return tslib.__generator(this, function (_a) {
5016 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signUp" /* SIGN_UP */, _addTidIfNecessary(auth, request))];
5017 });
5018 });
5019}
5020
5021/**
5022 * @license
5023 * Copyright 2020 Google LLC
5024 *
5025 * Licensed under the Apache License, Version 2.0 (the "License");
5026 * you may not use this file except in compliance with the License.
5027 * You may obtain a copy of the License at
5028 *
5029 * http://www.apache.org/licenses/LICENSE-2.0
5030 *
5031 * Unless required by applicable law or agreed to in writing, software
5032 * distributed under the License is distributed on an "AS IS" BASIS,
5033 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5034 * See the License for the specific language governing permissions and
5035 * limitations under the License.
5036 */
5037var UserCredentialImpl = /** @class */ (function () {
5038 function UserCredentialImpl(params) {
5039 this.user = params.user;
5040 this.providerId = params.providerId;
5041 this._tokenResponse = params._tokenResponse;
5042 this.operationType = params.operationType;
5043 }
5044 UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
5045 if (isAnonymous === void 0) { isAnonymous = false; }
5046 return tslib.__awaiter(this, void 0, void 0, function () {
5047 var user, providerId, userCred;
5048 return tslib.__generator(this, function (_a) {
5049 switch (_a.label) {
5050 case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
5051 case 1:
5052 user = _a.sent();
5053 providerId = providerIdForResponse(idTokenResponse);
5054 userCred = new UserCredentialImpl({
5055 user: user,
5056 providerId: providerId,
5057 _tokenResponse: idTokenResponse,
5058 operationType: operationType
5059 });
5060 return [2 /*return*/, userCred];
5061 }
5062 });
5063 });
5064 };
5065 UserCredentialImpl._forOperation = function (user, operationType, response) {
5066 return tslib.__awaiter(this, void 0, void 0, function () {
5067 var providerId;
5068 return tslib.__generator(this, function (_a) {
5069 switch (_a.label) {
5070 case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
5071 case 1:
5072 _a.sent();
5073 providerId = providerIdForResponse(response);
5074 return [2 /*return*/, new UserCredentialImpl({
5075 user: user,
5076 providerId: providerId,
5077 _tokenResponse: response,
5078 operationType: operationType
5079 })];
5080 }
5081 });
5082 });
5083 };
5084 return UserCredentialImpl;
5085}());
5086function providerIdForResponse(response) {
5087 if (response.providerId) {
5088 return response.providerId;
5089 }
5090 if ('phoneNumber' in response) {
5091 return "phone" /* PHONE */;
5092 }
5093 return null;
5094}
5095
5096/**
5097 * @license
5098 * Copyright 2020 Google LLC
5099 *
5100 * Licensed under the Apache License, Version 2.0 (the "License");
5101 * you may not use this file except in compliance with the License.
5102 * You may obtain a copy of the License at
5103 *
5104 * http://www.apache.org/licenses/LICENSE-2.0
5105 *
5106 * Unless required by applicable law or agreed to in writing, software
5107 * distributed under the License is distributed on an "AS IS" BASIS,
5108 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5109 * See the License for the specific language governing permissions and
5110 * limitations under the License.
5111 */
5112/**
5113 * Asynchronously signs in as an anonymous user.
5114 *
5115 * @remarks
5116 * If there is already an anonymous user signed in, that user will be returned; otherwise, a
5117 * new anonymous user identity will be created and returned.
5118 *
5119 * @param auth - The {@link Auth} instance.
5120 *
5121 * @public
5122 */
5123function signInAnonymously(auth) {
5124 var _a;
5125 return tslib.__awaiter(this, void 0, void 0, function () {
5126 var authInternal, response, userCredential;
5127 return tslib.__generator(this, function (_b) {
5128 switch (_b.label) {
5129 case 0:
5130 authInternal = _castAuth(auth);
5131 return [4 /*yield*/, authInternal._initializationPromise];
5132 case 1:
5133 _b.sent();
5134 if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
5135 // If an anonymous user is already signed in, no need to sign them in again.
5136 return [2 /*return*/, new UserCredentialImpl({
5137 user: authInternal.currentUser,
5138 providerId: null,
5139 operationType: "signIn" /* SIGN_IN */
5140 })];
5141 }
5142 return [4 /*yield*/, signUp(authInternal, {
5143 returnSecureToken: true
5144 })];
5145 case 2:
5146 response = _b.sent();
5147 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response, true)];
5148 case 3:
5149 userCredential = _b.sent();
5150 return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
5151 case 4:
5152 _b.sent();
5153 return [2 /*return*/, userCredential];
5154 }
5155 });
5156 });
5157}
5158
5159/**
5160 * @license
5161 * Copyright 2020 Google LLC
5162 *
5163 * Licensed under the Apache License, Version 2.0 (the "License");
5164 * you may not use this file except in compliance with the License.
5165 * You may obtain a copy of the License at
5166 *
5167 * http://www.apache.org/licenses/LICENSE-2.0
5168 *
5169 * Unless required by applicable law or agreed to in writing, software
5170 * distributed under the License is distributed on an "AS IS" BASIS,
5171 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5172 * See the License for the specific language governing permissions and
5173 * limitations under the License.
5174 */
5175var MultiFactorError = /** @class */ (function (_super) {
5176 tslib.__extends(MultiFactorError, _super);
5177 function MultiFactorError(auth, error, operationType, user) {
5178 var _a;
5179 var _this = _super.call(this, error.code, error.message) || this;
5180 _this.operationType = operationType;
5181 _this.user = user;
5182 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
5183 Object.setPrototypeOf(_this, MultiFactorError.prototype);
5184 _this.customData = {
5185 appName: auth.name,
5186 tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
5187 _serverResponse: error.customData._serverResponse,
5188 operationType: operationType,
5189 };
5190 return _this;
5191 }
5192 MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
5193 return new MultiFactorError(auth, error, operationType, user);
5194 };
5195 return MultiFactorError;
5196}(util.FirebaseError));
5197function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
5198 var idTokenProvider = operationType === "reauthenticate" /* REAUTHENTICATE */
5199 ? credential._getReauthenticationResolver(auth)
5200 : credential._getIdTokenResponse(auth);
5201 return idTokenProvider.catch(function (error) {
5202 if (error.code === "auth/" + "multi-factor-auth-required" /* MFA_REQUIRED */) {
5203 throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
5204 }
5205 throw error;
5206 });
5207}
5208
5209/**
5210 * @license
5211 * Copyright 2020 Google LLC
5212 *
5213 * Licensed under the Apache License, Version 2.0 (the "License");
5214 * you may not use this file except in compliance with the License.
5215 * You may obtain a copy of the License at
5216 *
5217 * http://www.apache.org/licenses/LICENSE-2.0
5218 *
5219 * Unless required by applicable law or agreed to in writing, software
5220 * distributed under the License is distributed on an "AS IS" BASIS,
5221 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5222 * See the License for the specific language governing permissions and
5223 * limitations under the License.
5224 */
5225/**
5226 * Takes a set of UserInfo provider data and converts it to a set of names
5227 */
5228function providerDataAsNames(providerData) {
5229 return new Set(providerData
5230 .map(function (_a) {
5231 var providerId = _a.providerId;
5232 return providerId;
5233 })
5234 .filter(function (pid) { return !!pid; }));
5235}
5236
5237/**
5238 * @license
5239 * Copyright 2019 Google LLC
5240 *
5241 * Licensed under the Apache License, Version 2.0 (the "License");
5242 * you may not use this file except in compliance with the License.
5243 * You may obtain a copy of the License at
5244 *
5245 * http://www.apache.org/licenses/LICENSE-2.0
5246 *
5247 * Unless required by applicable law or agreed to in writing, software
5248 * distributed under the License is distributed on an "AS IS" BASIS,
5249 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5250 * See the License for the specific language governing permissions and
5251 * limitations under the License.
5252 */
5253/**
5254 * Unlinks a provider from a user account.
5255 *
5256 * @param user - The user.
5257 * @param providerId - The provider to unlink.
5258 *
5259 * @public
5260 */
5261function unlink(user, providerId) {
5262 return tslib.__awaiter(this, void 0, void 0, function () {
5263 var userInternal, providerUserInfo, _a, _b, providersLeft;
5264 var _c;
5265 return tslib.__generator(this, function (_d) {
5266 switch (_d.label) {
5267 case 0:
5268 userInternal = util.getModularInstance(user);
5269 return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
5270 case 1:
5271 _d.sent();
5272 _a = deleteLinkedAccounts;
5273 _b = [userInternal.auth];
5274 _c = {};
5275 return [4 /*yield*/, userInternal.getIdToken()];
5276 case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
5277 _c.deleteProvider = [providerId],
5278 _c)]))];
5279 case 3:
5280 providerUserInfo = (_d.sent()).providerUserInfo;
5281 providersLeft = providerDataAsNames(providerUserInfo || []);
5282 userInternal.providerData = userInternal.providerData.filter(function (pd) {
5283 return providersLeft.has(pd.providerId);
5284 });
5285 if (!providersLeft.has("phone" /* PHONE */)) {
5286 userInternal.phoneNumber = null;
5287 }
5288 return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
5289 case 4:
5290 _d.sent();
5291 return [2 /*return*/, userInternal];
5292 }
5293 });
5294 });
5295}
5296function _link(user, credential, bypassAuthState) {
5297 if (bypassAuthState === void 0) { bypassAuthState = false; }
5298 return tslib.__awaiter(this, void 0, void 0, function () {
5299 var response, _a, _b, _c, _d, _e;
5300 return tslib.__generator(this, function (_f) {
5301 switch (_f.label) {
5302 case 0:
5303 _a = _logoutIfInvalidated;
5304 _b = [user];
5305 _d = (_c = credential)._linkToIdToken;
5306 _e = [user.auth];
5307 return [4 /*yield*/, user.getIdToken()];
5308 case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])), bypassAuthState]))];
5309 case 2:
5310 response = _f.sent();
5311 return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* LINK */, response)];
5312 }
5313 });
5314 });
5315}
5316function _assertLinkedStatus(expected, user, provider) {
5317 return tslib.__awaiter(this, void 0, void 0, function () {
5318 var providerIds, code;
5319 return tslib.__generator(this, function (_a) {
5320 switch (_a.label) {
5321 case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
5322 case 1:
5323 _a.sent();
5324 providerIds = providerDataAsNames(user.providerData);
5325 code = expected === false
5326 ? "provider-already-linked" /* PROVIDER_ALREADY_LINKED */
5327 : "no-such-provider" /* NO_SUCH_PROVIDER */;
5328 _assert(providerIds.has(provider) === expected, user.auth, code);
5329 return [2 /*return*/];
5330 }
5331 });
5332 });
5333}
5334
5335/**
5336 * @license
5337 * Copyright 2019 Google LLC
5338 *
5339 * Licensed under the Apache License, Version 2.0 (the "License");
5340 * you may not use this file except in compliance with the License.
5341 * You may obtain a copy of the License at
5342 *
5343 * http://www.apache.org/licenses/LICENSE-2.0
5344 *
5345 * Unless required by applicable law or agreed to in writing, software
5346 * distributed under the License is distributed on an "AS IS" BASIS,
5347 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5348 * See the License for the specific language governing permissions and
5349 * limitations under the License.
5350 */
5351function _reauthenticate(user, credential, bypassAuthState) {
5352 var _a;
5353 if (bypassAuthState === void 0) { bypassAuthState = false; }
5354 return tslib.__awaiter(this, void 0, void 0, function () {
5355 var auth, operationType, response, parsed, localId, e_1;
5356 return tslib.__generator(this, function (_b) {
5357 switch (_b.label) {
5358 case 0:
5359 auth = user.auth;
5360 operationType = "reauthenticate" /* REAUTHENTICATE */;
5361 _b.label = 1;
5362 case 1:
5363 _b.trys.push([1, 3, , 4]);
5364 return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
5365 case 2:
5366 response = _b.sent();
5367 _assert(response.idToken, auth, "internal-error" /* INTERNAL_ERROR */);
5368 parsed = _parseToken(response.idToken);
5369 _assert(parsed, auth, "internal-error" /* INTERNAL_ERROR */);
5370 localId = parsed.sub;
5371 _assert(user.uid === localId, auth, "user-mismatch" /* USER_MISMATCH */);
5372 return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
5373 case 3:
5374 e_1 = _b.sent();
5375 // Convert user deleted error into user mismatch
5376 if (((_a = e_1) === null || _a === void 0 ? void 0 : _a.code) === "auth/" + "user-not-found" /* USER_DELETED */) {
5377 _fail(auth, "user-mismatch" /* USER_MISMATCH */);
5378 }
5379 throw e_1;
5380 case 4: return [2 /*return*/];
5381 }
5382 });
5383 });
5384}
5385
5386/**
5387 * @license
5388 * Copyright 2020 Google LLC
5389 *
5390 * Licensed under the Apache License, Version 2.0 (the "License");
5391 * you may not use this file except in compliance with the License.
5392 * You may obtain a copy of the License at
5393 *
5394 * http://www.apache.org/licenses/LICENSE-2.0
5395 *
5396 * Unless required by applicable law or agreed to in writing, software
5397 * distributed under the License is distributed on an "AS IS" BASIS,
5398 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5399 * See the License for the specific language governing permissions and
5400 * limitations under the License.
5401 */
5402function _signInWithCredential(auth, credential, bypassAuthState) {
5403 if (bypassAuthState === void 0) { bypassAuthState = false; }
5404 return tslib.__awaiter(this, void 0, void 0, function () {
5405 var operationType, response, userCredential;
5406 return tslib.__generator(this, function (_a) {
5407 switch (_a.label) {
5408 case 0:
5409 operationType = "signIn" /* SIGN_IN */;
5410 return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
5411 case 1:
5412 response = _a.sent();
5413 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
5414 case 2:
5415 userCredential = _a.sent();
5416 if (!!bypassAuthState) return [3 /*break*/, 4];
5417 return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
5418 case 3:
5419 _a.sent();
5420 _a.label = 4;
5421 case 4: return [2 /*return*/, userCredential];
5422 }
5423 });
5424 });
5425}
5426/**
5427 * Asynchronously signs in with the given credentials.
5428 *
5429 * @remarks
5430 * An {@link AuthProvider} can be used to generate the credential.
5431 *
5432 * @param auth - The {@link Auth} instance.
5433 * @param credential - The auth credential.
5434 *
5435 * @public
5436 */
5437function signInWithCredential(auth, credential) {
5438 return tslib.__awaiter(this, void 0, void 0, function () {
5439 return tslib.__generator(this, function (_a) {
5440 return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
5441 });
5442 });
5443}
5444/**
5445 * Links the user account with the given credentials.
5446 *
5447 * @remarks
5448 * An {@link AuthProvider} can be used to generate the credential.
5449 *
5450 * @param user - The user.
5451 * @param credential - The auth credential.
5452 *
5453 * @public
5454 */
5455function linkWithCredential(user, credential) {
5456 return tslib.__awaiter(this, void 0, void 0, function () {
5457 var userInternal;
5458 return tslib.__generator(this, function (_a) {
5459 switch (_a.label) {
5460 case 0:
5461 userInternal = util.getModularInstance(user);
5462 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
5463 case 1:
5464 _a.sent();
5465 return [2 /*return*/, _link(userInternal, credential)];
5466 }
5467 });
5468 });
5469}
5470/**
5471 * Re-authenticates a user using a fresh credential.
5472 *
5473 * @remarks
5474 * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
5475 * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
5476 *
5477 * @param user - The user.
5478 * @param credential - The auth credential.
5479 *
5480 * @public
5481 */
5482function reauthenticateWithCredential(user, credential) {
5483 return tslib.__awaiter(this, void 0, void 0, function () {
5484 return tslib.__generator(this, function (_a) {
5485 return [2 /*return*/, _reauthenticate(util.getModularInstance(user), credential)];
5486 });
5487 });
5488}
5489
5490/**
5491 * @license
5492 * Copyright 2020 Google LLC
5493 *
5494 * Licensed under the Apache License, Version 2.0 (the "License");
5495 * you may not use this file except in compliance with the License.
5496 * You may obtain a copy of the License at
5497 *
5498 * http://www.apache.org/licenses/LICENSE-2.0
5499 *
5500 * Unless required by applicable law or agreed to in writing, software
5501 * distributed under the License is distributed on an "AS IS" BASIS,
5502 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5503 * See the License for the specific language governing permissions and
5504 * limitations under the License.
5505 */
5506function signInWithCustomToken$1(auth, request) {
5507 return tslib.__awaiter(this, void 0, void 0, function () {
5508 return tslib.__generator(this, function (_a) {
5509 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithCustomToken" /* SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
5510 });
5511 });
5512}
5513
5514/**
5515 * @license
5516 * Copyright 2020 Google LLC
5517 *
5518 * Licensed under the Apache License, Version 2.0 (the "License");
5519 * you may not use this file except in compliance with the License.
5520 * You may obtain a copy of the License at
5521 *
5522 * http://www.apache.org/licenses/LICENSE-2.0
5523 *
5524 * Unless required by applicable law or agreed to in writing, software
5525 * distributed under the License is distributed on an "AS IS" BASIS,
5526 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5527 * See the License for the specific language governing permissions and
5528 * limitations under the License.
5529 */
5530/**
5531 * Asynchronously signs in using a custom token.
5532 *
5533 * @remarks
5534 * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
5535 * be generated by an auth backend using the
5536 * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
5537 * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
5538 *
5539 * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
5540 *
5541 * @param auth - The {@link Auth} instance.
5542 * @param customToken - The custom token to sign in with.
5543 *
5544 * @public
5545 */
5546function signInWithCustomToken(auth, customToken) {
5547 return tslib.__awaiter(this, void 0, void 0, function () {
5548 var authInternal, response, cred;
5549 return tslib.__generator(this, function (_a) {
5550 switch (_a.label) {
5551 case 0:
5552 authInternal = _castAuth(auth);
5553 return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
5554 token: customToken,
5555 returnSecureToken: true
5556 })];
5557 case 1:
5558 response = _a.sent();
5559 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response)];
5560 case 2:
5561 cred = _a.sent();
5562 return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
5563 case 3:
5564 _a.sent();
5565 return [2 /*return*/, cred];
5566 }
5567 });
5568 });
5569}
5570
5571/**
5572 * @license
5573 * Copyright 2020 Google LLC
5574 *
5575 * Licensed under the Apache License, Version 2.0 (the "License");
5576 * you may not use this file except in compliance with the License.
5577 * You may obtain a copy of the License at
5578 *
5579 * http://www.apache.org/licenses/LICENSE-2.0
5580 *
5581 * Unless required by applicable law or agreed to in writing, software
5582 * distributed under the License is distributed on an "AS IS" BASIS,
5583 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5584 * See the License for the specific language governing permissions and
5585 * limitations under the License.
5586 */
5587var MultiFactorInfoImpl = /** @class */ (function () {
5588 function MultiFactorInfoImpl(factorId, response) {
5589 this.factorId = factorId;
5590 this.uid = response.mfaEnrollmentId;
5591 this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
5592 this.displayName = response.displayName;
5593 }
5594 MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
5595 if ('phoneInfo' in enrollment) {
5596 return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
5597 }
5598 return _fail(auth, "internal-error" /* INTERNAL_ERROR */);
5599 };
5600 return MultiFactorInfoImpl;
5601}());
5602var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
5603 tslib.__extends(PhoneMultiFactorInfoImpl, _super);
5604 function PhoneMultiFactorInfoImpl(response) {
5605 var _this = _super.call(this, "phone" /* PHONE */, response) || this;
5606 _this.phoneNumber = response.phoneInfo;
5607 return _this;
5608 }
5609 PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
5610 return new PhoneMultiFactorInfoImpl(enrollment);
5611 };
5612 return PhoneMultiFactorInfoImpl;
5613}(MultiFactorInfoImpl));
5614
5615/**
5616 * @license
5617 * Copyright 2020 Google LLC
5618 *
5619 * Licensed under the Apache License, Version 2.0 (the "License");
5620 * you may not use this file except in compliance with the License.
5621 * You may obtain a copy of the License at
5622 *
5623 * http://www.apache.org/licenses/LICENSE-2.0
5624 *
5625 * Unless required by applicable law or agreed to in writing, software
5626 * distributed under the License is distributed on an "AS IS" BASIS,
5627 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5628 * See the License for the specific language governing permissions and
5629 * limitations under the License.
5630 */
5631function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
5632 var _a;
5633 _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* INVALID_CONTINUE_URI */);
5634 _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
5635 actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* INVALID_DYNAMIC_LINK_DOMAIN */);
5636 request.continueUrl = actionCodeSettings.url;
5637 request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
5638 request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
5639 if (actionCodeSettings.iOS) {
5640 _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* MISSING_IOS_BUNDLE_ID */);
5641 request.iOSBundleId = actionCodeSettings.iOS.bundleId;
5642 }
5643 if (actionCodeSettings.android) {
5644 _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */);
5645 request.androidInstallApp = actionCodeSettings.android.installApp;
5646 request.androidMinimumVersionCode =
5647 actionCodeSettings.android.minimumVersion;
5648 request.androidPackageName = actionCodeSettings.android.packageName;
5649 }
5650}
5651
5652/**
5653 * @license
5654 * Copyright 2020 Google LLC
5655 *
5656 * Licensed under the Apache License, Version 2.0 (the "License");
5657 * you may not use this file except in compliance with the License.
5658 * You may obtain a copy of the License at
5659 *
5660 * http://www.apache.org/licenses/LICENSE-2.0
5661 *
5662 * Unless required by applicable law or agreed to in writing, software
5663 * distributed under the License is distributed on an "AS IS" BASIS,
5664 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5665 * See the License for the specific language governing permissions and
5666 * limitations under the License.
5667 */
5668/**
5669 * Sends a password reset email to the given email address.
5670 *
5671 * @remarks
5672 * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
5673 * the email sent to the user, along with the new password specified by the user.
5674 *
5675 * @example
5676 * ```javascript
5677 * const actionCodeSettings = {
5678 * url: 'https://www.example.com/?email=user@example.com',
5679 * iOS: {
5680 * bundleId: 'com.example.ios'
5681 * },
5682 * android: {
5683 * packageName: 'com.example.android',
5684 * installApp: true,
5685 * minimumVersion: '12'
5686 * },
5687 * handleCodeInApp: true
5688 * };
5689 * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
5690 * // Obtain code from user.
5691 * await confirmPasswordReset('user@example.com', code);
5692 * ```
5693 *
5694 * @param auth - The {@link Auth} instance.
5695 * @param email - The user's email address.
5696 * @param actionCodeSettings - The {@link ActionCodeSettings}.
5697 *
5698 * @public
5699 */
5700function sendPasswordResetEmail(auth, email, actionCodeSettings) {
5701 return tslib.__awaiter(this, void 0, void 0, function () {
5702 var authModular, request;
5703 return tslib.__generator(this, function (_a) {
5704 switch (_a.label) {
5705 case 0:
5706 authModular = util.getModularInstance(auth);
5707 request = {
5708 requestType: "PASSWORD_RESET" /* PASSWORD_RESET */,
5709 email: email
5710 };
5711 if (actionCodeSettings) {
5712 _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
5713 }
5714 return [4 /*yield*/, sendPasswordResetEmail$1(authModular, request)];
5715 case 1:
5716 _a.sent();
5717 return [2 /*return*/];
5718 }
5719 });
5720 });
5721}
5722/**
5723 * Completes the password reset process, given a confirmation code and new password.
5724 *
5725 * @param auth - The {@link Auth} instance.
5726 * @param oobCode - A confirmation code sent to the user.
5727 * @param newPassword - The new password.
5728 *
5729 * @public
5730 */
5731function confirmPasswordReset(auth, oobCode, newPassword) {
5732 return tslib.__awaiter(this, void 0, void 0, function () {
5733 return tslib.__generator(this, function (_a) {
5734 switch (_a.label) {
5735 case 0: return [4 /*yield*/, resetPassword(util.getModularInstance(auth), {
5736 oobCode: oobCode,
5737 newPassword: newPassword
5738 })];
5739 case 1:
5740 _a.sent();
5741 return [2 /*return*/];
5742 }
5743 });
5744 });
5745}
5746/**
5747 * Applies a verification code sent to the user by email or other out-of-band mechanism.
5748 *
5749 * @param auth - The {@link Auth} instance.
5750 * @param oobCode - A verification code sent to the user.
5751 *
5752 * @public
5753 */
5754function applyActionCode(auth, oobCode) {
5755 return tslib.__awaiter(this, void 0, void 0, function () {
5756 return tslib.__generator(this, function (_a) {
5757 switch (_a.label) {
5758 case 0: return [4 /*yield*/, applyActionCode$1(util.getModularInstance(auth), { oobCode: oobCode })];
5759 case 1:
5760 _a.sent();
5761 return [2 /*return*/];
5762 }
5763 });
5764 });
5765}
5766/**
5767 * Checks a verification code sent to the user by email or other out-of-band mechanism.
5768 *
5769 * @returns metadata about the code.
5770 *
5771 * @param auth - The {@link Auth} instance.
5772 * @param oobCode - A verification code sent to the user.
5773 *
5774 * @public
5775 */
5776function checkActionCode(auth, oobCode) {
5777 return tslib.__awaiter(this, void 0, void 0, function () {
5778 var authModular, response, operation, multiFactorInfo;
5779 return tslib.__generator(this, function (_a) {
5780 switch (_a.label) {
5781 case 0:
5782 authModular = util.getModularInstance(auth);
5783 return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
5784 case 1:
5785 response = _a.sent();
5786 operation = response.requestType;
5787 _assert(operation, authModular, "internal-error" /* INTERNAL_ERROR */);
5788 switch (operation) {
5789 case "EMAIL_SIGNIN" /* EMAIL_SIGNIN */:
5790 break;
5791 case "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */:
5792 _assert(response.newEmail, authModular, "internal-error" /* INTERNAL_ERROR */);
5793 break;
5794 case "REVERT_SECOND_FACTOR_ADDITION" /* REVERT_SECOND_FACTOR_ADDITION */:
5795 _assert(response.mfaInfo, authModular, "internal-error" /* INTERNAL_ERROR */);
5796 // fall through
5797 default:
5798 _assert(response.email, authModular, "internal-error" /* INTERNAL_ERROR */);
5799 }
5800 multiFactorInfo = null;
5801 if (response.mfaInfo) {
5802 multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
5803 }
5804 return [2 /*return*/, {
5805 data: {
5806 email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */
5807 ? response.newEmail
5808 : response.email) || null,
5809 previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */
5810 ? response.email
5811 : response.newEmail) || null,
5812 multiFactorInfo: multiFactorInfo
5813 },
5814 operation: operation
5815 }];
5816 }
5817 });
5818 });
5819}
5820/**
5821 * Checks a password reset code sent to the user by email or other out-of-band mechanism.
5822 *
5823 * @returns the user's email address if valid.
5824 *
5825 * @param auth - The {@link Auth} instance.
5826 * @param code - A verification code sent to the user.
5827 *
5828 * @public
5829 */
5830function verifyPasswordResetCode(auth, code) {
5831 return tslib.__awaiter(this, void 0, void 0, function () {
5832 var data;
5833 return tslib.__generator(this, function (_a) {
5834 switch (_a.label) {
5835 case 0: return [4 /*yield*/, checkActionCode(util.getModularInstance(auth), code)];
5836 case 1:
5837 data = (_a.sent()).data;
5838 // Email should always be present since a code was sent to it
5839 return [2 /*return*/, data.email];
5840 }
5841 });
5842 });
5843}
5844/**
5845 * Creates a new user account associated with the specified email address and password.
5846 *
5847 * @remarks
5848 * On successful creation of the user account, this user will also be signed in to your application.
5849 *
5850 * User account creation can fail if the account already exists or the password is invalid.
5851 *
5852 * Note: The email address acts as a unique identifier for the user and enables an email-based
5853 * password reset. This function will create a new user account and set the initial user password.
5854 *
5855 * @param auth - The {@link Auth} instance.
5856 * @param email - The user's email address.
5857 * @param password - The user's chosen password.
5858 *
5859 * @public
5860 */
5861function createUserWithEmailAndPassword(auth, email, password) {
5862 return tslib.__awaiter(this, void 0, void 0, function () {
5863 var authInternal, response, userCredential;
5864 return tslib.__generator(this, function (_a) {
5865 switch (_a.label) {
5866 case 0:
5867 authInternal = _castAuth(auth);
5868 return [4 /*yield*/, signUp(authInternal, {
5869 returnSecureToken: true,
5870 email: email,
5871 password: password
5872 })];
5873 case 1:
5874 response = _a.sent();
5875 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response)];
5876 case 2:
5877 userCredential = _a.sent();
5878 return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
5879 case 3:
5880 _a.sent();
5881 return [2 /*return*/, userCredential];
5882 }
5883 });
5884 });
5885}
5886/**
5887 * Asynchronously signs in using an email and password.
5888 *
5889 * @remarks
5890 * Fails with an error if the email address and password do not match.
5891 *
5892 * Note: The user's password is NOT the password used to access the user's email account. The
5893 * email address serves as a unique identifier for the user, and the password is used to access
5894 * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
5895 *
5896 * @param auth - The {@link Auth} instance.
5897 * @param email - The users email address.
5898 * @param password - The users password.
5899 *
5900 * @public
5901 */
5902function signInWithEmailAndPassword(auth, email, password) {
5903 return signInWithCredential(util.getModularInstance(auth), EmailAuthProvider.credential(email, password));
5904}
5905
5906/**
5907 * @license
5908 * Copyright 2020 Google LLC
5909 *
5910 * Licensed under the Apache License, Version 2.0 (the "License");
5911 * you may not use this file except in compliance with the License.
5912 * You may obtain a copy of the License at
5913 *
5914 * http://www.apache.org/licenses/LICENSE-2.0
5915 *
5916 * Unless required by applicable law or agreed to in writing, software
5917 * distributed under the License is distributed on an "AS IS" BASIS,
5918 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5919 * See the License for the specific language governing permissions and
5920 * limitations under the License.
5921 */
5922/**
5923 * Sends a sign-in email link to the user with the specified email.
5924 *
5925 * @remarks
5926 * The sign-in operation has to always be completed in the app unlike other out of band email
5927 * actions (password reset and email verifications). This is because, at the end of the flow,
5928 * the user is expected to be signed in and their Auth state persisted within the app.
5929 *
5930 * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
5931 * address and the email link supplied in the email sent to the user.
5932 *
5933 * @example
5934 * ```javascript
5935 * const actionCodeSettings = {
5936 * url: 'https://www.example.com/?email=user@example.com',
5937 * iOS: {
5938 * bundleId: 'com.example.ios'
5939 * },
5940 * android: {
5941 * packageName: 'com.example.android',
5942 * installApp: true,
5943 * minimumVersion: '12'
5944 * },
5945 * handleCodeInApp: true
5946 * };
5947 * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
5948 * // Obtain emailLink from the user.
5949 * if(isSignInWithEmailLink(auth, emailLink)) {
5950 * await signInWithEmailLink(auth, 'user@example.com', emailLink);
5951 * }
5952 * ```
5953 *
5954 * @param authInternal - The {@link Auth} instance.
5955 * @param email - The user's email address.
5956 * @param actionCodeSettings - The {@link ActionCodeSettings}.
5957 *
5958 * @public
5959 */
5960function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
5961 return tslib.__awaiter(this, void 0, void 0, function () {
5962 var authModular, request;
5963 return tslib.__generator(this, function (_a) {
5964 switch (_a.label) {
5965 case 0:
5966 authModular = util.getModularInstance(auth);
5967 request = {
5968 requestType: "EMAIL_SIGNIN" /* EMAIL_SIGNIN */,
5969 email: email
5970 };
5971 _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* ARGUMENT_ERROR */);
5972 if (actionCodeSettings) {
5973 _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
5974 }
5975 return [4 /*yield*/, sendSignInLinkToEmail$1(authModular, request)];
5976 case 1:
5977 _a.sent();
5978 return [2 /*return*/];
5979 }
5980 });
5981 });
5982}
5983/**
5984 * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
5985 *
5986 * @param auth - The {@link Auth} instance.
5987 * @param emailLink - The link sent to the user's email address.
5988 *
5989 * @public
5990 */
5991function isSignInWithEmailLink(auth, emailLink) {
5992 var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
5993 return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* EMAIL_SIGNIN */;
5994}
5995/**
5996 * Asynchronously signs in using an email and sign-in email link.
5997 *
5998 * @remarks
5999 * If no link is passed, the link is inferred from the current URL.
6000 *
6001 * Fails with an error if the email address is invalid or OTP in email link expires.
6002 *
6003 * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
6004 *
6005 * @example
6006 * ```javascript
6007 * const actionCodeSettings = {
6008 * url: 'https://www.example.com/?email=user@example.com',
6009 * iOS: {
6010 * bundleId: 'com.example.ios'
6011 * },
6012 * android: {
6013 * packageName: 'com.example.android',
6014 * installApp: true,
6015 * minimumVersion: '12'
6016 * },
6017 * handleCodeInApp: true
6018 * };
6019 * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
6020 * // Obtain emailLink from the user.
6021 * if(isSignInWithEmailLink(auth, emailLink)) {
6022 * await signInWithEmailLink(auth, 'user@example.com', emailLink);
6023 * }
6024 * ```
6025 *
6026 * @param auth - The {@link Auth} instance.
6027 * @param email - The user's email address.
6028 * @param emailLink - The link sent to the user's email address.
6029 *
6030 * @public
6031 */
6032function signInWithEmailLink(auth, email, emailLink) {
6033 return tslib.__awaiter(this, void 0, void 0, function () {
6034 var authModular, credential;
6035 return tslib.__generator(this, function (_a) {
6036 authModular = util.getModularInstance(auth);
6037 credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
6038 // Check if the tenant ID in the email link matches the tenant ID on Auth
6039 // instance.
6040 _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* TENANT_ID_MISMATCH */);
6041 return [2 /*return*/, signInWithCredential(authModular, credential)];
6042 });
6043 });
6044}
6045
6046/**
6047 * @license
6048 * Copyright 2020 Google LLC
6049 *
6050 * Licensed under the Apache License, Version 2.0 (the "License");
6051 * you may not use this file except in compliance with the License.
6052 * You may obtain a copy of the License at
6053 *
6054 * http://www.apache.org/licenses/LICENSE-2.0
6055 *
6056 * Unless required by applicable law or agreed to in writing, software
6057 * distributed under the License is distributed on an "AS IS" BASIS,
6058 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6059 * See the License for the specific language governing permissions and
6060 * limitations under the License.
6061 */
6062function createAuthUri(auth, request) {
6063 return tslib.__awaiter(this, void 0, void 0, function () {
6064 return tslib.__generator(this, function (_a) {
6065 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:createAuthUri" /* CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
6066 });
6067 });
6068}
6069
6070/**
6071 * @license
6072 * Copyright 2020 Google LLC
6073 *
6074 * Licensed under the Apache License, Version 2.0 (the "License");
6075 * you may not use this file except in compliance with the License.
6076 * You may obtain a copy of the License at
6077 *
6078 * http://www.apache.org/licenses/LICENSE-2.0
6079 *
6080 * Unless required by applicable law or agreed to in writing, software
6081 * distributed under the License is distributed on an "AS IS" BASIS,
6082 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6083 * See the License for the specific language governing permissions and
6084 * limitations under the License.
6085 */
6086/**
6087 * Gets the list of possible sign in methods for the given email address.
6088 *
6089 * @remarks
6090 * This is useful to differentiate methods of sign-in for the same provider, eg.
6091 * {@link EmailAuthProvider} which has 2 methods of sign-in,
6092 * {@link SignInMethod}.EMAIL_PASSWORD and
6093 * {@link SignInMethod}.EMAIL_LINK.
6094 *
6095 * @param auth - The {@link Auth} instance.
6096 * @param email - The user's email address.
6097 *
6098 * @public
6099 */
6100function fetchSignInMethodsForEmail(auth, email) {
6101 return tslib.__awaiter(this, void 0, void 0, function () {
6102 var continueUri, request, signinMethods;
6103 return tslib.__generator(this, function (_a) {
6104 switch (_a.label) {
6105 case 0:
6106 continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
6107 request = {
6108 identifier: email,
6109 continueUri: continueUri
6110 };
6111 return [4 /*yield*/, createAuthUri(util.getModularInstance(auth), request)];
6112 case 1:
6113 signinMethods = (_a.sent()).signinMethods;
6114 return [2 /*return*/, signinMethods || []];
6115 }
6116 });
6117 });
6118}
6119/**
6120 * Sends a verification email to a user.
6121 *
6122 * @remarks
6123 * The verification process is completed by calling {@link applyActionCode}.
6124 *
6125 * @example
6126 * ```javascript
6127 * const actionCodeSettings = {
6128 * url: 'https://www.example.com/?email=user@example.com',
6129 * iOS: {
6130 * bundleId: 'com.example.ios'
6131 * },
6132 * android: {
6133 * packageName: 'com.example.android',
6134 * installApp: true,
6135 * minimumVersion: '12'
6136 * },
6137 * handleCodeInApp: true
6138 * };
6139 * await sendEmailVerification(user, actionCodeSettings);
6140 * // Obtain code from the user.
6141 * await applyActionCode(auth, code);
6142 * ```
6143 *
6144 * @param user - The user.
6145 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6146 *
6147 * @public
6148 */
6149function sendEmailVerification(user, actionCodeSettings) {
6150 return tslib.__awaiter(this, void 0, void 0, function () {
6151 var userInternal, idToken, request, email;
6152 return tslib.__generator(this, function (_a) {
6153 switch (_a.label) {
6154 case 0:
6155 userInternal = util.getModularInstance(user);
6156 return [4 /*yield*/, user.getIdToken()];
6157 case 1:
6158 idToken = _a.sent();
6159 request = {
6160 requestType: "VERIFY_EMAIL" /* VERIFY_EMAIL */,
6161 idToken: idToken
6162 };
6163 if (actionCodeSettings) {
6164 _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
6165 }
6166 return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
6167 case 2:
6168 email = (_a.sent()).email;
6169 if (!(email !== user.email)) return [3 /*break*/, 4];
6170 return [4 /*yield*/, user.reload()];
6171 case 3:
6172 _a.sent();
6173 _a.label = 4;
6174 case 4: return [2 /*return*/];
6175 }
6176 });
6177 });
6178}
6179/**
6180 * Sends a verification email to a new email address.
6181 *
6182 * @remarks
6183 * The user's email will be updated to the new one after being verified.
6184 *
6185 * If you have a custom email action handler, you can complete the verification process by calling
6186 * {@link applyActionCode}.
6187 *
6188 * @example
6189 * ```javascript
6190 * const actionCodeSettings = {
6191 * url: 'https://www.example.com/?email=user@example.com',
6192 * iOS: {
6193 * bundleId: 'com.example.ios'
6194 * },
6195 * android: {
6196 * packageName: 'com.example.android',
6197 * installApp: true,
6198 * minimumVersion: '12'
6199 * },
6200 * handleCodeInApp: true
6201 * };
6202 * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
6203 * // Obtain code from the user.
6204 * await applyActionCode(auth, code);
6205 * ```
6206 *
6207 * @param user - The user.
6208 * @param newEmail - The new email address to be verified before update.
6209 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6210 *
6211 * @public
6212 */
6213function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
6214 return tslib.__awaiter(this, void 0, void 0, function () {
6215 var userInternal, idToken, request, email;
6216 return tslib.__generator(this, function (_a) {
6217 switch (_a.label) {
6218 case 0:
6219 userInternal = util.getModularInstance(user);
6220 return [4 /*yield*/, user.getIdToken()];
6221 case 1:
6222 idToken = _a.sent();
6223 request = {
6224 requestType: "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */,
6225 idToken: idToken,
6226 newEmail: newEmail
6227 };
6228 if (actionCodeSettings) {
6229 _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
6230 }
6231 return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
6232 case 2:
6233 email = (_a.sent()).email;
6234 if (!(email !== user.email)) return [3 /*break*/, 4];
6235 // If the local copy of the email on user is outdated, reload the
6236 // user.
6237 return [4 /*yield*/, user.reload()];
6238 case 3:
6239 // If the local copy of the email on user is outdated, reload the
6240 // user.
6241 _a.sent();
6242 _a.label = 4;
6243 case 4: return [2 /*return*/];
6244 }
6245 });
6246 });
6247}
6248
6249/**
6250 * @license
6251 * Copyright 2020 Google LLC
6252 *
6253 * Licensed under the Apache License, Version 2.0 (the "License");
6254 * you may not use this file except in compliance with the License.
6255 * You may obtain a copy of the License at
6256 *
6257 * http://www.apache.org/licenses/LICENSE-2.0
6258 *
6259 * Unless required by applicable law or agreed to in writing, software
6260 * distributed under the License is distributed on an "AS IS" BASIS,
6261 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6262 * See the License for the specific language governing permissions and
6263 * limitations under the License.
6264 */
6265function updateProfile$1(auth, request) {
6266 return tslib.__awaiter(this, void 0, void 0, function () {
6267 return tslib.__generator(this, function (_a) {
6268 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
6269 });
6270 });
6271}
6272
6273/**
6274 * @license
6275 * Copyright 2020 Google LLC
6276 *
6277 * Licensed under the Apache License, Version 2.0 (the "License");
6278 * you may not use this file except in compliance with the License.
6279 * You may obtain a copy of the License at
6280 *
6281 * http://www.apache.org/licenses/LICENSE-2.0
6282 *
6283 * Unless required by applicable law or agreed to in writing, software
6284 * distributed under the License is distributed on an "AS IS" BASIS,
6285 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6286 * See the License for the specific language governing permissions and
6287 * limitations under the License.
6288 */
6289/**
6290 * Updates a user's profile data.
6291 *
6292 * @param user - The user.
6293 * @param profile - The profile's `displayName` and `photoURL` to update.
6294 *
6295 * @public
6296 */
6297function updateProfile(user, _a) {
6298 var displayName = _a.displayName, photoUrl = _a.photoURL;
6299 return tslib.__awaiter(this, void 0, void 0, function () {
6300 var userInternal, idToken, profileRequest, response, passwordProvider;
6301 return tslib.__generator(this, function (_b) {
6302 switch (_b.label) {
6303 case 0:
6304 if (displayName === undefined && photoUrl === undefined) {
6305 return [2 /*return*/];
6306 }
6307 userInternal = util.getModularInstance(user);
6308 return [4 /*yield*/, userInternal.getIdToken()];
6309 case 1:
6310 idToken = _b.sent();
6311 profileRequest = {
6312 idToken: idToken,
6313 displayName: displayName,
6314 photoUrl: photoUrl,
6315 returnSecureToken: true
6316 };
6317 return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
6318 case 2:
6319 response = _b.sent();
6320 userInternal.displayName = response.displayName || null;
6321 userInternal.photoURL = response.photoUrl || null;
6322 passwordProvider = userInternal.providerData.find(function (_a) {
6323 var providerId = _a.providerId;
6324 return providerId === "password" /* PASSWORD */;
6325 });
6326 if (passwordProvider) {
6327 passwordProvider.displayName = userInternal.displayName;
6328 passwordProvider.photoURL = userInternal.photoURL;
6329 }
6330 return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
6331 case 3:
6332 _b.sent();
6333 return [2 /*return*/];
6334 }
6335 });
6336 });
6337}
6338/**
6339 * Updates the user's email address.
6340 *
6341 * @remarks
6342 * An email will be sent to the original email address (if it was set) that allows to revoke the
6343 * email address change, in order to protect them from account hijacking.
6344 *
6345 * Important: this is a security sensitive operation that requires the user to have recently signed
6346 * in. If this requirement isn't met, ask the user to authenticate again and then call
6347 * {@link reauthenticateWithCredential}.
6348 *
6349 * @param user - The user.
6350 * @param newEmail - The new email address.
6351 *
6352 * @public
6353 */
6354function updateEmail(user, newEmail) {
6355 return updateEmailOrPassword(util.getModularInstance(user), newEmail, null);
6356}
6357/**
6358 * Updates the user's password.
6359 *
6360 * @remarks
6361 * Important: this is a security sensitive operation that requires the user to have recently signed
6362 * in. If this requirement isn't met, ask the user to authenticate again and then call
6363 * {@link reauthenticateWithCredential}.
6364 *
6365 * @param user - The user.
6366 * @param newPassword - The new password.
6367 *
6368 * @public
6369 */
6370function updatePassword(user, newPassword) {
6371 return updateEmailOrPassword(util.getModularInstance(user), null, newPassword);
6372}
6373function updateEmailOrPassword(user, email, password) {
6374 return tslib.__awaiter(this, void 0, void 0, function () {
6375 var auth, idToken, request, response;
6376 return tslib.__generator(this, function (_a) {
6377 switch (_a.label) {
6378 case 0:
6379 auth = user.auth;
6380 return [4 /*yield*/, user.getIdToken()];
6381 case 1:
6382 idToken = _a.sent();
6383 request = {
6384 idToken: idToken,
6385 returnSecureToken: true
6386 };
6387 if (email) {
6388 request.email = email;
6389 }
6390 if (password) {
6391 request.password = password;
6392 }
6393 return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
6394 case 2:
6395 response = _a.sent();
6396 return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
6397 case 3:
6398 _a.sent();
6399 return [2 /*return*/];
6400 }
6401 });
6402 });
6403}
6404
6405/**
6406 * @license
6407 * Copyright 2019 Google LLC
6408 *
6409 * Licensed under the Apache License, Version 2.0 (the "License");
6410 * you may not use this file except in compliance with the License.
6411 * You may obtain a copy of the License at
6412 *
6413 * http://www.apache.org/licenses/LICENSE-2.0
6414 *
6415 * Unless required by applicable law or agreed to in writing, software
6416 * distributed under the License is distributed on an "AS IS" BASIS,
6417 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6418 * See the License for the specific language governing permissions and
6419 * limitations under the License.
6420 */
6421/**
6422 * Parse the `AdditionalUserInfo` from the ID token response.
6423 *
6424 */
6425function _fromIdTokenResponse(idTokenResponse) {
6426 var _a, _b;
6427 if (!idTokenResponse) {
6428 return null;
6429 }
6430 var providerId = idTokenResponse.providerId;
6431 var profile = idTokenResponse.rawUserInfo
6432 ? JSON.parse(idTokenResponse.rawUserInfo)
6433 : {};
6434 var isNewUser = idTokenResponse.isNewUser ||
6435 idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* SignupNewUser */;
6436 if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
6437 var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
6438 if (signInProvider) {
6439 var filteredProviderId = signInProvider !== "anonymous" /* ANONYMOUS */ &&
6440 signInProvider !== "custom" /* CUSTOM */
6441 ? signInProvider
6442 : null;
6443 // Uses generic class in accordance with the legacy SDK.
6444 return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
6445 }
6446 }
6447 if (!providerId) {
6448 return null;
6449 }
6450 switch (providerId) {
6451 case "facebook.com" /* FACEBOOK */:
6452 return new FacebookAdditionalUserInfo(isNewUser, profile);
6453 case "github.com" /* GITHUB */:
6454 return new GithubAdditionalUserInfo(isNewUser, profile);
6455 case "google.com" /* GOOGLE */:
6456 return new GoogleAdditionalUserInfo(isNewUser, profile);
6457 case "twitter.com" /* TWITTER */:
6458 return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
6459 case "custom" /* CUSTOM */:
6460 case "anonymous" /* ANONYMOUS */:
6461 return new GenericAdditionalUserInfo(isNewUser, null);
6462 default:
6463 return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
6464 }
6465}
6466var GenericAdditionalUserInfo = /** @class */ (function () {
6467 function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
6468 if (profile === void 0) { profile = {}; }
6469 this.isNewUser = isNewUser;
6470 this.providerId = providerId;
6471 this.profile = profile;
6472 }
6473 return GenericAdditionalUserInfo;
6474}());
6475var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
6476 tslib.__extends(FederatedAdditionalUserInfoWithUsername, _super);
6477 function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
6478 var _this = _super.call(this, isNewUser, providerId, profile) || this;
6479 _this.username = username;
6480 return _this;
6481 }
6482 return FederatedAdditionalUserInfoWithUsername;
6483}(GenericAdditionalUserInfo));
6484var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
6485 tslib.__extends(FacebookAdditionalUserInfo, _super);
6486 function FacebookAdditionalUserInfo(isNewUser, profile) {
6487 return _super.call(this, isNewUser, "facebook.com" /* FACEBOOK */, profile) || this;
6488 }
6489 return FacebookAdditionalUserInfo;
6490}(GenericAdditionalUserInfo));
6491var GithubAdditionalUserInfo = /** @class */ (function (_super) {
6492 tslib.__extends(GithubAdditionalUserInfo, _super);
6493 function GithubAdditionalUserInfo(isNewUser, profile) {
6494 return _super.call(this, isNewUser, "github.com" /* GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null) || this;
6495 }
6496 return GithubAdditionalUserInfo;
6497}(FederatedAdditionalUserInfoWithUsername));
6498var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
6499 tslib.__extends(GoogleAdditionalUserInfo, _super);
6500 function GoogleAdditionalUserInfo(isNewUser, profile) {
6501 return _super.call(this, isNewUser, "google.com" /* GOOGLE */, profile) || this;
6502 }
6503 return GoogleAdditionalUserInfo;
6504}(GenericAdditionalUserInfo));
6505var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
6506 tslib.__extends(TwitterAdditionalUserInfo, _super);
6507 function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
6508 return _super.call(this, isNewUser, "twitter.com" /* TWITTER */, profile, screenName) || this;
6509 }
6510 return TwitterAdditionalUserInfo;
6511}(FederatedAdditionalUserInfoWithUsername));
6512/**
6513 * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
6514 *
6515 * @param userCredential - The user credential.
6516 *
6517 * @public
6518 */
6519function getAdditionalUserInfo(userCredential) {
6520 var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
6521 if (user.isAnonymous && !_tokenResponse) {
6522 // Handle the special case where signInAnonymously() gets called twice.
6523 // No network call is made so there's nothing to actually fill this in
6524 return {
6525 providerId: null,
6526 isNewUser: false,
6527 profile: null
6528 };
6529 }
6530 return _fromIdTokenResponse(_tokenResponse);
6531}
6532
6533/**
6534 * @license
6535 * Copyright 2020 Google LLC
6536 *
6537 * Licensed under the Apache License, Version 2.0 (the "License");
6538 * you may not use this file except in compliance with the License.
6539 * You may obtain a copy of the License at
6540 *
6541 * http://www.apache.org/licenses/LICENSE-2.0
6542 *
6543 * Unless required by applicable law or agreed to in writing, software
6544 * distributed under the License is distributed on an "AS IS" BASIS,
6545 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6546 * See the License for the specific language governing permissions and
6547 * limitations under the License.
6548 */
6549// Non-optional auth methods.
6550/**
6551 * Changes the type of persistence on the {@link Auth} instance for the currently saved
6552 * `Auth` session and applies this type of persistence for future sign-in requests, including
6553 * sign-in with redirect requests.
6554 *
6555 * @remarks
6556 * This makes it easy for a user signing in to specify whether their session should be
6557 * remembered or not. It also makes it easier to never persist the `Auth` state for applications
6558 * that are shared by other users or have sensitive data.
6559 *
6560 * @example
6561 * ```javascript
6562 * setPersistence(auth, browserSessionPersistence);
6563 * ```
6564 *
6565 * @param auth - The {@link Auth} instance.
6566 * @param persistence - The {@link Persistence} to use.
6567 * @returns A `Promise` that resolves once the persistence change has completed
6568 *
6569 * @public
6570 */
6571function setPersistence(auth, persistence) {
6572 return util.getModularInstance(auth).setPersistence(persistence);
6573}
6574/**
6575 * Adds an observer for changes to the signed-in user's ID token.
6576 *
6577 * @remarks
6578 * This includes sign-in, sign-out, and token refresh events.
6579 *
6580 * @param auth - The {@link Auth} instance.
6581 * @param nextOrObserver - callback triggered on change.
6582 * @param error - Deprecated. This callback is never triggered. Errors
6583 * on signing in/out can be caught in promises returned from
6584 * sign-in/sign-out functions.
6585 * @param completed - Deprecated. This callback is never triggered.
6586 *
6587 * @public
6588 */
6589function onIdTokenChanged(auth, nextOrObserver, error, completed) {
6590 return util.getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
6591}
6592/**
6593 * Adds a blocking callback that runs before an auth state change
6594 * sets a new user.
6595 *
6596 * @param auth - The {@link Auth} instance.
6597 * @param callback - callback triggered before new user value is set.
6598 * If this throws, it blocks the user from being set.
6599 * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
6600 * callback throws, allowing you to undo any side effects.
6601 */
6602function beforeAuthStateChanged(auth, callback, onAbort) {
6603 return util.getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
6604}
6605/**
6606 * Adds an observer for changes to the user's sign-in state.
6607 *
6608 * @remarks
6609 * To keep the old behavior, see {@link onIdTokenChanged}.
6610 *
6611 * @param auth - The {@link Auth} instance.
6612 * @param nextOrObserver - callback triggered on change.
6613 * @param error - Deprecated. This callback is never triggered. Errors
6614 * on signing in/out can be caught in promises returned from
6615 * sign-in/sign-out functions.
6616 * @param completed - Deprecated. This callback is never triggered.
6617 *
6618 * @public
6619 */
6620function onAuthStateChanged(auth, nextOrObserver, error, completed) {
6621 return util.getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
6622}
6623/**
6624 * Sets the current language to the default device/browser preference.
6625 *
6626 * @param auth - The {@link Auth} instance.
6627 *
6628 * @public
6629 */
6630function useDeviceLanguage(auth) {
6631 util.getModularInstance(auth).useDeviceLanguage();
6632}
6633/**
6634 * Asynchronously sets the provided user as {@link Auth.currentUser} on the
6635 * {@link Auth} instance.
6636 *
6637 * @remarks
6638 * A new instance copy of the user provided will be made and set as currentUser.
6639 *
6640 * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
6641 * like other sign in methods.
6642 *
6643 * The operation fails with an error if the user to be updated belongs to a different Firebase
6644 * project.
6645 *
6646 * @param auth - The {@link Auth} instance.
6647 * @param user - The new {@link User}.
6648 *
6649 * @public
6650 */
6651function updateCurrentUser(auth, user) {
6652 return util.getModularInstance(auth).updateCurrentUser(user);
6653}
6654/**
6655 * Signs out the current user.
6656 *
6657 * @param auth - The {@link Auth} instance.
6658 *
6659 * @public
6660 */
6661function signOut(auth) {
6662 return util.getModularInstance(auth).signOut();
6663}
6664/**
6665 * Deletes and signs out the user.
6666 *
6667 * @remarks
6668 * Important: this is a security-sensitive operation that requires the user to have recently
6669 * signed in. If this requirement isn't met, ask the user to authenticate again and then call
6670 * {@link reauthenticateWithCredential}.
6671 *
6672 * @param user - The user.
6673 *
6674 * @public
6675 */
6676function deleteUser(user) {
6677 return tslib.__awaiter(this, void 0, void 0, function () {
6678 return tslib.__generator(this, function (_a) {
6679 return [2 /*return*/, util.getModularInstance(user).delete()];
6680 });
6681 });
6682}
6683
6684var MultiFactorSessionImpl = /** @class */ (function () {
6685 function MultiFactorSessionImpl(type, credential) {
6686 this.type = type;
6687 this.credential = credential;
6688 }
6689 MultiFactorSessionImpl._fromIdtoken = function (idToken) {
6690 return new MultiFactorSessionImpl("enroll" /* ENROLL */, idToken);
6691 };
6692 MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
6693 return new MultiFactorSessionImpl("signin" /* SIGN_IN */, mfaPendingCredential);
6694 };
6695 MultiFactorSessionImpl.prototype.toJSON = function () {
6696 var _a;
6697 var key = this.type === "enroll" /* ENROLL */
6698 ? 'idToken'
6699 : 'pendingCredential';
6700 return {
6701 multiFactorSession: (_a = {},
6702 _a[key] = this.credential,
6703 _a)
6704 };
6705 };
6706 MultiFactorSessionImpl.fromJSON = function (obj) {
6707 var _a, _b;
6708 if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
6709 if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
6710 return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
6711 }
6712 else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
6713 return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
6714 }
6715 }
6716 return null;
6717 };
6718 return MultiFactorSessionImpl;
6719}());
6720
6721/**
6722 * @license
6723 * Copyright 2020 Google LLC
6724 *
6725 * Licensed under the Apache License, Version 2.0 (the "License");
6726 * you may not use this file except in compliance with the License.
6727 * You may obtain a copy of the License at
6728 *
6729 * http://www.apache.org/licenses/LICENSE-2.0
6730 *
6731 * Unless required by applicable law or agreed to in writing, software
6732 * distributed under the License is distributed on an "AS IS" BASIS,
6733 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6734 * See the License for the specific language governing permissions and
6735 * limitations under the License.
6736 */
6737var MultiFactorResolverImpl = /** @class */ (function () {
6738 function MultiFactorResolverImpl(session, hints, signInResolver) {
6739 this.session = session;
6740 this.hints = hints;
6741 this.signInResolver = signInResolver;
6742 }
6743 /** @internal */
6744 MultiFactorResolverImpl._fromError = function (authExtern, error) {
6745 var _this = this;
6746 var auth = _castAuth(authExtern);
6747 var serverResponse = error.customData._serverResponse;
6748 var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
6749 return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
6750 });
6751 _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* INTERNAL_ERROR */);
6752 var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
6753 return new MultiFactorResolverImpl(session, hints, function (assertion) { return tslib.__awaiter(_this, void 0, void 0, function () {
6754 var mfaResponse, idTokenResponse, _a, userCredential;
6755 return tslib.__generator(this, function (_b) {
6756 switch (_b.label) {
6757 case 0: return [4 /*yield*/, assertion._process(auth, session)];
6758 case 1:
6759 mfaResponse = _b.sent();
6760 // Clear out the unneeded fields from the old login response
6761 delete serverResponse.mfaInfo;
6762 delete serverResponse.mfaPendingCredential;
6763 idTokenResponse = tslib.__assign(tslib.__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
6764 _a = error.operationType;
6765 switch (_a) {
6766 case "signIn" /* SIGN_IN */: return [3 /*break*/, 2];
6767 case "reauthenticate" /* REAUTHENTICATE */: return [3 /*break*/, 5];
6768 }
6769 return [3 /*break*/, 6];
6770 case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
6771 case 3:
6772 userCredential = _b.sent();
6773 return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
6774 case 4:
6775 _b.sent();
6776 return [2 /*return*/, userCredential];
6777 case 5:
6778 _assert(error.user, auth, "internal-error" /* INTERNAL_ERROR */);
6779 return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
6780 case 6:
6781 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
6782 _b.label = 7;
6783 case 7: return [2 /*return*/];
6784 }
6785 });
6786 }); });
6787 };
6788 MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
6789 return tslib.__awaiter(this, void 0, void 0, function () {
6790 var assertion;
6791 return tslib.__generator(this, function (_a) {
6792 assertion = assertionExtern;
6793 return [2 /*return*/, this.signInResolver(assertion)];
6794 });
6795 });
6796 };
6797 return MultiFactorResolverImpl;
6798}());
6799/**
6800 * Provides a {@link MultiFactorResolver} suitable for completion of a
6801 * multi-factor flow.
6802 *
6803 * @param auth - The {@link Auth} instance.
6804 * @param error - The {@link MultiFactorError} raised during a sign-in, or
6805 * reauthentication operation.
6806 *
6807 * @public
6808 */
6809function getMultiFactorResolver(auth, error) {
6810 var _a;
6811 var authModular = util.getModularInstance(auth);
6812 var errorInternal = error;
6813 _assert(error.customData.operationType, authModular, "argument-error" /* ARGUMENT_ERROR */);
6814 _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* ARGUMENT_ERROR */);
6815 return MultiFactorResolverImpl._fromError(authModular, errorInternal);
6816}
6817
6818/**
6819 * @license
6820 * Copyright 2020 Google LLC
6821 *
6822 * Licensed under the Apache License, Version 2.0 (the "License");
6823 * you may not use this file except in compliance with the License.
6824 * You may obtain a copy of the License at
6825 *
6826 * http://www.apache.org/licenses/LICENSE-2.0
6827 *
6828 * Unless required by applicable law or agreed to in writing, software
6829 * distributed under the License is distributed on an "AS IS" BASIS,
6830 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6831 * See the License for the specific language governing permissions and
6832 * limitations under the License.
6833 */
6834function startEnrollPhoneMfa(auth, request) {
6835 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:start" /* START_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
6836}
6837function finalizeEnrollPhoneMfa(auth, request) {
6838 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:finalize" /* FINALIZE_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
6839}
6840function withdrawMfa(auth, request) {
6841 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:withdraw" /* WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
6842}
6843
6844var MultiFactorUserImpl = /** @class */ (function () {
6845 function MultiFactorUserImpl(user) {
6846 var _this = this;
6847 this.user = user;
6848 this.enrolledFactors = [];
6849 user._onReload(function (userInfo) {
6850 if (userInfo.mfaInfo) {
6851 _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
6852 return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
6853 });
6854 }
6855 });
6856 }
6857 MultiFactorUserImpl._fromUser = function (user) {
6858 return new MultiFactorUserImpl(user);
6859 };
6860 MultiFactorUserImpl.prototype.getSession = function () {
6861 return tslib.__awaiter(this, void 0, void 0, function () {
6862 var _a, _b;
6863 return tslib.__generator(this, function (_c) {
6864 switch (_c.label) {
6865 case 0:
6866 _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
6867 return [4 /*yield*/, this.user.getIdToken()];
6868 case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
6869 }
6870 });
6871 });
6872 };
6873 MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
6874 return tslib.__awaiter(this, void 0, void 0, function () {
6875 var assertion, session, finalizeMfaResponse;
6876 return tslib.__generator(this, function (_a) {
6877 switch (_a.label) {
6878 case 0:
6879 assertion = assertionExtern;
6880 return [4 /*yield*/, this.getSession()];
6881 case 1:
6882 session = (_a.sent());
6883 return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
6884 case 2:
6885 finalizeMfaResponse = _a.sent();
6886 // New tokens will be issued after enrollment of the new second factors.
6887 // They need to be updated on the user.
6888 return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
6889 case 3:
6890 // New tokens will be issued after enrollment of the new second factors.
6891 // They need to be updated on the user.
6892 _a.sent();
6893 // The user needs to be reloaded to get the new multi-factor information
6894 // from server. USER_RELOADED event will be triggered and `enrolledFactors`
6895 // will be updated.
6896 return [2 /*return*/, this.user.reload()];
6897 }
6898 });
6899 });
6900 };
6901 MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
6902 var _a;
6903 return tslib.__awaiter(this, void 0, void 0, function () {
6904 var mfaEnrollmentId, idToken, idTokenResponse, e_1;
6905 return tslib.__generator(this, function (_b) {
6906 switch (_b.label) {
6907 case 0:
6908 mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
6909 return [4 /*yield*/, this.user.getIdToken()];
6910 case 1:
6911 idToken = _b.sent();
6912 return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
6913 idToken: idToken,
6914 mfaEnrollmentId: mfaEnrollmentId
6915 }))];
6916 case 2:
6917 idTokenResponse = _b.sent();
6918 // Remove the second factor from the user's list.
6919 this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
6920 var uid = _a.uid;
6921 return uid !== mfaEnrollmentId;
6922 });
6923 // Depending on whether the backend decided to revoke the user's session,
6924 // the tokenResponse may be empty. If the tokens were not updated (and they
6925 // are now invalid), reloading the user will discover this and invalidate
6926 // the user's state accordingly.
6927 return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
6928 case 3:
6929 // Depending on whether the backend decided to revoke the user's session,
6930 // the tokenResponse may be empty. If the tokens were not updated (and they
6931 // are now invalid), reloading the user will discover this and invalidate
6932 // the user's state accordingly.
6933 _b.sent();
6934 _b.label = 4;
6935 case 4:
6936 _b.trys.push([4, 6, , 7]);
6937 return [4 /*yield*/, this.user.reload()];
6938 case 5:
6939 _b.sent();
6940 return [3 /*break*/, 7];
6941 case 6:
6942 e_1 = _b.sent();
6943 if (((_a = e_1) === null || _a === void 0 ? void 0 : _a.code) !== "auth/" + "user-token-expired" /* TOKEN_EXPIRED */) {
6944 throw e_1;
6945 }
6946 return [3 /*break*/, 7];
6947 case 7: return [2 /*return*/];
6948 }
6949 });
6950 });
6951 };
6952 return MultiFactorUserImpl;
6953}());
6954var multiFactorUserCache = new WeakMap();
6955/**
6956 * The {@link MultiFactorUser} corresponding to the user.
6957 *
6958 * @remarks
6959 * This is used to access all multi-factor properties and operations related to the user.
6960 *
6961 * @param user - The user.
6962 *
6963 * @public
6964 */
6965function multiFactor(user) {
6966 var userModular = util.getModularInstance(user);
6967 if (!multiFactorUserCache.has(userModular)) {
6968 multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
6969 }
6970 return multiFactorUserCache.get(userModular);
6971}
6972
6973var name = "@firebase/auth";
6974var version = "0.20.5";
6975
6976/**
6977 * @license
6978 * Copyright 2020 Google LLC
6979 *
6980 * Licensed under the Apache License, Version 2.0 (the "License");
6981 * you may not use this file except in compliance with the License.
6982 * You may obtain a copy of the License at
6983 *
6984 * http://www.apache.org/licenses/LICENSE-2.0
6985 *
6986 * Unless required by applicable law or agreed to in writing, software
6987 * distributed under the License is distributed on an "AS IS" BASIS,
6988 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6989 * See the License for the specific language governing permissions and
6990 * limitations under the License.
6991 */
6992var AuthInterop = /** @class */ (function () {
6993 function AuthInterop(auth) {
6994 this.auth = auth;
6995 this.internalListeners = new Map();
6996 }
6997 AuthInterop.prototype.getUid = function () {
6998 var _a;
6999 this.assertAuthConfigured();
7000 return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
7001 };
7002 AuthInterop.prototype.getToken = function (forceRefresh) {
7003 return tslib.__awaiter(this, void 0, void 0, function () {
7004 var accessToken;
7005 return tslib.__generator(this, function (_a) {
7006 switch (_a.label) {
7007 case 0:
7008 this.assertAuthConfigured();
7009 return [4 /*yield*/, this.auth._initializationPromise];
7010 case 1:
7011 _a.sent();
7012 if (!this.auth.currentUser) {
7013 return [2 /*return*/, null];
7014 }
7015 return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
7016 case 2:
7017 accessToken = _a.sent();
7018 return [2 /*return*/, { accessToken: accessToken }];
7019 }
7020 });
7021 });
7022 };
7023 AuthInterop.prototype.addAuthTokenListener = function (listener) {
7024 this.assertAuthConfigured();
7025 if (this.internalListeners.has(listener)) {
7026 return;
7027 }
7028 var unsubscribe = this.auth.onIdTokenChanged(function (user) {
7029 var _a;
7030 listener(((_a = user) === null || _a === void 0 ? void 0 : _a.stsTokenManager.accessToken) || null);
7031 });
7032 this.internalListeners.set(listener, unsubscribe);
7033 this.updateProactiveRefresh();
7034 };
7035 AuthInterop.prototype.removeAuthTokenListener = function (listener) {
7036 this.assertAuthConfigured();
7037 var unsubscribe = this.internalListeners.get(listener);
7038 if (!unsubscribe) {
7039 return;
7040 }
7041 this.internalListeners.delete(listener);
7042 unsubscribe();
7043 this.updateProactiveRefresh();
7044 };
7045 AuthInterop.prototype.assertAuthConfigured = function () {
7046 _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */);
7047 };
7048 AuthInterop.prototype.updateProactiveRefresh = function () {
7049 if (this.internalListeners.size > 0) {
7050 this.auth._startProactiveRefresh();
7051 }
7052 else {
7053 this.auth._stopProactiveRefresh();
7054 }
7055 };
7056 return AuthInterop;
7057}());
7058
7059/**
7060 * @license
7061 * Copyright 2020 Google LLC
7062 *
7063 * Licensed under the Apache License, Version 2.0 (the "License");
7064 * you may not use this file except in compliance with the License.
7065 * You may obtain a copy of the License at
7066 *
7067 * http://www.apache.org/licenses/LICENSE-2.0
7068 *
7069 * Unless required by applicable law or agreed to in writing, software
7070 * distributed under the License is distributed on an "AS IS" BASIS,
7071 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7072 * See the License for the specific language governing permissions and
7073 * limitations under the License.
7074 */
7075function getVersionForPlatform(clientPlatform) {
7076 switch (clientPlatform) {
7077 case "Node" /* NODE */:
7078 return 'node';
7079 case "ReactNative" /* REACT_NATIVE */:
7080 return 'rn';
7081 case "Worker" /* WORKER */:
7082 return 'webworker';
7083 case "Cordova" /* CORDOVA */:
7084 return 'cordova';
7085 default:
7086 return undefined;
7087 }
7088}
7089/** @internal */
7090function registerAuth(clientPlatform) {
7091 app._registerComponent(new component.Component("auth" /* AUTH */, function (container, _a) {
7092 var deps = _a.options;
7093 var app = container.getProvider('app').getImmediate();
7094 var heartbeatServiceProvider = container.getProvider('heartbeat');
7095 var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
7096 return (function (app, heartbeatServiceProvider) {
7097 _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* INVALID_API_KEY */, { appName: app.name });
7098 // Auth domain is optional if IdP sign in isn't being used
7099 _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* ARGUMENT_ERROR */, {
7100 appName: app.name
7101 });
7102 var config = {
7103 apiKey: apiKey,
7104 authDomain: authDomain,
7105 clientPlatform: clientPlatform,
7106 apiHost: "identitytoolkit.googleapis.com" /* API_HOST */,
7107 tokenApiHost: "securetoken.googleapis.com" /* TOKEN_API_HOST */,
7108 apiScheme: "https" /* API_SCHEME */,
7109 sdkClientVersion: _getClientVersion(clientPlatform)
7110 };
7111 var authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
7112 _initializeAuthInstance(authInstance, deps);
7113 return authInstance;
7114 })(app, heartbeatServiceProvider);
7115 }, "PUBLIC" /* PUBLIC */)
7116 /**
7117 * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
7118 * For why we do this, See go/firebase-next-auth-init
7119 */
7120 .setInstantiationMode("EXPLICIT" /* EXPLICIT */)
7121 /**
7122 * Because all firebase products that depend on auth depend on auth-internal directly,
7123 * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
7124 */
7125 .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
7126 var authInternalProvider = container.getProvider("auth-internal" /* AUTH_INTERNAL */);
7127 authInternalProvider.initialize();
7128 }));
7129 app._registerComponent(new component.Component("auth-internal" /* AUTH_INTERNAL */, function (container) {
7130 var auth = _castAuth(container.getProvider("auth" /* AUTH */).getImmediate());
7131 return (function (auth) { return new AuthInterop(auth); })(auth);
7132 }, "PRIVATE" /* PRIVATE */).setInstantiationMode("EXPLICIT" /* EXPLICIT */));
7133 app.registerVersion(name, version, getVersionForPlatform(clientPlatform));
7134 // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
7135 app.registerVersion(name, version, 'cjs5');
7136}
7137
7138var STORAGE_AVAILABLE_KEY = '__sak';
7139
7140/**
7141 * @license
7142 * Copyright 2021 Google LLC
7143 *
7144 * Licensed under the Apache License, Version 2.0 (the "License");
7145 * you may not use this file except in compliance with the License.
7146 * You may obtain a copy of the License at
7147 *
7148 * http://www.apache.org/licenses/LICENSE-2.0
7149 *
7150 * Unless required by applicable law or agreed to in writing, software
7151 * distributed under the License is distributed on an "AS IS" BASIS,
7152 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7153 * See the License for the specific language governing permissions and
7154 * limitations under the License.
7155 */
7156/**
7157 * An enum of factors that may be used for multifactor authentication.
7158 *
7159 * @public
7160 */
7161var FactorId = {
7162 /** Phone as second factor */
7163 PHONE: 'phone'
7164};
7165/**
7166 * Enumeration of supported providers.
7167 *
7168 * @public
7169 */
7170var ProviderId = {
7171 /** Facebook provider ID */
7172 FACEBOOK: 'facebook.com',
7173 /** GitHub provider ID */
7174 GITHUB: 'github.com',
7175 /** Google provider ID */
7176 GOOGLE: 'google.com',
7177 /** Password provider */
7178 PASSWORD: 'password',
7179 /** Phone provider */
7180 PHONE: 'phone',
7181 /** Twitter provider ID */
7182 TWITTER: 'twitter.com'
7183};
7184/**
7185 * Enumeration of supported sign-in methods.
7186 *
7187 * @public
7188 */
7189var SignInMethod = {
7190 /** Email link sign in method */
7191 EMAIL_LINK: 'emailLink',
7192 /** Email/password sign in method */
7193 EMAIL_PASSWORD: 'password',
7194 /** Facebook sign in method */
7195 FACEBOOK: 'facebook.com',
7196 /** GitHub sign in method */
7197 GITHUB: 'github.com',
7198 /** Google sign in method */
7199 GOOGLE: 'google.com',
7200 /** Phone sign in method */
7201 PHONE: 'phone',
7202 /** Twitter sign in method */
7203 TWITTER: 'twitter.com'
7204};
7205/**
7206 * Enumeration of supported operation types.
7207 *
7208 * @public
7209 */
7210var OperationType = {
7211 /** Operation involving linking an additional provider to an already signed-in user. */
7212 LINK: 'link',
7213 /** Operation involving using a provider to reauthenticate an already signed-in user. */
7214 REAUTHENTICATE: 'reauthenticate',
7215 /** Operation involving signing in a user. */
7216 SIGN_IN: 'signIn'
7217};
7218/**
7219 * An enumeration of the possible email action types.
7220 *
7221 * @public
7222 */
7223var ActionCodeOperation = {
7224 /** The email link sign-in action. */
7225 EMAIL_SIGNIN: 'EMAIL_SIGNIN',
7226 /** The password reset action. */
7227 PASSWORD_RESET: 'PASSWORD_RESET',
7228 /** The email revocation action. */
7229 RECOVER_EMAIL: 'RECOVER_EMAIL',
7230 /** The revert second factor addition email action. */
7231 REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
7232 /** The revert second factor addition email action. */
7233 VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
7234 /** The email verification action. */
7235 VERIFY_EMAIL: 'VERIFY_EMAIL'
7236};
7237
7238/**
7239 * @license
7240 * Copyright 2020 Google LLC
7241 *
7242 * Licensed under the Apache License, Version 2.0 (the "License");
7243 * you may not use this file except in compliance with the License.
7244 * You may obtain a copy of the License at
7245 *
7246 * http://www.apache.org/licenses/LICENSE-2.0
7247 *
7248 * Unless required by applicable law or agreed to in writing, software
7249 * distributed under the License is distributed on an "AS IS" BASIS,
7250 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7251 * See the License for the specific language governing permissions and
7252 * limitations under the License.
7253 */
7254function startSignInPhoneMfa(auth, request) {
7255 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaSignIn:start" /* START_PHONE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
7256}
7257function finalizeSignInPhoneMfa(auth, request) {
7258 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaSignIn:finalize" /* FINALIZE_PHONE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
7259}
7260
7261/**
7262 * @license
7263 * Copyright 2020 Google LLC
7264 *
7265 * Licensed under the Apache License, Version 2.0 (the "License");
7266 * you may not use this file except in compliance with the License.
7267 * You may obtain a copy of the License at
7268 *
7269 * http://www.apache.org/licenses/LICENSE-2.0
7270 *
7271 * Unless required by applicable law or agreed to in writing, software
7272 * distributed under the License is distributed on an "AS IS" BASIS,
7273 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7274 * See the License for the specific language governing permissions and
7275 * limitations under the License.
7276 */
7277function getRecaptchaParams(auth) {
7278 return tslib.__awaiter(this, void 0, void 0, function () {
7279 return tslib.__generator(this, function (_a) {
7280 switch (_a.label) {
7281 case 0: return [4 /*yield*/, _performApiRequest(auth, "GET" /* GET */, "/v1/recaptchaParams" /* GET_RECAPTCHA_PARAM */)];
7282 case 1: return [2 /*return*/, ((_a.sent()).recaptchaSiteKey || '')];
7283 }
7284 });
7285 });
7286}
7287
7288/**
7289 * @license
7290 * Copyright 2020 Google LLC
7291 *
7292 * Licensed under the Apache License, Version 2.0 (the "License");
7293 * you may not use this file except in compliance with the License.
7294 * You may obtain a copy of the License at
7295 *
7296 * http://www.apache.org/licenses/LICENSE-2.0
7297 *
7298 * Unless required by applicable law or agreed to in writing, software
7299 * distributed under the License is distributed on an "AS IS" BASIS,
7300 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7301 * See the License for the specific language governing permissions and
7302 * limitations under the License.
7303 */
7304/**
7305 * Lazy accessor for window, since the compat layer won't tree shake this out,
7306 * we need to make sure not to mess with window unless we have to
7307 */
7308function _window() {
7309 return window;
7310}
7311function _setWindowLocation(url) {
7312 _window().location.href = url;
7313}
7314
7315/**
7316 * @license
7317 * Copyright 2020 Google LLC.
7318 *
7319 * Licensed under the Apache License, Version 2.0 (the "License");
7320 * you may not use this file except in compliance with the License.
7321 * You may obtain a copy of the License at
7322 *
7323 * http://www.apache.org/licenses/LICENSE-2.0
7324 *
7325 * Unless required by applicable law or agreed to in writing, software
7326 * distributed under the License is distributed on an "AS IS" BASIS,
7327 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7328 * See the License for the specific language governing permissions and
7329 * limitations under the License.
7330 */
7331function _isWorker() {
7332 return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
7333 typeof _window()['importScripts'] === 'function');
7334}
7335function _getActiveServiceWorker() {
7336 return tslib.__awaiter(this, void 0, void 0, function () {
7337 var registration;
7338 return tslib.__generator(this, function (_b) {
7339 switch (_b.label) {
7340 case 0:
7341 if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
7342 return [2 /*return*/, null];
7343 }
7344 _b.label = 1;
7345 case 1:
7346 _b.trys.push([1, 3, , 4]);
7347 return [4 /*yield*/, navigator.serviceWorker.ready];
7348 case 2:
7349 registration = _b.sent();
7350 return [2 /*return*/, registration.active];
7351 case 3:
7352 _b.sent();
7353 return [2 /*return*/, null];
7354 case 4: return [2 /*return*/];
7355 }
7356 });
7357 });
7358}
7359function _getServiceWorkerController() {
7360 var _a;
7361 return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
7362}
7363function _getWorkerGlobalScope() {
7364 return _isWorker() ? self : null;
7365}
7366
7367/**
7368 * @license
7369 * Copyright 2020 Google LLC
7370 *
7371 * Licensed under the Apache License, Version 2.0 (the "License");
7372 * you may not use this file except in compliance with the License.
7373 * You may obtain a copy of the License at
7374 *
7375 * http://www.apache.org/licenses/LICENSE-2.0
7376 *
7377 * Unless required by applicable law or agreed to in writing, software
7378 * distributed under the License is distributed on an "AS IS" BASIS,
7379 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7380 * See the License for the specific language governing permissions and
7381 * limitations under the License.
7382 */
7383function getScriptParentElement() {
7384 var _a, _b;
7385 return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
7386}
7387function _loadJS(url) {
7388 // TODO: consider adding timeout support & cancellation
7389 return new Promise(function (resolve, reject) {
7390 var el = document.createElement('script');
7391 el.setAttribute('src', url);
7392 el.onload = resolve;
7393 el.onerror = function (e) {
7394 var error = _createError("internal-error" /* INTERNAL_ERROR */);
7395 error.customData = e;
7396 reject(error);
7397 };
7398 el.type = 'text/javascript';
7399 el.charset = 'UTF-8';
7400 getScriptParentElement().appendChild(el);
7401 });
7402}
7403function _generateCallbackName(prefix) {
7404 return "__" + prefix + Math.floor(Math.random() * 1000000);
7405}
7406
7407/**
7408 * @license
7409 * Copyright 2020 Google LLC
7410 *
7411 * Licensed under the Apache License, Version 2.0 (the "License");
7412 * you may not use this file except in compliance with the License.
7413 * You may obtain a copy of the License at
7414 *
7415 * http://www.apache.org/licenses/LICENSE-2.0
7416 *
7417 * Unless required by applicable law or agreed to in writing, software
7418 * distributed under the License is distributed on an "AS IS" BASIS,
7419 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7420 * See the License for the specific language governing permissions and
7421 * limitations under the License.
7422 */
7423var _SOLVE_TIME_MS = 500;
7424var _EXPIRATION_TIME_MS = 60000;
7425var _WIDGET_ID_START = 1000000000000;
7426var MockReCaptcha = /** @class */ (function () {
7427 function MockReCaptcha(auth) {
7428 this.auth = auth;
7429 this.counter = _WIDGET_ID_START;
7430 this._widgets = new Map();
7431 }
7432 MockReCaptcha.prototype.render = function (container, parameters) {
7433 var id = this.counter;
7434 this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
7435 this.counter++;
7436 return id;
7437 };
7438 MockReCaptcha.prototype.reset = function (optWidgetId) {
7439 var _a;
7440 var id = optWidgetId || _WIDGET_ID_START;
7441 void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
7442 this._widgets.delete(id);
7443 };
7444 MockReCaptcha.prototype.getResponse = function (optWidgetId) {
7445 var _a;
7446 var id = optWidgetId || _WIDGET_ID_START;
7447 return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
7448 };
7449 MockReCaptcha.prototype.execute = function (optWidgetId) {
7450 var _a;
7451 return tslib.__awaiter(this, void 0, void 0, function () {
7452 var id;
7453 return tslib.__generator(this, function (_b) {
7454 id = optWidgetId || _WIDGET_ID_START;
7455 void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
7456 return [2 /*return*/, ''];
7457 });
7458 });
7459 };
7460 return MockReCaptcha;
7461}());
7462var MockWidget = /** @class */ (function () {
7463 function MockWidget(containerOrId, appName, params) {
7464 var _this = this;
7465 this.params = params;
7466 this.timerId = null;
7467 this.deleted = false;
7468 this.responseToken = null;
7469 this.clickHandler = function () {
7470 _this.execute();
7471 };
7472 var container = typeof containerOrId === 'string'
7473 ? document.getElementById(containerOrId)
7474 : containerOrId;
7475 _assert(container, "argument-error" /* ARGUMENT_ERROR */, { appName: appName });
7476 this.container = container;
7477 this.isVisible = this.params.size !== 'invisible';
7478 if (this.isVisible) {
7479 this.execute();
7480 }
7481 else {
7482 this.container.addEventListener('click', this.clickHandler);
7483 }
7484 }
7485 MockWidget.prototype.getResponse = function () {
7486 this.checkIfDeleted();
7487 return this.responseToken;
7488 };
7489 MockWidget.prototype.delete = function () {
7490 this.checkIfDeleted();
7491 this.deleted = true;
7492 if (this.timerId) {
7493 clearTimeout(this.timerId);
7494 this.timerId = null;
7495 }
7496 this.container.removeEventListener('click', this.clickHandler);
7497 };
7498 MockWidget.prototype.execute = function () {
7499 var _this = this;
7500 this.checkIfDeleted();
7501 if (this.timerId) {
7502 return;
7503 }
7504 this.timerId = window.setTimeout(function () {
7505 _this.responseToken = generateRandomAlphaNumericString(50);
7506 var _a = _this.params, callback = _a.callback, expiredCallback = _a["expired-callback"];
7507 if (callback) {
7508 try {
7509 callback(_this.responseToken);
7510 }
7511 catch (e) { }
7512 }
7513 _this.timerId = window.setTimeout(function () {
7514 _this.timerId = null;
7515 _this.responseToken = null;
7516 if (expiredCallback) {
7517 try {
7518 expiredCallback();
7519 }
7520 catch (e) { }
7521 }
7522 if (_this.isVisible) {
7523 _this.execute();
7524 }
7525 }, _EXPIRATION_TIME_MS);
7526 }, _SOLVE_TIME_MS);
7527 };
7528 MockWidget.prototype.checkIfDeleted = function () {
7529 if (this.deleted) {
7530 throw new Error('reCAPTCHA mock was already deleted!');
7531 }
7532 };
7533 return MockWidget;
7534}());
7535function generateRandomAlphaNumericString(len) {
7536 var chars = [];
7537 var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
7538 for (var i = 0; i < len; i++) {
7539 chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
7540 }
7541 return chars.join('');
7542}
7543
7544/**
7545 * @license
7546 * Copyright 2020 Google LLC
7547 *
7548 * Licensed under the Apache License, Version 2.0 (the "License");
7549 * you may not use this file except in compliance with the License.
7550 * You may obtain a copy of the License at
7551 *
7552 * http://www.apache.org/licenses/LICENSE-2.0
7553 *
7554 * Unless required by applicable law or agreed to in writing, software
7555 * distributed under the License is distributed on an "AS IS" BASIS,
7556 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7557 * See the License for the specific language governing permissions and
7558 * limitations under the License.
7559 */
7560// ReCaptcha will load using the same callback, so the callback function needs
7561// to be kept around
7562var _JSLOAD_CALLBACK = _generateCallbackName('rcb');
7563var NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
7564var RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
7565/**
7566 * Loader for the GReCaptcha library. There should only ever be one of this.
7567 */
7568var ReCaptchaLoaderImpl = /** @class */ (function () {
7569 function ReCaptchaLoaderImpl() {
7570 var _a;
7571 this.hostLanguage = '';
7572 this.counter = 0;
7573 /**
7574 * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
7575 * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
7576 * `window.grecaptcha.render()` will not. Another load will add it.
7577 */
7578 this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
7579 }
7580 ReCaptchaLoaderImpl.prototype.load = function (auth, hl) {
7581 var _this = this;
7582 if (hl === void 0) { hl = ''; }
7583 _assert(isHostLanguageValid(hl), auth, "argument-error" /* ARGUMENT_ERROR */);
7584 if (this.shouldResolveImmediately(hl)) {
7585 return Promise.resolve(_window().grecaptcha);
7586 }
7587 return new Promise(function (resolve, reject) {
7588 var networkTimeout = _window().setTimeout(function () {
7589 reject(_createError(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
7590 }, NETWORK_TIMEOUT_DELAY.get());
7591 _window()[_JSLOAD_CALLBACK] = function () {
7592 _window().clearTimeout(networkTimeout);
7593 delete _window()[_JSLOAD_CALLBACK];
7594 var recaptcha = _window().grecaptcha;
7595 if (!recaptcha) {
7596 reject(_createError(auth, "internal-error" /* INTERNAL_ERROR */));
7597 return;
7598 }
7599 // Wrap the greptcha render function so that we know if the developer has
7600 // called it separately
7601 var render = recaptcha.render;
7602 recaptcha.render = function (container, params) {
7603 var widgetId = render(container, params);
7604 _this.counter++;
7605 return widgetId;
7606 };
7607 _this.hostLanguage = hl;
7608 resolve(recaptcha);
7609 };
7610 var url = RECAPTCHA_BASE + "?" + util.querystring({
7611 onload: _JSLOAD_CALLBACK,
7612 render: 'explicit',
7613 hl: hl
7614 });
7615 _loadJS(url).catch(function () {
7616 clearTimeout(networkTimeout);
7617 reject(_createError(auth, "internal-error" /* INTERNAL_ERROR */));
7618 });
7619 });
7620 };
7621 ReCaptchaLoaderImpl.prototype.clearedOneInstance = function () {
7622 this.counter--;
7623 };
7624 ReCaptchaLoaderImpl.prototype.shouldResolveImmediately = function (hl) {
7625 var _a;
7626 // We can resolve immediately if:
7627 // • grecaptcha is already defined AND (
7628 // 1. the requested language codes are the same OR
7629 // 2. there exists already a ReCaptcha on the page
7630 // 3. the library was already loaded by the app
7631 // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
7632 // that are already in the page
7633 return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
7634 (hl === this.hostLanguage ||
7635 this.counter > 0 ||
7636 this.librarySeparatelyLoaded));
7637 };
7638 return ReCaptchaLoaderImpl;
7639}());
7640function isHostLanguageValid(hl) {
7641 return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
7642}
7643var MockReCaptchaLoaderImpl = /** @class */ (function () {
7644 function MockReCaptchaLoaderImpl() {
7645 }
7646 MockReCaptchaLoaderImpl.prototype.load = function (auth) {
7647 return tslib.__awaiter(this, void 0, void 0, function () {
7648 return tslib.__generator(this, function (_a) {
7649 return [2 /*return*/, new MockReCaptcha(auth)];
7650 });
7651 });
7652 };
7653 MockReCaptchaLoaderImpl.prototype.clearedOneInstance = function () { };
7654 return MockReCaptchaLoaderImpl;
7655}());
7656
7657/**
7658 * @license
7659 * Copyright 2020 Google LLC
7660 *
7661 * Licensed under the Apache License, Version 2.0 (the "License");
7662 * you may not use this file except in compliance with the License.
7663 * You may obtain a copy of the License at
7664 *
7665 * http://www.apache.org/licenses/LICENSE-2.0
7666 *
7667 * Unless required by applicable law or agreed to in writing, software
7668 * distributed under the License is distributed on an "AS IS" BASIS,
7669 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7670 * See the License for the specific language governing permissions and
7671 * limitations under the License.
7672 */
7673var RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
7674var DEFAULT_PARAMS = {
7675 theme: 'light',
7676 type: 'image'
7677};
7678/**
7679 * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
7680 *
7681 * @public
7682 */
7683var RecaptchaVerifier = /** @class */ (function () {
7684 /**
7685 *
7686 * @param containerOrId - The reCAPTCHA container parameter.
7687 *
7688 * @remarks
7689 * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
7690 * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
7691 * an element ID. The corresponding element must also must be in the DOM at the time of
7692 * initialization.
7693 *
7694 * @param parameters - The optional reCAPTCHA parameters.
7695 *
7696 * @remarks
7697 * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
7698 * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
7699 * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
7700 * 'invisible'.
7701 *
7702 * @param authExtern - The corresponding Firebase {@link Auth} instance.
7703 *
7704 * @remarks
7705 * If none is provided, the default Firebase {@link Auth} instance is used. A Firebase {@link Auth} instance
7706 * must be initialized with an API key, otherwise an error will be thrown.
7707 */
7708 function RecaptchaVerifier(containerOrId, parameters, authExtern) {
7709 if (parameters === void 0) { parameters = tslib.__assign({}, DEFAULT_PARAMS); }
7710 this.parameters = parameters;
7711 /**
7712 * The application verifier type.
7713 *
7714 * @remarks
7715 * For a reCAPTCHA verifier, this is 'recaptcha'.
7716 */
7717 this.type = RECAPTCHA_VERIFIER_TYPE;
7718 this.destroyed = false;
7719 this.widgetId = null;
7720 this.tokenChangeListeners = new Set();
7721 this.renderPromise = null;
7722 this.recaptcha = null;
7723 this.auth = _castAuth(authExtern);
7724 this.isInvisible = this.parameters.size === 'invisible';
7725 _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
7726 var container = typeof containerOrId === 'string'
7727 ? document.getElementById(containerOrId)
7728 : containerOrId;
7729 _assert(container, this.auth, "argument-error" /* ARGUMENT_ERROR */);
7730 this.container = container;
7731 this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
7732 this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
7733 ? new MockReCaptchaLoaderImpl()
7734 : new ReCaptchaLoaderImpl();
7735 this.validateStartingState();
7736 // TODO: Figure out if sdk version is needed
7737 }
7738 /**
7739 * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
7740 *
7741 * @returns A Promise for the reCAPTCHA token.
7742 */
7743 RecaptchaVerifier.prototype.verify = function () {
7744 return tslib.__awaiter(this, void 0, void 0, function () {
7745 var id, recaptcha, response;
7746 var _this = this;
7747 return tslib.__generator(this, function (_a) {
7748 switch (_a.label) {
7749 case 0:
7750 this.assertNotDestroyed();
7751 return [4 /*yield*/, this.render()];
7752 case 1:
7753 id = _a.sent();
7754 recaptcha = this.getAssertedRecaptcha();
7755 response = recaptcha.getResponse(id);
7756 if (response) {
7757 return [2 /*return*/, response];
7758 }
7759 return [2 /*return*/, new Promise(function (resolve) {
7760 var tokenChange = function (token) {
7761 if (!token) {
7762 return; // Ignore token expirations.
7763 }
7764 _this.tokenChangeListeners.delete(tokenChange);
7765 resolve(token);
7766 };
7767 _this.tokenChangeListeners.add(tokenChange);
7768 if (_this.isInvisible) {
7769 recaptcha.execute(id);
7770 }
7771 })];
7772 }
7773 });
7774 });
7775 };
7776 /**
7777 * Renders the reCAPTCHA widget on the page.
7778 *
7779 * @returns A Promise that resolves with the reCAPTCHA widget ID.
7780 */
7781 RecaptchaVerifier.prototype.render = function () {
7782 var _this = this;
7783 try {
7784 this.assertNotDestroyed();
7785 }
7786 catch (e) {
7787 // This method returns a promise. Since it's not async (we want to return the
7788 // _same_ promise if rendering is still occurring), the API surface should
7789 // reject with the error rather than just throw
7790 return Promise.reject(e);
7791 }
7792 if (this.renderPromise) {
7793 return this.renderPromise;
7794 }
7795 this.renderPromise = this.makeRenderPromise().catch(function (e) {
7796 _this.renderPromise = null;
7797 throw e;
7798 });
7799 return this.renderPromise;
7800 };
7801 /** @internal */
7802 RecaptchaVerifier.prototype._reset = function () {
7803 this.assertNotDestroyed();
7804 if (this.widgetId !== null) {
7805 this.getAssertedRecaptcha().reset(this.widgetId);
7806 }
7807 };
7808 /**
7809 * Clears the reCAPTCHA widget from the page and destroys the instance.
7810 */
7811 RecaptchaVerifier.prototype.clear = function () {
7812 var _this = this;
7813 this.assertNotDestroyed();
7814 this.destroyed = true;
7815 this._recaptchaLoader.clearedOneInstance();
7816 if (!this.isInvisible) {
7817 this.container.childNodes.forEach(function (node) {
7818 _this.container.removeChild(node);
7819 });
7820 }
7821 };
7822 RecaptchaVerifier.prototype.validateStartingState = function () {
7823 _assert(!this.parameters.sitekey, this.auth, "argument-error" /* ARGUMENT_ERROR */);
7824 _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* ARGUMENT_ERROR */);
7825 _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
7826 };
7827 RecaptchaVerifier.prototype.makeTokenCallback = function (existing) {
7828 var _this = this;
7829 return function (token) {
7830 _this.tokenChangeListeners.forEach(function (listener) { return listener(token); });
7831 if (typeof existing === 'function') {
7832 existing(token);
7833 }
7834 else if (typeof existing === 'string') {
7835 var globalFunc = _window()[existing];
7836 if (typeof globalFunc === 'function') {
7837 globalFunc(token);
7838 }
7839 }
7840 };
7841 };
7842 RecaptchaVerifier.prototype.assertNotDestroyed = function () {
7843 _assert(!this.destroyed, this.auth, "internal-error" /* INTERNAL_ERROR */);
7844 };
7845 RecaptchaVerifier.prototype.makeRenderPromise = function () {
7846 return tslib.__awaiter(this, void 0, void 0, function () {
7847 var container, guaranteedEmpty;
7848 return tslib.__generator(this, function (_a) {
7849 switch (_a.label) {
7850 case 0: return [4 /*yield*/, this.init()];
7851 case 1:
7852 _a.sent();
7853 if (!this.widgetId) {
7854 container = this.container;
7855 if (!this.isInvisible) {
7856 guaranteedEmpty = document.createElement('div');
7857 container.appendChild(guaranteedEmpty);
7858 container = guaranteedEmpty;
7859 }
7860 this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
7861 }
7862 return [2 /*return*/, this.widgetId];
7863 }
7864 });
7865 });
7866 };
7867 RecaptchaVerifier.prototype.init = function () {
7868 return tslib.__awaiter(this, void 0, void 0, function () {
7869 var _a, siteKey;
7870 return tslib.__generator(this, function (_b) {
7871 switch (_b.label) {
7872 case 0:
7873 _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* INTERNAL_ERROR */);
7874 return [4 /*yield*/, domReady()];
7875 case 1:
7876 _b.sent();
7877 _a = this;
7878 return [4 /*yield*/, this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined)];
7879 case 2:
7880 _a.recaptcha = _b.sent();
7881 return [4 /*yield*/, getRecaptchaParams(this.auth)];
7882 case 3:
7883 siteKey = _b.sent();
7884 _assert(siteKey, this.auth, "internal-error" /* INTERNAL_ERROR */);
7885 this.parameters.sitekey = siteKey;
7886 return [2 /*return*/];
7887 }
7888 });
7889 });
7890 };
7891 RecaptchaVerifier.prototype.getAssertedRecaptcha = function () {
7892 _assert(this.recaptcha, this.auth, "internal-error" /* INTERNAL_ERROR */);
7893 return this.recaptcha;
7894 };
7895 return RecaptchaVerifier;
7896}());
7897function domReady() {
7898 var resolver = null;
7899 return new Promise(function (resolve) {
7900 if (document.readyState === 'complete') {
7901 resolve();
7902 return;
7903 }
7904 // Document not ready, wait for load before resolving.
7905 // Save resolver, so we can remove listener in case it was externally
7906 // cancelled.
7907 resolver = function () { return resolve(); };
7908 window.addEventListener('load', resolver);
7909 }).catch(function (e) {
7910 if (resolver) {
7911 window.removeEventListener('load', resolver);
7912 }
7913 throw e;
7914 });
7915}
7916
7917/**
7918 * @license
7919 * Copyright 2020 Google LLC
7920 *
7921 * Licensed under the Apache License, Version 2.0 (the "License");
7922 * you may not use this file except in compliance with the License.
7923 * You may obtain a copy of the License at
7924 *
7925 * http://www.apache.org/licenses/LICENSE-2.0
7926 *
7927 * Unless required by applicable law or agreed to in writing, software
7928 * distributed under the License is distributed on an "AS IS" BASIS,
7929 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7930 * See the License for the specific language governing permissions and
7931 * limitations under the License.
7932 */
7933var ConfirmationResultImpl = /** @class */ (function () {
7934 function ConfirmationResultImpl(verificationId, onConfirmation) {
7935 this.verificationId = verificationId;
7936 this.onConfirmation = onConfirmation;
7937 }
7938 ConfirmationResultImpl.prototype.confirm = function (verificationCode) {
7939 var authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
7940 return this.onConfirmation(authCredential);
7941 };
7942 return ConfirmationResultImpl;
7943}());
7944/**
7945 * Asynchronously signs in using a phone number.
7946 *
7947 * @remarks
7948 * This method sends a code via SMS to the given
7949 * phone number, and returns a {@link ConfirmationResult}. After the user
7950 * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
7951 * with the code to sign the user in.
7952 *
7953 * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
7954 * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
7955 * This function can work on other platforms that do not support the
7956 * {@link RecaptchaVerifier} (like React Native), but you need to use a
7957 * third-party {@link ApplicationVerifier} implementation.
7958 *
7959 * @example
7960 * ```javascript
7961 * // 'recaptcha-container' is the ID of an element in the DOM.
7962 * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
7963 * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
7964 * // Obtain a verificationCode from the user.
7965 * const credential = await confirmationResult.confirm(verificationCode);
7966 * ```
7967 *
7968 * @param auth - The {@link Auth} instance.
7969 * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
7970 * @param appVerifier - The {@link ApplicationVerifier}.
7971 *
7972 * @public
7973 */
7974function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
7975 return tslib.__awaiter(this, void 0, void 0, function () {
7976 var authInternal, verificationId;
7977 return tslib.__generator(this, function (_a) {
7978 switch (_a.label) {
7979 case 0:
7980 authInternal = _castAuth(auth);
7981 return [4 /*yield*/, _verifyPhoneNumber(authInternal, phoneNumber, util.getModularInstance(appVerifier))];
7982 case 1:
7983 verificationId = _a.sent();
7984 return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
7985 return signInWithCredential(authInternal, cred);
7986 })];
7987 }
7988 });
7989 });
7990}
7991/**
7992 * Links the user account with the given phone number.
7993 *
7994 * @param user - The user.
7995 * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
7996 * @param appVerifier - The {@link ApplicationVerifier}.
7997 *
7998 * @public
7999 */
8000function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
8001 return tslib.__awaiter(this, void 0, void 0, function () {
8002 var userInternal, verificationId;
8003 return tslib.__generator(this, function (_a) {
8004 switch (_a.label) {
8005 case 0:
8006 userInternal = util.getModularInstance(user);
8007 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, "phone" /* PHONE */)];
8008 case 1:
8009 _a.sent();
8010 return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, util.getModularInstance(appVerifier))];
8011 case 2:
8012 verificationId = _a.sent();
8013 return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
8014 return linkWithCredential(userInternal, cred);
8015 })];
8016 }
8017 });
8018 });
8019}
8020/**
8021 * Re-authenticates a user using a fresh phone credential.
8022 *
8023 * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
8024 *
8025 * @param user - The user.
8026 * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
8027 * @param appVerifier - The {@link ApplicationVerifier}.
8028 *
8029 * @public
8030 */
8031function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
8032 return tslib.__awaiter(this, void 0, void 0, function () {
8033 var userInternal, verificationId;
8034 return tslib.__generator(this, function (_a) {
8035 switch (_a.label) {
8036 case 0:
8037 userInternal = util.getModularInstance(user);
8038 return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, util.getModularInstance(appVerifier))];
8039 case 1:
8040 verificationId = _a.sent();
8041 return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
8042 return reauthenticateWithCredential(userInternal, cred);
8043 })];
8044 }
8045 });
8046 });
8047}
8048/**
8049 * Returns a verification ID to be used in conjunction with the SMS code that is sent.
8050 *
8051 */
8052function _verifyPhoneNumber(auth, options, verifier) {
8053 var _a;
8054 return tslib.__awaiter(this, void 0, void 0, function () {
8055 var recaptchaToken, phoneInfoOptions, session, response, mfaEnrollmentId, response, sessionInfo;
8056 return tslib.__generator(this, function (_b) {
8057 switch (_b.label) {
8058 case 0: return [4 /*yield*/, verifier.verify()];
8059 case 1:
8060 recaptchaToken = _b.sent();
8061 _b.label = 2;
8062 case 2:
8063 _b.trys.push([2, , 10, 11]);
8064 _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* ARGUMENT_ERROR */);
8065 _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* ARGUMENT_ERROR */);
8066 phoneInfoOptions = void 0;
8067 if (typeof options === 'string') {
8068 phoneInfoOptions = {
8069 phoneNumber: options
8070 };
8071 }
8072 else {
8073 phoneInfoOptions = options;
8074 }
8075 if (!('session' in phoneInfoOptions)) return [3 /*break*/, 7];
8076 session = phoneInfoOptions.session;
8077 if (!('phoneNumber' in phoneInfoOptions)) return [3 /*break*/, 4];
8078 _assert(session.type === "enroll" /* ENROLL */, auth, "internal-error" /* INTERNAL_ERROR */);
8079 return [4 /*yield*/, startEnrollPhoneMfa(auth, {
8080 idToken: session.credential,
8081 phoneEnrollmentInfo: {
8082 phoneNumber: phoneInfoOptions.phoneNumber,
8083 recaptchaToken: recaptchaToken
8084 }
8085 })];
8086 case 3:
8087 response = _b.sent();
8088 return [2 /*return*/, response.phoneSessionInfo.sessionInfo];
8089 case 4:
8090 _assert(session.type === "signin" /* SIGN_IN */, auth, "internal-error" /* INTERNAL_ERROR */);
8091 mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
8092 phoneInfoOptions.multiFactorUid;
8093 _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* MISSING_MFA_INFO */);
8094 return [4 /*yield*/, startSignInPhoneMfa(auth, {
8095 mfaPendingCredential: session.credential,
8096 mfaEnrollmentId: mfaEnrollmentId,
8097 phoneSignInInfo: {
8098 recaptchaToken: recaptchaToken
8099 }
8100 })];
8101 case 5:
8102 response = _b.sent();
8103 return [2 /*return*/, response.phoneResponseInfo.sessionInfo];
8104 case 6: return [3 /*break*/, 9];
8105 case 7: return [4 /*yield*/, sendPhoneVerificationCode(auth, {
8106 phoneNumber: phoneInfoOptions.phoneNumber,
8107 recaptchaToken: recaptchaToken
8108 })];
8109 case 8:
8110 sessionInfo = (_b.sent()).sessionInfo;
8111 return [2 /*return*/, sessionInfo];
8112 case 9: return [3 /*break*/, 11];
8113 case 10:
8114 verifier._reset();
8115 return [7 /*endfinally*/];
8116 case 11: return [2 /*return*/];
8117 }
8118 });
8119 });
8120}
8121/**
8122 * Updates the user's phone number.
8123 *
8124 * @example
8125 * ```
8126 * // 'recaptcha-container' is the ID of an element in the DOM.
8127 * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
8128 * const provider = new PhoneAuthProvider(auth);
8129 * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
8130 * // Obtain the verificationCode from the user.
8131 * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
8132 * await updatePhoneNumber(user, phoneCredential);
8133 * ```
8134 *
8135 * @param user - The user.
8136 * @param credential - A credential authenticating the new phone number.
8137 *
8138 * @public
8139 */
8140function updatePhoneNumber(user, credential) {
8141 return tslib.__awaiter(this, void 0, void 0, function () {
8142 return tslib.__generator(this, function (_a) {
8143 switch (_a.label) {
8144 case 0: return [4 /*yield*/, _link(util.getModularInstance(user), credential)];
8145 case 1:
8146 _a.sent();
8147 return [2 /*return*/];
8148 }
8149 });
8150 });
8151}
8152
8153/**
8154 * @license
8155 * Copyright 2020 Google LLC
8156 *
8157 * Licensed under the Apache License, Version 2.0 (the "License");
8158 * you may not use this file except in compliance with the License.
8159 * You may obtain a copy of the License at
8160 *
8161 * http://www.apache.org/licenses/LICENSE-2.0
8162 *
8163 * Unless required by applicable law or agreed to in writing, software
8164 * distributed under the License is distributed on an "AS IS" BASIS,
8165 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8166 * See the License for the specific language governing permissions and
8167 * limitations under the License.
8168 */
8169/**
8170 * Provider for generating an {@link PhoneAuthCredential}.
8171 *
8172 * @example
8173 * ```javascript
8174 * // 'recaptcha-container' is the ID of an element in the DOM.
8175 * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
8176 * const provider = new PhoneAuthProvider(auth);
8177 * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
8178 * // Obtain the verificationCode from the user.
8179 * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
8180 * const userCredential = await signInWithCredential(auth, phoneCredential);
8181 * ```
8182 *
8183 * @public
8184 */
8185var PhoneAuthProvider = /** @class */ (function () {
8186 /**
8187 * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
8188 *
8189 */
8190 function PhoneAuthProvider(auth) {
8191 /** Always set to {@link ProviderId}.PHONE. */
8192 this.providerId = PhoneAuthProvider.PROVIDER_ID;
8193 this.auth = _castAuth(auth);
8194 }
8195 /**
8196 *
8197 * Starts a phone number authentication flow by sending a verification code to the given phone
8198 * number.
8199 *
8200 * @example
8201 * ```javascript
8202 * const provider = new PhoneAuthProvider(auth);
8203 * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
8204 * // Obtain verificationCode from the user.
8205 * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
8206 * const userCredential = await signInWithCredential(auth, authCredential);
8207 * ```
8208 *
8209 * @example
8210 * An alternative flow is provided using the `signInWithPhoneNumber` method.
8211 * ```javascript
8212 * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
8213 * // Obtain verificationCode from the user.
8214 * const userCredential = confirmationResult.confirm(verificationCode);
8215 * ```
8216 *
8217 * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
8218 * E.164 format (e.g. +16505550101).
8219 * @param applicationVerifier - For abuse prevention, this method also requires a
8220 * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
8221 * {@link RecaptchaVerifier}.
8222 *
8223 * @returns A Promise for a verification ID that can be passed to
8224 * {@link PhoneAuthProvider.credential} to identify this flow..
8225 */
8226 PhoneAuthProvider.prototype.verifyPhoneNumber = function (phoneOptions, applicationVerifier) {
8227 return _verifyPhoneNumber(this.auth, phoneOptions, util.getModularInstance(applicationVerifier));
8228 };
8229 /**
8230 * Creates a phone auth credential, given the verification ID from
8231 * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
8232 * mobile device.
8233 *
8234 * @example
8235 * ```javascript
8236 * const provider = new PhoneAuthProvider(auth);
8237 * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
8238 * // Obtain verificationCode from the user.
8239 * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
8240 * const userCredential = signInWithCredential(auth, authCredential);
8241 * ```
8242 *
8243 * @example
8244 * An alternative flow is provided using the `signInWithPhoneNumber` method.
8245 * ```javascript
8246 * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
8247 * // Obtain verificationCode from the user.
8248 * const userCredential = await confirmationResult.confirm(verificationCode);
8249 * ```
8250 *
8251 * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
8252 * @param verificationCode - The verification code sent to the user's mobile device.
8253 *
8254 * @returns The auth provider credential.
8255 */
8256 PhoneAuthProvider.credential = function (verificationId, verificationCode) {
8257 return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
8258 };
8259 /**
8260 * Generates an {@link AuthCredential} from a {@link UserCredential}.
8261 * @param userCredential - The user credential.
8262 */
8263 PhoneAuthProvider.credentialFromResult = function (userCredential) {
8264 var credential = userCredential;
8265 return PhoneAuthProvider.credentialFromTaggedObject(credential);
8266 };
8267 /**
8268 * Returns an {@link AuthCredential} when passed an error.
8269 *
8270 * @remarks
8271 *
8272 * This method works for errors like
8273 * `auth/account-exists-with-different-credentials`. This is useful for
8274 * recovering when attempting to set a user's phone number but the number
8275 * in question is already tied to another account. For example, the following
8276 * code tries to update the current user's phone number, and if that
8277 * fails, links the user with the account associated with that number:
8278 *
8279 * ```js
8280 * const provider = new PhoneAuthProvider(auth);
8281 * const verificationId = await provider.verifyPhoneNumber(number, verifier);
8282 * try {
8283 * const code = ''; // Prompt the user for the verification code
8284 * await updatePhoneNumber(
8285 * auth.currentUser,
8286 * PhoneAuthProvider.credential(verificationId, code));
8287 * } catch (e) {
8288 * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
8289 * const cred = PhoneAuthProvider.credentialFromError(e);
8290 * await linkWithCredential(auth.currentUser, cred);
8291 * }
8292 * }
8293 *
8294 * // At this point, auth.currentUser.phoneNumber === number.
8295 * ```
8296 *
8297 * @param error - The error to generate a credential from.
8298 */
8299 PhoneAuthProvider.credentialFromError = function (error) {
8300 return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
8301 };
8302 PhoneAuthProvider.credentialFromTaggedObject = function (_a) {
8303 var tokenResponse = _a._tokenResponse;
8304 if (!tokenResponse) {
8305 return null;
8306 }
8307 var _b = tokenResponse, phoneNumber = _b.phoneNumber, temporaryProof = _b.temporaryProof;
8308 if (phoneNumber && temporaryProof) {
8309 return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
8310 }
8311 return null;
8312 };
8313 /** Always set to {@link ProviderId}.PHONE. */
8314 PhoneAuthProvider.PROVIDER_ID = "phone" /* PHONE */;
8315 /** Always set to {@link SignInMethod}.PHONE. */
8316 PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* PHONE */;
8317 return PhoneAuthProvider;
8318}());
8319
8320var MultiFactorAssertionImpl = /** @class */ (function () {
8321 function MultiFactorAssertionImpl(factorId) {
8322 this.factorId = factorId;
8323 }
8324 MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
8325 switch (session.type) {
8326 case "enroll" /* ENROLL */:
8327 return this._finalizeEnroll(auth, session.credential, displayName);
8328 case "signin" /* SIGN_IN */:
8329 return this._finalizeSignIn(auth, session.credential);
8330 default:
8331 return debugFail('unexpected MultiFactorSessionType');
8332 }
8333 };
8334 return MultiFactorAssertionImpl;
8335}());
8336
8337/**
8338 * {@inheritdoc PhoneMultiFactorAssertion}
8339 *
8340 * @public
8341 */
8342var PhoneMultiFactorAssertionImpl = /** @class */ (function (_super) {
8343 tslib.__extends(PhoneMultiFactorAssertionImpl, _super);
8344 function PhoneMultiFactorAssertionImpl(credential) {
8345 var _this = _super.call(this, "phone" /* PHONE */) || this;
8346 _this.credential = credential;
8347 return _this;
8348 }
8349 /** @internal */
8350 PhoneMultiFactorAssertionImpl._fromCredential = function (credential) {
8351 return new PhoneMultiFactorAssertionImpl(credential);
8352 };
8353 /** @internal */
8354 PhoneMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
8355 return finalizeEnrollPhoneMfa(auth, {
8356 idToken: idToken,
8357 displayName: displayName,
8358 phoneVerificationInfo: this.credential._makeVerificationRequest()
8359 });
8360 };
8361 /** @internal */
8362 PhoneMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
8363 return finalizeSignInPhoneMfa(auth, {
8364 mfaPendingCredential: mfaPendingCredential,
8365 phoneVerificationInfo: this.credential._makeVerificationRequest()
8366 });
8367 };
8368 return PhoneMultiFactorAssertionImpl;
8369}(MultiFactorAssertionImpl));
8370/**
8371 * Provider for generating a {@link PhoneMultiFactorAssertion}.
8372 *
8373 * @public
8374 */
8375var PhoneMultiFactorGenerator = /** @class */ (function () {
8376 function PhoneMultiFactorGenerator() {
8377 }
8378 /**
8379 * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
8380 *
8381 * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
8382 * @returns A {@link PhoneMultiFactorAssertion} which can be used with
8383 * {@link MultiFactorResolver.resolveSignIn}
8384 */
8385 PhoneMultiFactorGenerator.assertion = function (credential) {
8386 return PhoneMultiFactorAssertionImpl._fromCredential(credential);
8387 };
8388 /**
8389 * The identifier of the phone second factor: `phone`.
8390 */
8391 PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
8392 return PhoneMultiFactorGenerator;
8393}());
8394
8395exports.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;
8396exports.ActionCodeOperation = ActionCodeOperation;
8397exports.ActionCodeURL = ActionCodeURL;
8398exports.AuthCredential = AuthCredential;
8399exports.AuthImpl = AuthImpl;
8400exports.BaseOAuthProvider = BaseOAuthProvider;
8401exports.Delay = Delay;
8402exports.EmailAuthCredential = EmailAuthCredential;
8403exports.EmailAuthProvider = EmailAuthProvider;
8404exports.FacebookAuthProvider = FacebookAuthProvider;
8405exports.FactorId = FactorId;
8406exports.FederatedAuthProvider = FederatedAuthProvider;
8407exports.FetchProvider = FetchProvider;
8408exports.GithubAuthProvider = GithubAuthProvider;
8409exports.GoogleAuthProvider = GoogleAuthProvider;
8410exports.OAuthCredential = OAuthCredential;
8411exports.OAuthProvider = OAuthProvider;
8412exports.OperationType = OperationType;
8413exports.PhoneAuthCredential = PhoneAuthCredential;
8414exports.PhoneAuthProvider = PhoneAuthProvider;
8415exports.PhoneMultiFactorGenerator = PhoneMultiFactorGenerator;
8416exports.ProviderId = ProviderId;
8417exports.RecaptchaVerifier = RecaptchaVerifier;
8418exports.SAMLAuthCredential = SAMLAuthCredential;
8419exports.SAMLAuthProvider = SAMLAuthProvider;
8420exports.STORAGE_AVAILABLE_KEY = STORAGE_AVAILABLE_KEY;
8421exports.SignInMethod = SignInMethod;
8422exports.TwitterAuthProvider = TwitterAuthProvider;
8423exports.UserImpl = UserImpl;
8424exports._assert = _assert;
8425exports._assertInstanceOf = _assertInstanceOf;
8426exports._assertLinkedStatus = _assertLinkedStatus;
8427exports._castAuth = _castAuth;
8428exports._createError = _createError;
8429exports._emulatorUrl = _emulatorUrl;
8430exports._fail = _fail;
8431exports._generateCallbackName = _generateCallbackName;
8432exports._getActiveServiceWorker = _getActiveServiceWorker;
8433exports._getClientVersion = _getClientVersion;
8434exports._getCurrentUrl = _getCurrentUrl;
8435exports._getInstance = _getInstance;
8436exports._getServiceWorkerController = _getServiceWorkerController;
8437exports._getWorkerGlobalScope = _getWorkerGlobalScope;
8438exports._isAndroid = _isAndroid;
8439exports._isChromeIOS = _isChromeIOS;
8440exports._isFirefox = _isFirefox;
8441exports._isIE10 = _isIE10;
8442exports._isIOS = _isIOS;
8443exports._isIOS7Or8 = _isIOS7Or8;
8444exports._isIOSStandalone = _isIOSStandalone;
8445exports._isIframe = _isIframe;
8446exports._isMobileBrowser = _isMobileBrowser;
8447exports._isSafari = _isSafari;
8448exports._isWorker = _isWorker;
8449exports._link = _link;
8450exports._loadJS = _loadJS;
8451exports._performApiRequest = _performApiRequest;
8452exports._persistenceKeyName = _persistenceKeyName;
8453exports._reauthenticate = _reauthenticate;
8454exports._setWindowLocation = _setWindowLocation;
8455exports._signInWithCredential = _signInWithCredential;
8456exports._window = _window;
8457exports.applyActionCode = applyActionCode;
8458exports.beforeAuthStateChanged = beforeAuthStateChanged;
8459exports.checkActionCode = checkActionCode;
8460exports.confirmPasswordReset = confirmPasswordReset;
8461exports.connectAuthEmulator = connectAuthEmulator;
8462exports.createUserWithEmailAndPassword = createUserWithEmailAndPassword;
8463exports.debugAssert = debugAssert;
8464exports.debugErrorMap = debugErrorMap;
8465exports.deleteUser = deleteUser;
8466exports.fetchSignInMethodsForEmail = fetchSignInMethodsForEmail;
8467exports.getAdditionalUserInfo = getAdditionalUserInfo;
8468exports.getIdToken = getIdToken;
8469exports.getIdTokenResult = getIdTokenResult;
8470exports.getMultiFactorResolver = getMultiFactorResolver;
8471exports.inMemoryPersistence = inMemoryPersistence;
8472exports.initializeAuth = initializeAuth;
8473exports.isSignInWithEmailLink = isSignInWithEmailLink;
8474exports.linkWithCredential = linkWithCredential;
8475exports.linkWithPhoneNumber = linkWithPhoneNumber;
8476exports.multiFactor = multiFactor;
8477exports.onAuthStateChanged = onAuthStateChanged;
8478exports.onIdTokenChanged = onIdTokenChanged;
8479exports.parseActionCodeURL = parseActionCodeURL;
8480exports.prodErrorMap = prodErrorMap;
8481exports.reauthenticateWithCredential = reauthenticateWithCredential;
8482exports.reauthenticateWithPhoneNumber = reauthenticateWithPhoneNumber;
8483exports.registerAuth = registerAuth;
8484exports.reload = reload;
8485exports.sendEmailVerification = sendEmailVerification;
8486exports.sendPasswordResetEmail = sendPasswordResetEmail;
8487exports.sendSignInLinkToEmail = sendSignInLinkToEmail;
8488exports.setPersistence = setPersistence;
8489exports.signInAnonymously = signInAnonymously;
8490exports.signInWithCredential = signInWithCredential;
8491exports.signInWithCustomToken = signInWithCustomToken;
8492exports.signInWithEmailAndPassword = signInWithEmailAndPassword;
8493exports.signInWithEmailLink = signInWithEmailLink;
8494exports.signInWithIdp = signInWithIdp;
8495exports.signInWithPhoneNumber = signInWithPhoneNumber;
8496exports.signOut = signOut;
8497exports.unlink = unlink;
8498exports.updateCurrentUser = updateCurrentUser;
8499exports.updateEmail = updateEmail;
8500exports.updatePassword = updatePassword;
8501exports.updatePhoneNumber = updatePhoneNumber;
8502exports.updateProfile = updateProfile;
8503exports.useDeviceLanguage = useDeviceLanguage;
8504exports.verifyBeforeUpdateEmail = verifyBeforeUpdateEmail;
8505exports.verifyPasswordResetCode = verifyPasswordResetCode;
8506//# sourceMappingURL=phone-51423d6b.js.map