UNPKG

@stanfordspezi/spezi-web-design-system

Version:

Stanford Biodesign Digital Health Spezi Web Design System

1,436 lines 52.5 kB
import { L as Te, g as we, i as Ae, a as ke, _ as $, C as G, r as q, b as Se, c as V, d as z, e as _, f as k, h as Ne, j as re, k as f, F as ie, l as ve, q as ne, n as se, o as Ee } from "./SignInForm-mZh0yQy5.mjs"; import { useState as Pe, useEffect as Ce } from "react"; function ae() { return { "dependent-sdk-initialized-before-auth": "Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK." }; } const Re = ae, oe = new z("auth", "Firebase", ae()); const P = new Te("@firebase/auth"); function Ue(r, ...e) { P.logLevel <= re.WARN && P.warn(`Auth (${V}): ${r}`, ...e); } function v(r, ...e) { P.logLevel <= re.ERROR && P.error(`Auth (${V}): ${r}`, ...e); } function J(r, ...e) { throw H(r, ...e); } function ce(r, ...e) { return H(r, ...e); } function ue(r, e, t) { const i = { ...Re(), [e]: t }; return new z("auth", "Firebase", i).create(e, { appName: r.name }); } function E(r) { return ue(r, "operation-not-supported-in-this-environment", "Operations that alter the current user are not supported in conjunction with FirebaseServerApp"); } function H(r, ...e) { if (typeof r != "string") { const t = e[0], i = [...e.slice(1)]; return i[0] && (i[0].appName = r.name), r._errorFactory.create(t, ...i); } return oe.create(r, ...e); } function c(r, e, ...t) { if (!r) throw H(e, ...t); } function w(r) { const e = "INTERNAL ASSERTION FAILED: " + r; throw v(e), new Error(e); } function C(r, e) { r || w(e); } function be() { return B() === "http:" || B() === "https:"; } function B() { return typeof self < "u" && self.location?.protocol || null; } function Le() { return typeof navigator < "u" && navigator && "onLine" in navigator && typeof navigator.onLine == "boolean" && // Apply only for traditional web apps and Chrome extensions. // This is especially true for Cordova apps which have unreliable // navigator.onLine behavior unless cordova-plugin-network-information is // installed which overwrites the native navigator.onLine value and // defines navigator.connection. (be() || Se() || "connection" in navigator) ? navigator.onLine : !0; } function Oe() { if (typeof navigator > "u") return null; const r = navigator; return ( // Most reliable, but only supported in Chrome/Firefox. r.languages && r.languages[0] || // Supported in most browsers, but returns the language of the browser // UI, not the language set in browser settings. r.language || // Couldn't determine language. null ); } class S { constructor(e, t) { this.shortDelay = e, this.longDelay = t, C(t > e, "Short delay should be less than long delay!"), this.isMobile = Ae() || ke(); } get() { return Le() ? this.isMobile ? this.longDelay : this.shortDelay : Math.min(5e3, this.shortDelay); } } function Me(r, e) { C(r.emulator, "Emulator should always be set here"); const { url: t } = r.emulator; return e ? `${t}${e.startsWith("/") ? e.slice(1) : e}` : t; } class he { static initialize(e, t, i) { this.fetchImpl = e, t && (this.headersImpl = t), i && (this.responseImpl = i); } static fetch() { if (this.fetchImpl) return this.fetchImpl; if (typeof self < "u" && "fetch" in self) return self.fetch; if (typeof globalThis < "u" && globalThis.fetch) return globalThis.fetch; if (typeof fetch < "u") return fetch; w("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"); } static headers() { if (this.headersImpl) return this.headersImpl; if (typeof self < "u" && "Headers" in self) return self.Headers; if (typeof globalThis < "u" && globalThis.Headers) return globalThis.Headers; if (typeof Headers < "u") return Headers; w("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"); } static response() { if (this.responseImpl) return this.responseImpl; if (typeof self < "u" && "Response" in self) return self.Response; if (typeof globalThis < "u" && globalThis.Response) return globalThis.Response; if (typeof Response < "u") return Response; w("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"); } } const De = { // Custom token errors. CREDENTIAL_MISMATCH: "custom-token-mismatch", // This can only happen if the SDK sends a bad request. MISSING_CUSTOM_TOKEN: "internal-error", // Create Auth URI errors. INVALID_IDENTIFIER: "invalid-email", // This can only happen if the SDK sends a bad request. MISSING_CONTINUE_URI: "internal-error", // Sign in with email and password errors (some apply to sign up too). INVALID_PASSWORD: "wrong-password", // This can only happen if the SDK sends a bad request. MISSING_PASSWORD: "missing-password", // Thrown if Email Enumeration Protection is enabled in the project and the email or password is // invalid. INVALID_LOGIN_CREDENTIALS: "invalid-credential", // Sign up with email and password errors. EMAIL_EXISTS: "email-already-in-use", PASSWORD_LOGIN_DISABLED: "operation-not-allowed", // Verify assertion for sign in with credential errors: INVALID_IDP_RESPONSE: "invalid-credential", INVALID_PENDING_TOKEN: "invalid-credential", FEDERATED_USER_ID_ALREADY_LINKED: "credential-already-in-use", // This can only happen if the SDK sends a bad request. MISSING_REQ_TYPE: "internal-error", // Send Password reset email errors: EMAIL_NOT_FOUND: "user-not-found", RESET_PASSWORD_EXCEED_LIMIT: "too-many-requests", EXPIRED_OOB_CODE: "expired-action-code", INVALID_OOB_CODE: "invalid-action-code", // This can only happen if the SDK sends a bad request. MISSING_OOB_CODE: "internal-error", // Operations that require ID token in request: CREDENTIAL_TOO_OLD_LOGIN_AGAIN: "requires-recent-login", INVALID_ID_TOKEN: "invalid-user-token", TOKEN_EXPIRED: "user-token-expired", USER_NOT_FOUND: "user-token-expired", // Other errors. TOO_MANY_ATTEMPTS_TRY_LATER: "too-many-requests", PASSWORD_DOES_NOT_MEET_REQUIREMENTS: "password-does-not-meet-requirements", // Phone Auth related errors. INVALID_CODE: "invalid-verification-code", INVALID_SESSION_INFO: "invalid-verification-id", INVALID_TEMPORARY_PROOF: "invalid-credential", MISSING_SESSION_INFO: "missing-verification-id", SESSION_EXPIRED: "code-expired", // Other action code errors when additional settings passed. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above. // This is OK as this error will be caught by client side validation. MISSING_ANDROID_PACKAGE_NAME: "missing-android-pkg-name", UNAUTHORIZED_DOMAIN: "unauthorized-continue-uri", // getProjectConfig errors when clientId is passed. INVALID_OAUTH_CLIENT_ID: "invalid-oauth-client-id", // User actions (sign-up or deletion) disabled errors. ADMIN_ONLY_OPERATION: "admin-restricted-operation", // Multi factor related errors. INVALID_MFA_PENDING_CREDENTIAL: "invalid-multi-factor-session", MFA_ENROLLMENT_NOT_FOUND: "multi-factor-info-not-found", MISSING_MFA_ENROLLMENT_ID: "missing-multi-factor-info", MISSING_MFA_PENDING_CREDENTIAL: "missing-multi-factor-session", SECOND_FACTOR_EXISTS: "second-factor-already-in-use", SECOND_FACTOR_LIMIT_EXCEEDED: "maximum-second-factor-count-exceeded", // Blocking functions related errors. BLOCKING_FUNCTION_ERROR_RESPONSE: "internal-error", // Recaptcha related errors. RECAPTCHA_NOT_ENABLED: "recaptcha-not-enabled", MISSING_RECAPTCHA_TOKEN: "missing-recaptcha-token", INVALID_RECAPTCHA_TOKEN: "invalid-recaptcha-token", INVALID_RECAPTCHA_ACTION: "invalid-recaptcha-action", MISSING_CLIENT_TYPE: "missing-client-type", MISSING_RECAPTCHA_VERSION: "missing-recaptcha-version", INVALID_RECAPTCHA_VERSION: "invalid-recaptcha-version", INVALID_REQ_TYPE: "invalid-req-type" /* AuthErrorCode.INVALID_REQ_TYPE */ }; const Fe = [ "/v1/accounts:signInWithCustomToken", "/v1/accounts:signInWithEmailLink", "/v1/accounts:signInWithIdp", "/v1/accounts:signInWithPassword", "/v1/accounts:signInWithPhoneNumber", "/v1/token" /* Endpoint.TOKEN */ ], xe = new S(3e4, 6e4); function le(r, e) { return r.tenantId && !e.tenantId ? { ...e, tenantId: r.tenantId } : e; } async function b(r, e, t, i, n = {}) { return de(r, n, async () => { let s = {}, a = {}; i && (e === "GET" ? a = i : s = { body: JSON.stringify(i) }); const h = ne({ key: r.config.apiKey, ...a }).slice(1), o = await r._getAdditionalHeaders(); o[ "Content-Type" /* HttpHeader.CONTENT_TYPE */ ] = "application/json", r.languageCode && (o[ "X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */ ] = r.languageCode); const u = { method: e, headers: o, ...s }; return Ee() || (u.referrerPolicy = "no-referrer"), r.emulatorConfig && se(r.emulatorConfig.host) && (u.credentials = "include"), he.fetch()(await fe(r, r.config.apiHost, t, h), u); }); } async function de(r, e, t) { r._canInitEmulator = !1; const i = { ...De, ...e }; try { const n = new Ve(r), s = await Promise.race([ t(), n.promise ]); n.clearNetworkTimeout(); const a = await s.json(); if ("needConfirmation" in a) throw N(r, "account-exists-with-different-credential", a); if (s.ok && !("errorMessage" in a)) return a; { const h = s.ok ? a.errorMessage : a.error.message, [o, u] = h.split(" : "); if (o === "FEDERATED_USER_ID_ALREADY_LINKED") throw N(r, "credential-already-in-use", a); if (o === "EMAIL_EXISTS") throw N(r, "email-already-in-use", a); if (o === "USER_DISABLED") throw N(r, "user-disabled", a); const l = i[o] || o.toLowerCase().replace(/[_\s]+/g, "-"); if (u) throw ue(r, l, u); J(r, l); } } catch (n) { if (n instanceof ie) throw n; J(r, "network-request-failed", { message: String(n) }); } } async function fe(r, e, t, i) { const n = `${e}${t}?${i}`, s = r, a = s.config.emulator ? Me(r.config, n) : `${r.config.apiScheme}://${n}`; return Fe.includes(t) && (await s._persistenceManagerAvailable, s._getPersistenceType() === "COOKIE") ? s._getPersistence()._getFinalTarget(a).toString() : a; } class Ve { clearNetworkTimeout() { clearTimeout(this.timer); } constructor(e) { this.auth = e, this.timer = null, this.promise = new Promise((t, i) => { this.timer = setTimeout(() => i(ce( this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */ )), xe.get()); }); } } function N(r, e, t) { const i = { appName: r.name }; t.email && (i.email = t.email), t.phoneNumber && (i.phoneNumber = t.phoneNumber); const n = ce(r, e, i); return n.customData._tokenResponse = t, n; } async function ze(r, e) { return b(r, "POST", "/v1/accounts:delete", e); } async function R(r, e) { return b(r, "POST", "/v1/accounts:lookup", e); } function A(r) { if (r) try { const e = new Date(Number(r)); if (!isNaN(e.getTime())) return e.toUTCString(); } catch { } } async function He(r, e = !1) { const t = k(r), i = await t.getIdToken(e), n = pe(i); c( n && n.exp && n.auth_time && n.iat, t.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ); const s = typeof n.firebase == "object" ? n.firebase : void 0, a = s?.sign_in_provider; return { claims: n, token: i, authTime: A(M(n.auth_time)), issuedAtTime: A(M(n.iat)), expirationTime: A(M(n.exp)), signInProvider: a || null, signInSecondFactor: s?.sign_in_second_factor || null }; } function M(r) { return Number(r) * 1e3; } function pe(r) { const [e, t, i] = r.split("."); if (e === void 0 || t === void 0 || i === void 0) return v("JWT malformed, contained fewer than 3 sections"), null; try { const n = ve(t); return n ? JSON.parse(n) : (v("Failed to decode base64 JWT payload"), null); } catch (n) { return v("Caught error parsing JWT payload as JSON", n?.toString()), null; } } function X(r) { const e = pe(r); return c( e, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), c( typeof e.exp < "u", "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), c( typeof e.iat < "u", "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), Number(e.exp) - Number(e.iat); } async function F(r, e, t = !1) { if (t) return e; try { return await e; } catch (i) { throw i instanceof ie && Ke(i) && r.auth.currentUser === r && await r.auth.signOut(), i; } } function Ke({ code: r }) { return r === "auth/user-disabled" || r === "auth/user-token-expired"; } class We { constructor(e) { this.user = e, this.isRunning = !1, this.timerId = null, this.errorBackoff = 3e4; } _start() { this.isRunning || (this.isRunning = !0, this.schedule()); } _stop() { this.isRunning && (this.isRunning = !1, this.timerId !== null && clearTimeout(this.timerId)); } getInterval(e) { if (e) { const t = this.errorBackoff; return this.errorBackoff = Math.min( this.errorBackoff * 2, 96e4 /* Duration.RETRY_BACKOFF_MAX */ ), t; } else { this.errorBackoff = 3e4; const i = (this.user.stsTokenManager.expirationTime ?? 0) - Date.now() - 3e5; return Math.max(0, i); } } schedule(e = !1) { if (!this.isRunning) return; const t = this.getInterval(e); this.timerId = setTimeout(async () => { await this.iteration(); }, t); } async iteration() { try { await this.user.getIdToken(!0); } catch (e) { e?.code === "auth/network-request-failed" && this.schedule( /* wasError */ !0 ); return; } this.schedule(); } } class x { constructor(e, t) { this.createdAt = e, this.lastLoginAt = t, this._initializeTime(); } _initializeTime() { this.lastSignInTime = A(this.lastLoginAt), this.creationTime = A(this.createdAt); } _copy(e) { this.createdAt = e.createdAt, this.lastLoginAt = e.lastLoginAt, this._initializeTime(); } toJSON() { return { createdAt: this.createdAt, lastLoginAt: this.lastLoginAt }; } } async function U(r) { const e = r.auth, t = await r.getIdToken(), i = await F(r, R(e, { idToken: t })); c( i?.users.length, e, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ); const n = i.users[0]; r._notifyReloadListener(n); const s = n.providerUserInfo?.length ? me(n.providerUserInfo) : [], a = Ge(r.providerData, s), h = r.isAnonymous, o = !(r.email && n.passwordHash) && !a?.length, u = h ? o : !1, l = { uid: n.localId, displayName: n.displayName || null, photoURL: n.photoUrl || null, email: n.email || null, emailVerified: n.emailVerified || !1, phoneNumber: n.phoneNumber || null, tenantId: n.tenantId || null, providerData: a, metadata: new x(n.createdAt, n.lastLoginAt), isAnonymous: u }; Object.assign(r, l); } async function $e(r) { const e = k(r); await U(e), await e.auth._persistUserIfCurrent(e), e.auth._notifyListenersIfCurrent(e); } function Ge(r, e) { return [...r.filter((i) => !e.some((n) => n.providerId === i.providerId)), ...e]; } function me(r) { return r.map(({ providerId: e, ...t }) => ({ providerId: e, uid: t.rawId || "", displayName: t.displayName || null, email: t.email || null, phoneNumber: t.phoneNumber || null, photoURL: t.photoUrl || null })); } async function qe(r, e) { const t = await de(r, {}, async () => { const i = ne({ grant_type: "refresh_token", refresh_token: e }).slice(1), { tokenApiHost: n, apiKey: s } = r.config, a = await fe(r, n, "/v1/token", `key=${s}`), h = await r._getAdditionalHeaders(); h[ "Content-Type" /* HttpHeader.CONTENT_TYPE */ ] = "application/x-www-form-urlencoded"; const o = { method: "POST", headers: h, body: i }; return r.emulatorConfig && se(r.emulatorConfig.host) && (o.credentials = "include"), he.fetch()(a, o); }); return { accessToken: t.access_token, expiresIn: t.expires_in, refreshToken: t.refresh_token }; } async function Je(r, e) { return b(r, "POST", "/v2/accounts:revokeToken", le(r, e)); } class I { constructor() { this.refreshToken = null, this.accessToken = null, this.expirationTime = null; } get isExpired() { return !this.expirationTime || Date.now() > this.expirationTime - 3e4; } updateFromServerResponse(e) { c( e.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), c( typeof e.idToken < "u", "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), c( typeof e.refreshToken < "u", "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ); const t = "expiresIn" in e && typeof e.expiresIn < "u" ? Number(e.expiresIn) : X(e.idToken); this.updateTokensAndExpiration(e.idToken, e.refreshToken, t); } updateFromIdToken(e) { c( e.length !== 0, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ); const t = X(e); this.updateTokensAndExpiration(e, null, t); } async getToken(e, t = !1) { return !t && this.accessToken && !this.isExpired ? this.accessToken : (c( this.refreshToken, e, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */ ), this.refreshToken ? (await this.refresh(e, this.refreshToken), this.accessToken) : null); } clearRefreshToken() { this.refreshToken = null; } async refresh(e, t) { const { accessToken: i, refreshToken: n, expiresIn: s } = await qe(e, t); this.updateTokensAndExpiration(i, n, Number(s)); } updateTokensAndExpiration(e, t, i) { this.refreshToken = t || null, this.accessToken = e || null, this.expirationTime = Date.now() + i * 1e3; } static fromJSON(e, t) { const { refreshToken: i, accessToken: n, expirationTime: s } = t, a = new I(); return i && (c(typeof i == "string", "internal-error", { appName: e }), a.refreshToken = i), n && (c(typeof n == "string", "internal-error", { appName: e }), a.accessToken = n), s && (c(typeof s == "number", "internal-error", { appName: e }), a.expirationTime = s), a; } toJSON() { return { refreshToken: this.refreshToken, accessToken: this.accessToken, expirationTime: this.expirationTime }; } _assign(e) { this.accessToken = e.accessToken, this.refreshToken = e.refreshToken, this.expirationTime = e.expirationTime; } _clone() { return Object.assign(new I(), this.toJSON()); } _performRefresh() { return w("not implemented"); } } function p(r, e) { c(typeof r == "string" || typeof r > "u", "internal-error", { appName: e }); } class d { constructor({ uid: e, auth: t, stsTokenManager: i, ...n }) { this.providerId = "firebase", this.proactiveRefresh = new We(this), this.reloadUserInfo = null, this.reloadListener = null, this.uid = e, this.auth = t, this.stsTokenManager = i, this.accessToken = i.accessToken, this.displayName = n.displayName || null, this.email = n.email || null, this.emailVerified = n.emailVerified || !1, this.phoneNumber = n.phoneNumber || null, this.photoURL = n.photoURL || null, this.isAnonymous = n.isAnonymous || !1, this.tenantId = n.tenantId || null, this.providerData = n.providerData ? [...n.providerData] : [], this.metadata = new x(n.createdAt || void 0, n.lastLoginAt || void 0); } async getIdToken(e) { const t = await F(this, this.stsTokenManager.getToken(this.auth, e)); return c( t, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), this.accessToken !== t && (this.accessToken = t, await this.auth._persistUserIfCurrent(this), this.auth._notifyListenersIfCurrent(this)), t; } getIdTokenResult(e) { return He(this, e); } reload() { return $e(this); } _assign(e) { this !== e && (c( this.uid === e.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), this.displayName = e.displayName, this.photoURL = e.photoURL, this.email = e.email, this.emailVerified = e.emailVerified, this.phoneNumber = e.phoneNumber, this.isAnonymous = e.isAnonymous, this.tenantId = e.tenantId, this.providerData = e.providerData.map((t) => ({ ...t })), this.metadata._copy(e.metadata), this.stsTokenManager._assign(e.stsTokenManager)); } _clone(e) { const t = new d({ ...this, auth: e, stsTokenManager: this.stsTokenManager._clone() }); return t.metadata._copy(this.metadata), t; } _onReload(e) { c( !this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), this.reloadListener = e, this.reloadUserInfo && (this._notifyReloadListener(this.reloadUserInfo), this.reloadUserInfo = null); } _notifyReloadListener(e) { this.reloadListener ? this.reloadListener(e) : this.reloadUserInfo = e; } _startProactiveRefresh() { this.proactiveRefresh._start(); } _stopProactiveRefresh() { this.proactiveRefresh._stop(); } async _updateTokensIfNecessary(e, t = !1) { let i = !1; e.idToken && e.idToken !== this.stsTokenManager.accessToken && (this.stsTokenManager.updateFromServerResponse(e), i = !0), t && await U(this), await this.auth._persistUserIfCurrent(this), i && this.auth._notifyListenersIfCurrent(this); } async delete() { if (_(this.auth.app)) return Promise.reject(E(this.auth)); const e = await this.getIdToken(); return await F(this, ze(this.auth, { idToken: e })), this.stsTokenManager.clearRefreshToken(), this.auth.signOut(); } toJSON() { return { uid: this.uid, email: this.email || void 0, emailVerified: this.emailVerified, displayName: this.displayName || void 0, isAnonymous: this.isAnonymous, photoURL: this.photoURL || void 0, phoneNumber: this.phoneNumber || void 0, tenantId: this.tenantId || void 0, providerData: this.providerData.map((e) => ({ ...e })), stsTokenManager: this.stsTokenManager.toJSON(), // Redirect event ID must be maintained in case there is a pending // redirect event. _redirectEventId: this._redirectEventId, ...this.metadata.toJSON(), // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing): apiKey: this.auth.config.apiKey, appName: this.auth.name // Missing authDomain will be tolerated by the legacy SDK. // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it). }; } get refreshToken() { return this.stsTokenManager.refreshToken || ""; } static _fromJSON(e, t) { const i = t.displayName ?? void 0, n = t.email ?? void 0, s = t.phoneNumber ?? void 0, a = t.photoURL ?? void 0, h = t.tenantId ?? void 0, o = t._redirectEventId ?? void 0, u = t.createdAt ?? void 0, l = t.lastLoginAt ?? void 0, { uid: m, emailVerified: T, isAnonymous: K, providerData: L, stsTokenManager: W } = t; c( m && W, e, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ); const Ie = I.fromJSON(this.name, W); c( typeof m == "string", e, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), p(i, e.name), p(n, e.name), c( typeof T == "boolean", e, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), c( typeof K == "boolean", e, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), p(s, e.name), p(a, e.name), p(h, e.name), p(o, e.name), p(u, e.name), p(l, e.name); const O = new d({ uid: m, auth: e, email: n, emailVerified: T, displayName: i, isAnonymous: K, photoURL: a, phoneNumber: s, tenantId: h, stsTokenManager: Ie, createdAt: u, lastLoginAt: l }); return L && Array.isArray(L) && (O.providerData = L.map((ye) => ({ ...ye }))), o && (O._redirectEventId = o), O; } /** * Initialize a User from an idToken server response * @param auth * @param idTokenResponse */ static async _fromIdTokenResponse(e, t, i = !1) { const n = new I(); n.updateFromServerResponse(t); const s = new d({ uid: t.localId, auth: e, stsTokenManager: n, isAnonymous: i }); return await U(s), s; } /** * Initialize a User from an idToken server response * @param auth * @param idTokenResponse */ static async _fromGetAccountInfoResponse(e, t, i) { const n = t.users[0]; c( n.localId !== void 0, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ); const s = n.providerUserInfo !== void 0 ? me(n.providerUserInfo) : [], a = !(n.email && n.passwordHash) && !s?.length, h = new I(); h.updateFromIdToken(i); const o = new d({ uid: n.localId, auth: e, stsTokenManager: h, isAnonymous: a }), u = { uid: n.localId, displayName: n.displayName || null, photoURL: n.photoUrl || null, email: n.email || null, emailVerified: n.emailVerified || !1, phoneNumber: n.phoneNumber || null, tenantId: n.tenantId || null, providerData: s, metadata: new x(n.createdAt, n.lastLoginAt), isAnonymous: !(n.email && n.passwordHash) && !s?.length }; return Object.assign(o, u), o; } } const j = /* @__PURE__ */ new Map(); function g(r) { C(r instanceof Function, "Expected a class definition"); let e = j.get(r); return e ? (C(e instanceof r, "Instance stored in cache mismatched with class"), e) : (e = new r(), j.set(r, e), e); } class ge { constructor() { this.type = "NONE", this.storage = {}; } async _isAvailable() { return !0; } async _set(e, t) { this.storage[e] = t; } async _get(e) { const t = this.storage[e]; return t === void 0 ? null : t; } async _remove(e) { delete this.storage[e]; } _addListener(e, t) { } _removeListener(e, t) { } } ge.type = "NONE"; const Y = ge; function D(r, e, t) { return `firebase:${r}:${e}:${t}`; } class y { constructor(e, t, i) { this.persistence = e, this.auth = t, this.userKey = i; const { config: n, name: s } = this.auth; this.fullUserKey = D(this.userKey, n.apiKey, s), this.fullPersistenceKey = D("persistence", n.apiKey, s), this.boundEventHandler = t._onStorageEvent.bind(t), this.persistence._addListener(this.fullUserKey, this.boundEventHandler); } setCurrentUser(e) { return this.persistence._set(this.fullUserKey, e.toJSON()); } async getCurrentUser() { const e = await this.persistence._get(this.fullUserKey); if (!e) return null; if (typeof e == "string") { const t = await R(this.auth, { idToken: e }).catch(() => { }); return t ? d._fromGetAccountInfoResponse(this.auth, t, e) : null; } return d._fromJSON(this.auth, e); } removeCurrentUser() { return this.persistence._remove(this.fullUserKey); } savePersistenceForRedirect() { return this.persistence._set(this.fullPersistenceKey, this.persistence.type); } async setPersistence(e) { if (this.persistence === e) return; const t = await this.getCurrentUser(); if (await this.removeCurrentUser(), this.persistence = e, t) return this.setCurrentUser(t); } delete() { this.persistence._removeListener(this.fullUserKey, this.boundEventHandler); } static async create(e, t, i = "authUser") { if (!t.length) return new y(g(Y), e, i); const n = (await Promise.all(t.map(async (u) => { if (await u._isAvailable()) return u; }))).filter((u) => u); let s = n[0] || g(Y); const a = D(i, e.config.apiKey, e.name); let h = null; for (const u of t) try { const l = await u._get(a); if (l) { let m; if (typeof l == "string") { const T = await R(e, { idToken: l }).catch(() => { }); if (!T) break; m = await d._fromGetAccountInfoResponse(e, T, l); } else m = d._fromJSON(e, l); u !== s && (h = m), s = u; break; } } catch { } const o = n.filter((u) => u._shouldAllowMigration); return !s._shouldAllowMigration || !o.length ? new y(s, e, i) : (s = o[0], h && await s._set(a, h.toJSON()), await Promise.all(t.map(async (u) => { if (u !== s) try { await u._remove(a); } catch { } })), new y(s, e, i)); } } function Q(r) { const e = r.toLowerCase(); if (e.includes("opera/") || e.includes("opr/") || e.includes("opios/")) return "Opera"; if (Ye(e)) return "IEMobile"; if (e.includes("msie") || e.includes("trident/")) return "IE"; if (e.includes("edge/")) return "Edge"; if (Be(e)) return "Firefox"; if (e.includes("silk/")) return "Silk"; if (Ze(e)) return "Blackberry"; if (et(e)) return "Webos"; if (Xe(e)) return "Safari"; if ((e.includes("chrome/") || je(e)) && !e.includes("edge/")) return "Chrome"; if (Qe(e)) return "Android"; { const t = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/, i = r.match(t); if (i?.length === 2) return i[1]; } return "Other"; } function Be(r = f()) { return /firefox\//i.test(r); } function Xe(r = f()) { const e = r.toLowerCase(); return e.includes("safari/") && !e.includes("chrome/") && !e.includes("crios/") && !e.includes("android"); } function je(r = f()) { return /crios\//i.test(r); } function Ye(r = f()) { return /iemobile/i.test(r); } function Qe(r = f()) { return /android/i.test(r); } function Ze(r = f()) { return /blackberry/i.test(r); } function et(r = f()) { return /webos/i.test(r); } function _e(r, e = []) { let t; switch (r) { case "Browser": t = Q(f()); break; case "Worker": t = `${Q(f())}-${r}`; break; default: t = r; } const i = e.length ? e.join(",") : "FirebaseCore-web"; return `${t}/JsCore/${V}/${i}`; } class tt { constructor(e) { this.auth = e, this.queue = []; } pushCallback(e, t) { const i = (s) => new Promise((a, h) => { try { const o = e(s); a(o); } catch (o) { h(o); } }); i.onAbort = t, this.queue.push(i); const n = this.queue.length - 1; return () => { this.queue[n] = () => Promise.resolve(); }; } async runMiddleware(e) { if (this.auth.currentUser === e) return; const t = []; try { for (const i of this.queue) await i(e), i.onAbort && t.push(i.onAbort); } catch (i) { t.reverse(); for (const n of t) try { n(); } catch { } throw this.auth._errorFactory.create("login-blocked", { originalMessage: i?.message }); } } } async function rt(r, e = {}) { return b(r, "GET", "/v2/passwordPolicy", le(r, e)); } const it = 6; class nt { constructor(e) { const t = e.customStrengthOptions; this.customStrengthOptions = {}, this.customStrengthOptions.minPasswordLength = t.minPasswordLength ?? it, t.maxPasswordLength && (this.customStrengthOptions.maxPasswordLength = t.maxPasswordLength), t.containsLowercaseCharacter !== void 0 && (this.customStrengthOptions.containsLowercaseLetter = t.containsLowercaseCharacter), t.containsUppercaseCharacter !== void 0 && (this.customStrengthOptions.containsUppercaseLetter = t.containsUppercaseCharacter), t.containsNumericCharacter !== void 0 && (this.customStrengthOptions.containsNumericCharacter = t.containsNumericCharacter), t.containsNonAlphanumericCharacter !== void 0 && (this.customStrengthOptions.containsNonAlphanumericCharacter = t.containsNonAlphanumericCharacter), this.enforcementState = e.enforcementState, this.enforcementState === "ENFORCEMENT_STATE_UNSPECIFIED" && (this.enforcementState = "OFF"), this.allowedNonAlphanumericCharacters = e.allowedNonAlphanumericCharacters?.join("") ?? "", this.forceUpgradeOnSignin = e.forceUpgradeOnSignin ?? !1, this.schemaVersion = e.schemaVersion; } validatePassword(e) { const t = { isValid: !0, passwordPolicy: this }; return this.validatePasswordLengthOptions(e, t), this.validatePasswordCharacterOptions(e, t), t.isValid && (t.isValid = t.meetsMinPasswordLength ?? !0), t.isValid && (t.isValid = t.meetsMaxPasswordLength ?? !0), t.isValid && (t.isValid = t.containsLowercaseLetter ?? !0), t.isValid && (t.isValid = t.containsUppercaseLetter ?? !0), t.isValid && (t.isValid = t.containsNumericCharacter ?? !0), t.isValid && (t.isValid = t.containsNonAlphanumericCharacter ?? !0), t; } /** * Validates that the password meets the length options for the policy. * * @param password Password to validate. * @param status Validation status. */ validatePasswordLengthOptions(e, t) { const i = this.customStrengthOptions.minPasswordLength, n = this.customStrengthOptions.maxPasswordLength; i && (t.meetsMinPasswordLength = e.length >= i), n && (t.meetsMaxPasswordLength = e.length <= n); } /** * Validates that the password meets the character options for the policy. * * @param password Password to validate. * @param status Validation status. */ validatePasswordCharacterOptions(e, t) { this.updatePasswordCharacterOptionsStatuses( t, /* containsLowercaseCharacter= */ !1, /* containsUppercaseCharacter= */ !1, /* containsNumericCharacter= */ !1, /* containsNonAlphanumericCharacter= */ !1 ); let i; for (let n = 0; n < e.length; n++) i = e.charAt(n), this.updatePasswordCharacterOptionsStatuses( t, /* containsLowercaseCharacter= */ i >= "a" && i <= "z", /* containsUppercaseCharacter= */ i >= "A" && i <= "Z", /* containsNumericCharacter= */ i >= "0" && i <= "9", /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(i) ); } /** * Updates the running validation status with the statuses for the character options. * Expected to be called each time a character is processed to update each option status * based on the current character. * * @param status Validation status. * @param containsLowercaseCharacter Whether the character is a lowercase letter. * @param containsUppercaseCharacter Whether the character is an uppercase letter. * @param containsNumericCharacter Whether the character is a numeric character. * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character. */ updatePasswordCharacterOptionsStatuses(e, t, i, n, s) { this.customStrengthOptions.containsLowercaseLetter && (e.containsLowercaseLetter || (e.containsLowercaseLetter = t)), this.customStrengthOptions.containsUppercaseLetter && (e.containsUppercaseLetter || (e.containsUppercaseLetter = i)), this.customStrengthOptions.containsNumericCharacter && (e.containsNumericCharacter || (e.containsNumericCharacter = n)), this.customStrengthOptions.containsNonAlphanumericCharacter && (e.containsNonAlphanumericCharacter || (e.containsNonAlphanumericCharacter = s)); } } class st { constructor(e, t, i, n) { this.app = e, this.heartbeatServiceProvider = t, this.appCheckServiceProvider = i, this.config = n, this.currentUser = null, this.emulatorConfig = null, this.operations = Promise.resolve(), this.authStateSubscription = new Z(this), this.idTokenSubscription = new Z(this), this.beforeStateQueue = new tt(this), this.redirectUser = null, this.isProactiveRefreshEnabled = !1, this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1, this._canInitEmulator = !0, this._isInitialized = !1, this._deleted = !1, this._initializationPromise = null, this._popupRedirectResolver = null, this._errorFactory = oe, this._agentRecaptchaConfig = null, this._tenantRecaptchaConfigs = {}, this._projectPasswordPolicy = null, this._tenantPasswordPolicies = {}, this._resolvePersistenceManagerAvailable = void 0, this.lastNotifiedUid = void 0, this.languageCode = null, this.tenantId = null, this.settings = { appVerificationDisabledForTesting: !1 }, this.frameworks = [], this.name = e.name, this.clientVersion = n.sdkClientVersion, this._persistenceManagerAvailable = new Promise((s) => this._resolvePersistenceManagerAvailable = s); } _initializeWithPersistence(e, t) { return t && (this._popupRedirectResolver = g(t)), this._initializationPromise = this.queue(async () => { if (!this._deleted && (this.persistenceManager = await y.create(this, e), this._resolvePersistenceManagerAvailable?.(), !this._deleted)) { if (this._popupRedirectResolver?._shouldInitProactively) try { await this._popupRedirectResolver._initialize(this); } catch { } await this.initializeCurrentUser(t), this.lastNotifiedUid = this.currentUser?.uid || null, !this._deleted && (this._isInitialized = !0); } }), this._initializationPromise; } /** * If the persistence is changed in another window, the user manager will let us know */ async _onStorageEvent() { if (this._deleted) return; const e = await this.assertedPersistence.getCurrentUser(); if (!(!this.currentUser && !e)) { if (this.currentUser && e && this.currentUser.uid === e.uid) { this._currentUser._assign(e), await this.currentUser.getIdToken(); return; } await this._updateCurrentUser( e, /* skipBeforeStateCallbacks */ !0 ); } } async initializeCurrentUserFromIdToken(e) { try { const t = await R(this, { idToken: e }), i = await d._fromGetAccountInfoResponse(this, t, e); await this.directlySetCurrentUser(i); } catch (t) { console.warn("FirebaseServerApp could not login user with provided authIdToken: ", t), await this.directlySetCurrentUser(null); } } async initializeCurrentUser(e) { if (_(this.app)) { const s = this.app.settings.authIdToken; return s ? new Promise((a) => { setTimeout(() => this.initializeCurrentUserFromIdToken(s).then(a, a)); }) : this.directlySetCurrentUser(null); } const t = await this.assertedPersistence.getCurrentUser(); let i = t, n = !1; if (e && this.config.authDomain) { await this.getOrInitRedirectPersistenceManager(); const s = this.redirectUser?._redirectEventId, a = i?._redirectEventId, h = await this.tryRedirectSignIn(e); (!s || s === a) && h?.user && (i = h.user, n = !0); } if (!i) return this.directlySetCurrentUser(null); if (!i._redirectEventId) { if (n) try { await this.beforeStateQueue.runMiddleware(i); } catch (s) { i = t, this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(s)); } return i ? this.reloadAndSetCurrentUserOrClear(i) : this.directlySetCurrentUser(null); } return c( this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */ ), await this.getOrInitRedirectPersistenceManager(), this.redirectUser && this.redirectUser._redirectEventId === i._redirectEventId ? this.directlySetCurrentUser(i) : this.reloadAndSetCurrentUserOrClear(i); } async tryRedirectSignIn(e) { let t = null; try { t = await this._popupRedirectResolver._completeRedirectFn(this, e, !0); } catch { await this._setRedirectUser(null); } return t; } async reloadAndSetCurrentUserOrClear(e) { try { await U(e); } catch (t) { if (t?.code !== "auth/network-request-failed") return this.directlySetCurrentUser(null); } return this.directlySetCurrentUser(e); } useDeviceLanguage() { this.languageCode = Oe(); } async _delete() { this._deleted = !0; } async updateCurrentUser(e) { if (_(this.app)) return Promise.reject(E(this)); const t = e ? k(e) : null; return t && c( t.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */ ), this._updateCurrentUser(t && t._clone(this)); } async _updateCurrentUser(e, t = !1) { if (!this._deleted) return e && c( this.tenantId === e.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */ ), t || await this.beforeStateQueue.runMiddleware(e), this.queue(async () => { await this.directlySetCurrentUser(e), this.notifyAuthListeners(); }); } async signOut() { return _(this.app) ? Promise.reject(E(this)) : (await this.beforeStateQueue.runMiddleware(null), (this.redirectPersistenceManager || this._popupRedirectResolver) && await this._setRedirectUser(null), this._updateCurrentUser( null, /* skipBeforeStateCallbacks */ !0 )); } setPersistence(e) { return _(this.app) ? Promise.reject(E(this)) : this.queue(async () => { await this.assertedPersistence.setPersistence(g(e)); }); } _getRecaptchaConfig() { return this.tenantId == null ? this._agentRecaptchaConfig : this._tenantRecaptchaConfigs[this.tenantId]; } async validatePassword(e) { this._getPasswordPolicyInternal() || await this._updatePasswordPolicy(); const t = this._getPasswordPolicyInternal(); return t.schemaVersion !== this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION ? Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version", {})) : t.validatePassword(e); } _getPasswordPolicyInternal() { return this.tenantId === null ? this._projectPasswordPolicy : this._tenantPasswordPolicies[this.tenantId]; } async _updatePasswordPolicy() { const e = await rt(this), t = new nt(e); this.tenantId === null ? this._projectPasswordPolicy = t : this._tenantPasswordPolicies[this.tenantId] = t; } _getPersistenceType() { return this.assertedPersistence.persistence.type; } _getPersistence() { return this.assertedPersistence.persistence; } _updateErrorMap(e) { this._errorFactory = new z("auth", "Firebase", e()); } onAuthStateChanged(e, t, i) { return this.registerStateListener(this.authStateSubscription, e, t, i); } beforeAuthStateChanged(e, t) { return this.beforeStateQueue.pushCallback(e, t); } onIdTokenChanged(e, t, i) { return this.registerStateListener(this.idTokenSubscription, e, t, i); } authStateReady() { return new Promise((e, t) => { if (this.currentUser) e(); else { const i = this.onAuthStateChanged(() => { i(), e(); }, t); } }); } /** * Revokes the given access token. Currently only supports Apple OAuth access tokens. */ async revokeAccessToken(e) { if (this.currentUser) { const t = await this.currentUser.getIdToken(), i = { providerId: "apple.com", tokenType: "ACCESS_TOKEN", token: e, idToken: t }; this.tenantId != null && (i.tenantId = this.tenantId), await Je(this, i); } } toJSON() { return { apiKey: this.config.apiKey, authDomain: this.config.authDomain, appName: this.name, currentUser: this._currentUser?.toJSON() }; } async _setRedirectUser(e, t) { const i = await this.getOrInitRedirectPersistenceManager(t); return e === null ? i.removeCurrentUser() : i.setCurrentUser(e); } async getOrInitRedirectPersistenceManager(e) { if (!this.redirectPersistenceManager) { const t = e && g(e) || this._popupRedirectResolver; c( t, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */ ), this.redirectPersistenceManager = await y.create( this, [g(t._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */ ), this.redirectUser = await this.redirectPersistenceManager.getCurrentUser(); } return this.redirectPersistenceManager; } async _redirectUserForId(e) { return this._isInitialized && await this.queue(async () => { }), this._currentUser?._redirectEventId === e ? this._currentUser : this.redirectUser?._redirectEventId === e ? this.redirectUser : null; } async _persistUserIfCurrent(e) { if (e === this.currentUser) return this.queue(async () => this.directlySetCurrentUser(e)); } /** Notifies listeners only if the user is current */ _notifyListenersIfCurrent(e) { e === this.currentUser && this.notifyAuthListeners(); } _key() { return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`; } _startProactiveRefresh() { this.isProactiveRefreshEnabled = !0, this.currentUser && this._currentUser._startProactiveRefresh(); } _stopProactiveRefresh() { this.isProactiveRefreshEnabled = !1, this.currentUser && this._currentUser._stopProactiveRefresh(); } /** Returns the current user cast as the internal type */ get _currentUser() { return this.currentUser; } notifyAuthListeners() { if (!this._isInitialized) return; this.idTokenSubscription.next(this.currentUser); const e = this.currentUser?.uid ?? null; this.lastNotifiedUid !== e && (this.lastNotifiedUid = e, this.authStateSubscription.next(this.currentUser)); } registerStateListener(e, t, i, n) { if (this._deleted) return () => { }; const s = typeof t == "function" ? t : t.next.bind(t); let a = !1; const h = this._isInitialized ? Promise.resolve() : this._initializationPromise; if (c( h, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), h.then(() => { a || s(this.currentUser); }), typeof t == "function") { const o = e.addObserver(t, i, n); return () => { a = !0, o(); }; } else { const o = e.addObserver(t); return () => { a = !0, o(); }; } } /** * Unprotected (from race conditions) method to set the current user. This * should only be called from within a queued callback. This is necessary * because the queue shouldn't rely on another queued callback. */ async directlySetCurrentUser(e) { this.currentUser && this.currentUser !== e && this._currentUser._stopProactiveRefresh(), e && this.isProactiveRefreshEnabled && e._startProactiveRefresh(), this.currentUser = e, e ? await this.assertedPersistence.setCurrentUser(e) : await this.assertedPersistence.removeCurrentUser(); } queue(e) { return this.operations = this.operations.then(e, e), this.operations; } get assertedPersistence() { return c( this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), this.persistenceManager; } _logFramework(e) { !e || this.frameworks.includes(e) || (this.frameworks.push(e), this.frameworks.sort(), this.clientVersion = _e(this.config.clientPlatform, this._getFrameworks())); } _getFrameworks() { return this.frameworks; } async _getAdditionalHeaders() { const e = { "X-Client-Version": this.clientVersion }; this.app.options.appId && (e[ "X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */ ] = this.app.options.appId); const t = await this.heartbeatServiceProvider.getImmediate({ optional: !0 })?.getHeartbeatsHeader(); t && (e[ "X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */ ] = t); const i = await this._getAppCheckToken(); return i && (e[ "X-Firebase-AppCheck" /* HttpHeader.X_FIREBASE_APP_CHECK */ ] = i), e; } async _getAppCheckToken() { if (_(this.app) && this.app.settings.appCheckToken) return this.app.settings.appCheckToken; const e = await this.appCheckServiceProvider.getImmediate({ optional: !0 })?.getToken(); return e?.error && Ue(`Error while retrieving App Check token: ${e.error}`), e?.token; } } function at(r) { return k(r); } class Z { constructor(e) { this.auth = e, this.observer = null, this.addObserver = Ne((t) => this.observer = t); } get next() { return c( this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */ ), this.observer.next.bind(this.observer); } } function ot(r, e) { const t = e?.persistence || [], i = (Array.isArray(t) ? t : [t]).map(g); e?.errorMap && r._updateErrorMap(e.errorMap), r._initializeWithPersistence(i, e?.popupRedirectResolver); } function ct(r, e, t, i) { return k(r).onAuthStateChanged(e, t, i); } new S(3e4, 6e4); new S(2e3, 1e4); new S(3e4, 6e4); new S(5e3, 15e3); var ee = "@firebase/auth", te = "1.12.1"; class ut { constructor(e) { this.auth = e, this.internalListeners = /* @__PURE__ */ new Map(); } getUid() { return this.assertAuthConfigured(), this.auth.currentUser?.uid || null; } async getToken(e) { return this.assertAuthConfigured(), await this.auth._initializationPromise, this.auth.currentUser ? { accessToken: await this.auth.currentUser.getIdToken(e) } : null; } addAuthTokenListener(e) { if (this.assertAuthConfigured(), this.internalListeners.has(e)) return; const t = this.auth.onIdTokenChanged((i) => { e(i?.stsTokenManager.accessToken || null); }); this.internalListeners.set(e, t), this.updateProactiveRefresh(); } removeAuthTokenListener(e) { this.assertAuthConfigured(); const t