UNPKG

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