UNPKG

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