@edgespark/web 0.0.1-beta.4 → 0.0.1-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,42 +1,42 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const de=require("better-auth/client");class k extends Error{constructor(e,t){super(t),this.name="EdgeSparkError",this.code=e}}class d extends k{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class ee extends k{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class m extends k{constructor(e,t){super((t==null?void 0:t.code)??"AUTH_ERROR",e),this.name="EdgeSparkAuthError",this.cause=t==null?void 0:t.cause,this.status=t==null?void 0:t.status}}function re(){if(typeof window>"u"||typeof document>"u")throw new ee("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function x(){return re(),window.location.origin}function ce(s){return s instanceof URL?s:typeof s=="string"?new URL(s,window.location.href):new URL(s.url,window.location.href)}function ue(s){if(s.origin!==x())throw new d(`Cross-origin requests are not supported by this SDK. Received ${s.origin}, expected ${x()}.`)}function he(){return{async fetch(s,e){const t=ce(s);return ue(t),fetch(s,{...e,credentials:"include"})}}}const oe="/api/_es/auth";function ae(s){return de.createAuthClient({baseURL:x(),basePath:oe,...s!=null&&s.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function v(s){var e,t;return(t=(e=s.$store)==null?void 0:e.atoms)==null?void 0:t.session}function O(s){if(s instanceof m)return s;const e=s;return new m((e==null?void 0:e.message)||"Failed to load the current session.",{code:(e==null?void 0:e.code)??"SESSION_LOOKUP_FAILED",cause:s,status:e==null?void 0:e.status})}async function me(s){var e;await((e=v(s))==null?void 0:e.get().refetch())}function we(){const s=ae(),e=2,t=500;let i=null,r=!1;const o=()=>{var c;return r?Promise.resolve(((c=v(s))==null?void 0:c.get().data)??null):(i||(i=(async()=>{var P,L,y,_;let a=!1,l=null;try{for(let p=0;p<=e;p++){const f=await s.getSession(),b=((P=v(s))==null?void 0:P.get().data)??null;if((L=f.data)!=null&&L.session&&((y=f.data)!=null&&y.user))return r=!0,f.data;if(b!=null&&b.session&&(b!=null&&b.user))return r=!0,b;if(f.error?l=f.error:a=!0,!f.error&&p<e){await new Promise(M=>setTimeout(M,t));continue}p<e&&await new Promise(M=>setTimeout(M,t))}if(!a)throw i=null,new m("Failed to load the current session.",{code:"SESSION_LOOKUP_FAILED",cause:l});const h=((_=v(s))==null?void 0:_.get().data)??null;return r=!0,h}catch(h){throw i=null,O(h)}})()),i)};o().catch(()=>{});const u=async()=>{var c,a;try{const l=await s.getSession();if((c=l.data)!=null&&c.session&&((a=l.data)!=null&&a.user))return l.data;throw l.error?O(l.error):new m("No authenticated session is available.",{code:"UNAUTHENTICATED"})}catch(l){throw O(l)}},w=c=>{let a=!1,l=!1,P;const L=h=>{h!==P&&(P=h,c(h))};o().then(h=>{a||(l=!0,L(h))}).catch(()=>{a||(l=!0)});const y=v(s);if(!y)return()=>{a=!0};const _=y.subscribe(h=>{if(a||!l||h.error&&!h.data)return;const p=h.data??null;L(p)});return()=>{a=!0,_()}},S=async(...c)=>{var l;const a=await s.signOut(...c);if(a&&typeof a=="object"&&"error"in a&&a.error)return a;try{await((l=v(s))==null?void 0:l.get().refetch())}catch{}return a};return new Proxy(s,{get(c,a,l){return a==="requireSession"?u:a==="onSessionChange"?w:a==="signOut"?S:Reflect.get(c,a,l)}})}function be(){return ae({disableDefaultRedirectPlugin:!0})}function V(s){const e=(()=>{if(s instanceof URL)return s;const t=s.trim();if(!t)throw new d("redirectTo must not be an empty string.");try{return new URL(t,window.location.href)}catch{throw new d(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(s)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new d(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function pe(s,e){return e?{common:{...s.common,...e.common},signIn:{...s.signIn,...e.signIn},signUp:{...s.signUp,...e.signUp},verifyEmail:{...s.verifyEmail,...e.verifyEmail},forgotPassword:{...s.forgotPassword,...e.forgotPassword},resetPassword:{...s.resetPassword,...e.resetPassword},oauth:{...s.oauth,...e.oauth},errors:{...s.errors,...e.errors}}:s}const E={common:{loading:"Loading sign-in…",redirecting:"Redirecting…",backToSignIn:"Back to sign in"},signIn:{title:"Welcome back",subtitle:"Sign in to continue",emailLabel:"Email",passwordLabel:"Password",submitButton:"Sign in",forgotPassword:"Forgot password?",switchToSignUp:"Create an account",signUpPrompt:"Don’t have an account?"},signUp:{title:"Create your account",subtitle:"Start with your name, email, and password",nameLabel:"Name",emailLabel:"Email",passwordLabel:"Password",confirmPasswordLabel:"Confirm password",submitButton:"Create account",switchToSignIn:"Sign in",signInPrompt:"Already have an account?"},verifyEmail:{title:"Verify your email",subtitle:"Finish account setup from the verification email we sent.",sentToLabel:"Sent to",resendButton:"Resend verification email",resendCountdown:"Resend in {seconds}s",changeEmailButton:"Use a different email"},forgotPassword:{title:"Reset your password",subtitle:"Enter your email and we will send a reset code.",emailLabel:"Email",submitButton:"Send reset code"},resetPassword:{title:"Set a new password",subtitle:"Use the code from your email to finish resetting your password.",codeLabel:"Verification code",newPasswordLabel:"New password",confirmPasswordLabel:"Confirm password",submitButton:"Update password",resendCodeButton:"Resend code",resendCountdown:"Resend in {seconds}s"},oauth:{dividerText:"or",continueWith:"Continue with"},errors:{invalidEmail:"Enter a valid email address.",requiredField:"This field is required.",passwordTooShort:"Password must be at least {min} characters.",passwordMismatch:"Passwords do not match.",invalidCode:"Enter the 6-digit verification code.",generic:"Something went wrong. Please try again."}},A={common:{loading:"加载中…",redirecting:"跳转中…",backToSignIn:"返回登录"},signIn:{title:"欢迎回来",subtitle:"登录以继续",emailLabel:"邮箱",passwordLabel:"密码",submitButton:"登录",forgotPassword:"忘记密码?",switchToSignUp:"立即注册",signUpPrompt:"没有账号?"},signUp:{title:"创建账号",subtitle:"填写姓名、邮箱和密码开始使用",nameLabel:"姓名",emailLabel:"邮箱",passwordLabel:"密码",confirmPasswordLabel:"确认密码",submitButton:"注册",switchToSignIn:"去登录",signInPrompt:"已有账号?"},verifyEmail:{title:"验证邮箱",subtitle:"请查收邮件并点击验证链接",sentToLabel:"已发送至",resendButton:"重新发送验证邮件",resendCountdown:"{seconds}秒后可重发",changeEmailButton:"更换邮箱"},forgotPassword:{title:"重置密码",subtitle:"输入邮箱以接收重置验证码",emailLabel:"邮箱",submitButton:"发送重置码"},resetPassword:{title:"设置新密码",subtitle:"使用邮件中的验证码完成密码重置",codeLabel:"验证码",newPasswordLabel:"新密码",confirmPasswordLabel:"确认密码",submitButton:"更新密码",resendCodeButton:"重新发送",resendCountdown:"{seconds}秒后可重发"},oauth:{dividerText:"或",continueWith:"使用"},errors:{invalidEmail:"请输入有效的邮箱地址",requiredField:"此项为必填",passwordTooShort:"密码至少需要 {min} 个字符",passwordMismatch:"两次密码输入不一致",invalidCode:"请输入 6 位验证码",generic:"出现错误,请稍后重试"}},W={common:{loading:"サインインを読み込み中…",redirecting:"リダイレクト中…",backToSignIn:"サインインに戻る"},signIn:{title:"おかえりなさい",subtitle:"サインインして続行",emailLabel:"メールアドレス",passwordLabel:"パスワード",submitButton:"サインイン",forgotPassword:"パスワードをお忘れですか?",switchToSignUp:"アカウントを作成",signUpPrompt:"アカウントをお持ちでない方"},signUp:{title:"アカウントを作成",subtitle:"名前、メールアドレス、パスワードを入力してください",nameLabel:"名前",emailLabel:"メールアドレス",passwordLabel:"パスワード",confirmPasswordLabel:"パスワード(確認)",submitButton:"アカウント作成",switchToSignIn:"サインイン",signInPrompt:"既にアカウントをお持ちですか?"},verifyEmail:{title:"メールアドレスを確認",subtitle:"送信した確認メールからアカウント設定を完了してください",sentToLabel:"送信先",resendButton:"確認メールを再送信",resendCountdown:"{seconds}秒後に再送信可能",changeEmailButton:"別のメールアドレスを使用"},forgotPassword:{title:"パスワードをリセット",subtitle:"メールアドレスを入力するとリセットコードをお送りします",emailLabel:"メールアドレス",submitButton:"リセットコードを送信"},resetPassword:{title:"新しいパスワードを設定",subtitle:"メールで届いた認証コードを使ってパスワードをリセットしてください",codeLabel:"認証コード",newPasswordLabel:"新しいパスワード",confirmPasswordLabel:"パスワード(確認)",submitButton:"パスワードを更新",resendCodeButton:"コードを再送信",resendCountdown:"{seconds}秒後に再送信可能"},oauth:{dividerText:"または",continueWith:"で続行"},errors:{invalidEmail:"有効なメールアドレスを入力してください",requiredField:"この項目は必須です",passwordTooShort:"パスワードは {min} 文字以上で入力してください",passwordMismatch:"パスワードが一致しません",invalidCode:"6桁の認証コードを入力してください",generic:"エラーが発生しました。もう一度お試しください"}},j={common:{loading:"로그인 로딩 중…",redirecting:"리디렉션 중…",backToSignIn:"로그인으로 돌아가기"},signIn:{title:"다시 오신 것을 환영합니다",subtitle:"로그인하여 계속하기",emailLabel:"이메일",passwordLabel:"비밀번호",submitButton:"로그인",forgotPassword:"비밀번호를 잊으셨나요?",switchToSignUp:"계정 만들기",signUpPrompt:"계정이 없으신가요?"},signUp:{title:"계정 만들기",subtitle:"이름, 이메일, 비밀번호를 입력해 주세요",nameLabel:"이름",emailLabel:"이메일",passwordLabel:"비밀번호",confirmPasswordLabel:"비밀번호 확인",submitButton:"계정 생성",switchToSignIn:"로그인",signInPrompt:"이미 계정이 있으신가요?"},verifyEmail:{title:"이메일 인증",subtitle:"발송된 인증 이메일에서 계정 설정을 완료해 주세요",sentToLabel:"발송 대상",resendButton:"인증 이메일 재발송",resendCountdown:"{seconds}초 후 재발송 가능",changeEmailButton:"다른 이메일 사용"},forgotPassword:{title:"비밀번호 재설정",subtitle:"이메일을 입력하시면 재설정 코드를 보내드립니다",emailLabel:"이메일",submitButton:"재설정 코드 발송"},resetPassword:{title:"새 비밀번호 설정",subtitle:"이메일로 받은 인증 코드를 사용하여 비밀번호를 재설정하세요",codeLabel:"인증 코드",newPasswordLabel:"새 비밀번호",confirmPasswordLabel:"비밀번호 확인",submitButton:"비밀번호 변경",resendCodeButton:"코드 재발송",resendCountdown:"{seconds}초 후 재발송 가능"},oauth:{dividerText:"또는",continueWith:"으로 계속"},errors:{invalidEmail:"올바른 이메일 주소를 입력해 주세요",requiredField:"필수 입력 항목입니다",passwordTooShort:"비밀번호는 최소 {min}자 이상이어야 합니다",passwordMismatch:"비밀번호가 일치하지 않습니다",invalidCode:"6자리 인증 코드를 입력해 주세요",generic:"문제가 발생했습니다. 다시 시도해 주세요"}},B={common:{loading:"Cargando inicio de sesión…",redirecting:"Redirigiendo…",backToSignIn:"Volver a iniciar sesión"},signIn:{title:"Bienvenido de nuevo",subtitle:"Inicia sesión para continuar",emailLabel:"Correo electrónico",passwordLabel:"Contraseña",submitButton:"Iniciar sesión",forgotPassword:"¿Olvidaste tu contraseña?",switchToSignUp:"Crear una cuenta",signUpPrompt:"¿No tienes cuenta?"},signUp:{title:"Crea tu cuenta",subtitle:"Empieza con tu nombre, correo y contraseña",nameLabel:"Nombre",emailLabel:"Correo electrónico",passwordLabel:"Contraseña",confirmPasswordLabel:"Confirmar contraseña",submitButton:"Crear cuenta",switchToSignIn:"Iniciar sesión",signInPrompt:"¿Ya tienes una cuenta?"},verifyEmail:{title:"Verifica tu correo",subtitle:"Completa la configuración desde el correo de verificación que te enviamos.",sentToLabel:"Enviado a",resendButton:"Reenviar correo de verificación",resendCountdown:"Reenviar en {seconds}s",changeEmailButton:"Usar otro correo"},forgotPassword:{title:"Restablecer contraseña",subtitle:"Ingresa tu correo y te enviaremos un código de restablecimiento.",emailLabel:"Correo electrónico",submitButton:"Enviar código"},resetPassword:{title:"Establece una nueva contraseña",subtitle:"Usa el código de tu correo para completar el restablecimiento.",codeLabel:"Código de verificación",newPasswordLabel:"Nueva contraseña",confirmPasswordLabel:"Confirmar contraseña",submitButton:"Actualizar contraseña",resendCodeButton:"Reenviar código",resendCountdown:"Reenviar en {seconds}s"},oauth:{dividerText:"o",continueWith:"Continuar con"},errors:{invalidEmail:"Ingresa una dirección de correo válida.",requiredField:"Este campo es obligatorio.",passwordTooShort:"La contraseña debe tener al menos {min} caracteres.",passwordMismatch:"Las contraseñas no coinciden.",invalidCode:"Ingresa el código de verificación de 6 dígitos.",generic:"Algo salió mal. Por favor, inténtalo de nuevo."}},G={common:{loading:"Carregando login…",redirecting:"Redirecionando…",backToSignIn:"Voltar para o login"},signIn:{title:"Bem-vindo de volta",subtitle:"Faça login para continuar",emailLabel:"E-mail",passwordLabel:"Senha",submitButton:"Entrar",forgotPassword:"Esqueceu a senha?",switchToSignUp:"Criar uma conta",signUpPrompt:"Não tem uma conta?"},signUp:{title:"Crie sua conta",subtitle:"Comece com seu nome, e-mail e senha",nameLabel:"Nome",emailLabel:"E-mail",passwordLabel:"Senha",confirmPasswordLabel:"Confirmar senha",submitButton:"Criar conta",switchToSignIn:"Entrar",signInPrompt:"Já tem uma conta?"},verifyEmail:{title:"Verifique seu e-mail",subtitle:"Conclua a configuração a partir do e-mail de verificação que enviamos.",sentToLabel:"Enviado para",resendButton:"Reenviar e-mail de verificação",resendCountdown:"Reenviar em {seconds}s",changeEmailButton:"Usar outro e-mail"},forgotPassword:{title:"Redefinir senha",subtitle:"Informe seu e-mail e enviaremos um código de redefinição.",emailLabel:"E-mail",submitButton:"Enviar código"},resetPassword:{title:"Defina uma nova senha",subtitle:"Use o código recebido por e-mail para concluir a redefinição.",codeLabel:"Código de verificação",newPasswordLabel:"Nova senha",confirmPasswordLabel:"Confirmar senha",submitButton:"Atualizar senha",resendCodeButton:"Reenviar código",resendCountdown:"Reenviar em {seconds}s"},oauth:{dividerText:"ou",continueWith:"Continuar com"},errors:{invalidEmail:"Insira um endereço de e-mail válido.",requiredField:"Este campo é obrigatório.",passwordTooShort:"A senha deve ter pelo menos {min} caracteres.",passwordMismatch:"As senhas não coincidem.",invalidCode:"Insira o código de verificação de 6 dígitos.",generic:"Algo deu errado. Por favor, tente novamente."}},Y={common:{loading:"Chargement de la connexion…",redirecting:"Redirection…",backToSignIn:"Retour à la connexion"},signIn:{title:"Bon retour",subtitle:"Connectez-vous pour continuer",emailLabel:"Adresse e-mail",passwordLabel:"Mot de passe",submitButton:"Se connecter",forgotPassword:"Mot de passe oublié ?",switchToSignUp:"Créer un compte",signUpPrompt:"Vous n’avez pas de compte ?"},signUp:{title:"Créez votre compte",subtitle:"Commencez par votre nom, e-mail et mot de passe",nameLabel:"Nom",emailLabel:"Adresse e-mail",passwordLabel:"Mot de passe",confirmPasswordLabel:"Confirmer le mot de passe",submitButton:"Créer le compte",switchToSignIn:"Se connecter",signInPrompt:"Vous avez déjà un compte ?"},verifyEmail:{title:"Vérifiez votre e-mail",subtitle:"Finalisez la création de votre compte depuis l’e-mail de vérification envoyé.",sentToLabel:"Envoyé à",resendButton:"Renvoyer l’e-mail de vérification",resendCountdown:"Renvoyer dans {seconds}s",changeEmailButton:"Utiliser un autre e-mail"},forgotPassword:{title:"Réinitialiser le mot de passe",subtitle:"Saisissez votre e-mail pour recevoir un code de réinitialisation.",emailLabel:"Adresse e-mail",submitButton:"Envoyer le code"},resetPassword:{title:"Définir un nouveau mot de passe",subtitle:"Utilisez le code reçu par e-mail pour réinitialiser votre mot de passe.",codeLabel:"Code de vérification",newPasswordLabel:"Nouveau mot de passe",confirmPasswordLabel:"Confirmer le mot de passe",submitButton:"Mettre à jour le mot de passe",resendCodeButton:"Renvoyer le code",resendCountdown:"Renvoyer dans {seconds}s"},oauth:{dividerText:"ou",continueWith:"Continuer avec"},errors:{invalidEmail:"Veuillez saisir une adresse e-mail valide.",requiredField:"Ce champ est requis.",passwordTooShort:"Le mot de passe doit contenir au moins {min} caractères.",passwordMismatch:"Les mots de passe ne correspondent pas.",invalidCode:"Saisissez le code de vérification à 6 chiffres.",generic:"Une erreur est survenue. Veuillez réessayer."}},K={common:{loading:"Anmeldung wird geladen…",redirecting:"Weiterleitung…",backToSignIn:"Zurück zur Anmeldung"},signIn:{title:"Willkommen zurück",subtitle:"Melden Sie sich an, um fortzufahren",emailLabel:"E-Mail-Adresse",passwordLabel:"Passwort",submitButton:"Anmelden",forgotPassword:"Passwort vergessen?",switchToSignUp:"Konto erstellen",signUpPrompt:"Noch kein Konto?"},signUp:{title:"Konto erstellen",subtitle:"Geben Sie Ihren Namen, Ihre E-Mail und ein Passwort ein",nameLabel:"Name",emailLabel:"E-Mail-Adresse",passwordLabel:"Passwort",confirmPasswordLabel:"Passwort bestätigen",submitButton:"Konto erstellen",switchToSignIn:"Anmelden",signInPrompt:"Bereits ein Konto?"},verifyEmail:{title:"E-Mail bestätigen",subtitle:"Schließen Sie die Einrichtung über die Bestätigungs-E-Mail ab, die wir Ihnen gesendet haben.",sentToLabel:"Gesendet an",resendButton:"Bestätigungs-E-Mail erneut senden",resendCountdown:"Erneut senden in {seconds}s",changeEmailButton:"Andere E-Mail verwenden"},forgotPassword:{title:"Passwort zurücksetzen",subtitle:"Geben Sie Ihre E-Mail ein und wir senden Ihnen einen Zurücksetzungscode.",emailLabel:"E-Mail-Adresse",submitButton:"Code senden"},resetPassword:{title:"Neues Passwort festlegen",subtitle:"Verwenden Sie den Code aus der E-Mail, um Ihr Passwort zurückzusetzen.",codeLabel:"Bestätigungscode",newPasswordLabel:"Neues Passwort",confirmPasswordLabel:"Passwort bestätigen",submitButton:"Passwort aktualisieren",resendCodeButton:"Code erneut senden",resendCountdown:"Erneut senden in {seconds}s"},oauth:{dividerText:"oder",continueWith:"Weiter mit"},errors:{invalidEmail:"Bitte geben Sie eine gültige E-Mail-Adresse ein.",requiredField:"Dieses Feld ist erforderlich.",passwordTooShort:"Das Passwort muss mindestens {min} Zeichen lang sein.",passwordMismatch:"Die Passwörter stimmen nicht überein.",invalidCode:"Geben Sie den 6-stelligen Bestätigungscode ein.",generic:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut."}},J={common:{loading:"Caricamento accesso…",redirecting:"Reindirizzamento…",backToSignIn:"Torna all’accesso"},signIn:{title:"Bentornato",subtitle:"Accedi per continuare",emailLabel:"Indirizzo e-mail",passwordLabel:"Password",submitButton:"Accedi",forgotPassword:"Password dimenticata?",switchToSignUp:"Crea un account",signUpPrompt:"Non hai un account?"},signUp:{title:"Crea il tuo account",subtitle:"Inserisci nome, e-mail e password per iniziare",nameLabel:"Nome",emailLabel:"Indirizzo e-mail",passwordLabel:"Password",confirmPasswordLabel:"Conferma password",submitButton:"Crea account",switchToSignIn:"Accedi",signInPrompt:"Hai già un account?"},verifyEmail:{title:"Verifica la tua e-mail",subtitle:"Completa la configurazione dall’e-mail di verifica che ti abbiamo inviato.",sentToLabel:"Inviata a",resendButton:"Reinvia e-mail di verifica",resendCountdown:"Reinvia tra {seconds}s",changeEmailButton:"Usa un’altra e-mail"},forgotPassword:{title:"Reimposta la password",subtitle:"Inserisci la tua e-mail e ti invieremo un codice di reimpostazione.",emailLabel:"Indirizzo e-mail",submitButton:"Invia codice"},resetPassword:{title:"Imposta una nuova password",subtitle:"Usa il codice ricevuto via e-mail per reimpostare la password.",codeLabel:"Codice di verifica",newPasswordLabel:"Nuova password",confirmPasswordLabel:"Conferma password",submitButton:"Aggiorna password",resendCodeButton:"Reinvia codice",resendCountdown:"Reinvia tra {seconds}s"},oauth:{dividerText:"oppure",continueWith:"Continua con"},errors:{invalidEmail:"Inserisci un indirizzo e-mail valido.",requiredField:"Questo campo è obbligatorio.",passwordTooShort:"La password deve contenere almeno {min} caratteri.",passwordMismatch:"Le password non corrispondono.",invalidCode:"Inserisci il codice di verifica a 6 cifre.",generic:"Qualcosa è andato storto. Riprova."}},Z={common:{loading:"Загрузка входа…",redirecting:"Перенаправление…",backToSignIn:"Вернуться ко входу"},signIn:{title:"С возвращением",subtitle:"Войдите, чтобы продолжить",emailLabel:"Электронная почта",passwordLabel:"Пароль",submitButton:"Войти",forgotPassword:"Забыли пароль?",switchToSignUp:"Создать аккаунт",signUpPrompt:"Нет аккаунта?"},signUp:{title:"Создание аккаунта",subtitle:"Укажите имя, электронную почту и пароль",nameLabel:"Имя",emailLabel:"Электронная почта",passwordLabel:"Пароль",confirmPasswordLabel:"Подтвердите пароль",submitButton:"Создать аккаунт",switchToSignIn:"Войти",signInPrompt:"Уже есть аккаунт?"},verifyEmail:{title:"Подтвердите почту",subtitle:"Завершите настройку через письмо с подтверждением, которое мы отправили.",sentToLabel:"Отправлено на",resendButton:"Отправить повторно",resendCountdown:"Повторная отправка через {seconds}с",changeEmailButton:"Использовать другую почту"},forgotPassword:{title:"Сброс пароля",subtitle:"Введите электронную почту, и мы отправим код для сброса.",emailLabel:"Электронная почта",submitButton:"Отправить код"},resetPassword:{title:"Установите новый пароль",subtitle:"Используйте код из письма для завершения сброса пароля.",codeLabel:"Код подтверждения",newPasswordLabel:"Новый пароль",confirmPasswordLabel:"Подтвердите пароль",submitButton:"Обновить пароль",resendCodeButton:"Отправить код повторно",resendCountdown:"Повторная отправка через {seconds}с"},oauth:{dividerText:"или",continueWith:"Продолжить через"},errors:{invalidEmail:"Введите корректный адрес электронной почты.",requiredField:"Это поле обязательно.",passwordTooShort:"Пароль должен содержать не менее {min} символов.",passwordMismatch:"Пароли не совпадают.",invalidCode:"Введите 6-значный код подтверждения.",generic:"Произошла ошибка. Пожалуйста, попробуйте снова."}},Q={common:{loading:"جارٍ تحميل تسجيل الدخول…",redirecting:"جارٍ إعادة التوجيه…",backToSignIn:"العودة إلى تسجيل الدخول"},signIn:{title:"مرحبًا بعودتك",subtitle:"سجّل الدخول للمتابعة",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",submitButton:"تسجيل الدخول",forgotPassword:"هل نسيت كلمة المرور؟",switchToSignUp:"إنشاء حساب",signUpPrompt:"ليس لديك حساب؟"},signUp:{title:"أنشئ حسابك",subtitle:"ابدأ بإدخال اسمك وبريدك الإلكتروني وكلمة المرور",nameLabel:"الاسم",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",confirmPasswordLabel:"تأكيد كلمة المرور",submitButton:"إنشاء الحساب",switchToSignIn:"تسجيل الدخول",signInPrompt:"لديك حساب بالفعل؟"},verifyEmail:{title:"تحقّق من بريدك الإلكتروني",subtitle:"أكمل إعداد حسابك من رسالة التحقّق التي أرسلناها.",sentToLabel:"أُرسل إلى",resendButton:"إعادة إرسال رسالة التحقّق",resendCountdown:"إعادة الإرسال خلال {seconds} ثانية",changeEmailButton:"استخدام بريد إلكتروني آخر"},forgotPassword:{title:"إعادة تعيين كلمة المرور",subtitle:"أدخل بريدك الإلكتروني وسنرسل لك رمز إعادة التعيين.",emailLabel:"البريد الإلكتروني",submitButton:"إرسال رمز إعادة التعيين"},resetPassword:{title:"تعيين كلمة مرور جديدة",subtitle:"استخدم الرمز المرسل إلى بريدك لإكمال إعادة تعيين كلمة المرور.",codeLabel:"رمز التحقّق",newPasswordLabel:"كلمة المرور الجديدة",confirmPasswordLabel:"تأكيد كلمة المرور",submitButton:"تحديث كلمة المرور",resendCodeButton:"إعادة إرسال الرمز",resendCountdown:"إعادة الإرسال خلال {seconds} ثانية"},oauth:{dividerText:"أو",continueWith:"المتابعة باستخدام"},errors:{invalidEmail:"يرجى إدخال عنوان بريد إلكتروني صالح.",requiredField:"هذا الحقل مطلوب.",passwordTooShort:"يجب أن تتكوّن كلمة المرور من {min} حرفًا على الأقل.",passwordMismatch:"كلمتا المرور غير متطابقتين.",invalidCode:"يرجى إدخال رمز التحقّق المكوّن من 6 أرقام.",generic:"حدث خطأ. يرجى المحاولة مرة أخرى."}},X={common:{loading:"सधाइन की जुलातीअ लोड हो रही है…",redirecting:"रीडायरेक्ट हो रहا है…",backToSignIn:"साइन इन पर वापस जाएँ"},signIn:{title:"वापसी आपका स्वागत है",subtitle:"जारी रखने के लिए साइन इन करें",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",submitButton:"साइन इन",forgotPassword:"पासवर्ड भूल गए?",switchToSignUp:"खाता बनाएँ",signUpPrompt:"खाता नहीं है?"},signUp:{title:"अपना खाता बनाएँ",subtitle:"अपना नाम, ईमेल और पासवर्ड दर्ज करें",nameLabel:"नाम",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",confirmPasswordLabel:"पासवर्ड की पुष्टि",submitButton:"खाता बनाएँ",switchToSignIn:"साइन इन",signInPrompt:"पहले से खाता है?"},verifyEmail:{title:"अपना ईमेल सत्यापित करें",subtitle:"हमने जो सत्यापन ईमेल भेजा है उससे सेटअप पूरा करें।",sentToLabel:"भेजा गया",resendButton:"सत्यापन ईमेल फिर से भेजें",resendCountdown:"{seconds} सेकंड में फिर से भेजें",changeEmailButton:"दूसरा ईमेल इस्तेमाल करें"},forgotPassword:{title:"पासवर्ड रीसेट करें",subtitle:"अपना ईमेल दर्ज करें और हम रीसेट कोड भेजेंगे।",emailLabel:"ईमेल",submitButton:"रीसेट कोड भेजें"},resetPassword:{title:"नया पासवर्ड सेट करें",subtitle:"पासवर्ड रीसेट पूरा करने के लिए ईमेल में प्राप्त कोड का उपयोग करें।",codeLabel:"सत्यापन कोड",newPasswordLabel:"नया पासवर्ड",confirmPasswordLabel:"पासवर्ड की पुष्टि",submitButton:"पासवर्ड अपडेट करें",resendCodeButton:"कोड फिर से भेजें",resendCountdown:"{seconds} सेकंड में फिर से भेजें"},oauth:{dividerText:"या",continueWith:"से जारी रखें"},errors:{invalidEmail:"कृपया एक वैध ईमेल पता दर्ज करें।",requiredField:"यह फ़ील्ड आवश्यक है।",passwordTooShort:"पासवर्ड कम से कम {min} अक्षरों का होना चाहिए।",passwordMismatch:"पासवर्ड मेल नहीं खाते।",invalidCode:"कृपया 6 अंकों का सत्यापन कोड दर्ज करें।",generic:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।"}},te={en:E,"en-US":E,zh:A,"zh-CN":A,"zh-TW":A,ja:W,"ja-JP":W,ko:j,"ko-KR":j,es:B,"es-ES":B,"es-MX":B,pt:G,"pt-BR":G,fr:Y,"fr-FR":Y,de:K,"de-DE":K,it:J,"it-IT":J,ru:Z,"ru-RU":Z,ar:Q,"ar-SA":Q,hi:X,"hi-IN":X};function le(){if(typeof navigator>"u")return E;const s=navigator.languages??[navigator.language];for(const e of s){const t=te[e]??te[e.split("-")[0]];if(t)return t}return E}function F(s,e="Authentication failed."){if(s instanceof m)return s;if(typeof s=="object"&&s!==null){const t=s;return new m(t.message||e,{code:t.code,status:t.status,cause:s})}return typeof s=="string"?new m(s):new m(e,{cause:s})}async function C(s){var t,i;const e=await s.getSession();if(e.error)throw new m(e.error.message||"Failed to load the current session.",{code:e.error.code??"SESSION_LOOKUP_FAILED",status:e.error.status,cause:e.error});return(t=e.data)!=null&&t.user&&((i=e.data)!=null&&i.session)?{user:e.data.user,session:e.data}:{user:null,session:null}}const fe="data-edgespark-auth",n="edgespark-auth",z="es_auth_completion",T="es_auth_email",se="oauth",I="verify-sign-in",g="verify-sign-up",ie=200,N=2,q={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function R(s){return"redirectTo"in s}function D(s){return"onSuccess"in s&&!("redirectTo"in s)}function H(s){return!s||typeof s!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim())}function ge(s){return/^\d{6}$/.test(s.trim())}function ve(s){return s==="email"||s==="name"||s==="password"||s==="confirmPassword"||s==="code"||s==="newPassword"}class Pe{constructor(e,t,i,r,o){if(this.container=e,this.auth=t,this.options=i,this.loadConfig=r,this.runtimeOptions=o,this.state={view:"loading",busy:!0,busyLabel:void 0,error:null,notice:null,email:"",name:"",password:"",confirmPassword:"",code:"",newPassword:""},this.destroyed=!1,this.terminalActionInProgress=!1,this.config=null,this.countdownUntil=null,this.countdownTimer=null,this.pendingFocusSnapshot=null,this.focusRestoreTimer=null,this.verificationCompletionAction=null,!(e instanceof HTMLElement))throw new d("authUI.mount(container, options) requires a real HTMLElement container.");this.labels=pe(le(),i.labels),this.root=document.createElement("div"),this.root.setAttribute(fe,""),e.innerHTML="",e.appendChild(this.root),this.render(),this.initialize()}destroy(){this.destroyed||(this.destroyed=!0,this.clearCountdown(),this.clearFocusRestoreTimer(),this.container.innerHTML="")}async initialize(){try{const e=this.consumeManagedReturnContext(),[t,i]=await Promise.all([this.loadConfig(),this.readMountSession(e)]);if(this.destroyed)return;if(this.config=t,i.user&&i.session){switch(e.marker){case se:case I:await this.completeAuth("sign-in",i);return;case g:await this.completeAuth("sign-up",i);return;default:break}this.handleExistingSessionOnMount(i);return}if(this.handleSessionlessManagedReturn(e))return;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(e){this.handleError(e,"Failed to load the authentication UI.")}}async readMountSession(e){if(!e.marker)return C(this.auth);let t=null;for(let i=0;i<=N;i++){try{const r=await C(this.auth);if(r.user&&r.session)return r}catch(r){t=r}i<N&&await new Promise(r=>setTimeout(r,ie))}if(t)throw t;return{user:null,session:null}}render(){if(this.destroyed)return;const e=this.captureFocusSnapshot();if(e&&(this.pendingFocusSnapshot=e),!this.config){this.root.innerHTML=this.renderLoading();return}this.root.innerHTML=`
2
- <div class="${n}__shell">
3
- <div class="${n}__card">
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Be=require("better-auth/client");class q extends Error{constructor(e,s){super(s),this.name="EdgeSparkError",this.code=e}}class h extends q{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class ce extends q{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class g extends q{constructor(e,s){super((s==null?void 0:s.code)??"AUTH_ERROR",e),this.name="EdgeSparkAuthError",this.cause=s==null?void 0:s.cause,this.status=s==null?void 0:s.status}}function Pe(){if(typeof window>"u"||typeof document>"u")throw new ce("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function X(){return Pe(),window.location.origin}function ke(t){return t instanceof URL?t:typeof t=="string"?new URL(t,window.location.href):new URL(t.url,window.location.href)}function Me(t){if(t.origin!==X())throw new h(`Cross-origin requests are not supported by this SDK. Received ${t.origin}, expected ${X()}.`)}function Oe(){return{async fetch(t,e){const s=ke(t);return Me(s),fetch(t,{...e,credentials:"include"})}}}const Ee="/api/_es/auth",Ve="edgespark-auth-session",Le="__edgespark_auth_sync__",S="__edgespark_auth_pending_sign_in__",_e=Symbol("edgespark.notifyAuthTabs"),Ie=10*60*1e3,Ne=new Set(["signOut","revokeSession","revokeSessions","revokeOtherSessions"]);class Fe{constructor(e){this.value=e}deref(){return this.value}}const me=globalThis.WeakRef,fe=globalThis.FinalizationRegistry;let j,we=!1;const A=new Map,H=fe?new fe(t=>{A.delete(t)}):null;function Ce(t){return Be.createAuthClient({baseURL:X(),basePath:Ee,...t!=null&&t.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function T(t){var e,s;return(s=(e=t.$store)==null?void 0:e.atoms)==null?void 0:s.session}function ze(t){return JSON.stringify({source:t,timestamp:Date.now()})}function De(t){if(typeof t!="string")return null;try{const e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}async function ee(t){var e;try{return await((e=T(t))==null?void 0:e.get().refetch()),!0}catch{return!1}}function Te(){return j===void 0&&(j=typeof BroadcastChannel<"u"?new BroadcastChannel(Ve):null),j}function ge(t){const e=De(t);if(e)for(const[s,i]of A){if(s===e.source)continue;const n=i.deref();if(!n){A.delete(s);continue}ee(n)}}function qe(){var t;we||(we=!0,(t=Te())==null||t.addEventListener("message",e=>{ge(e.data)}),typeof window<"u"&&window.addEventListener("storage",e=>{e.key!==Le||e.newValue===null||ge(e.newValue)}))}function je(t,e){me?A.set(t,new me(e)):(A.clear(),A.set(t,new Fe(e))),H==null||H.register(e,t),qe()}function _(t){var s;const e=ze(t);try{(s=Te())==null||s.postMessage(e)}catch{}try{window.localStorage.setItem(Le,e)}catch{}}function x(t){if(!(typeof window>"u"))try{window.sessionStorage.setItem(S,JSON.stringify({path:t,createdAt:Date.now()}))}catch{}}function U(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(S)}catch{}}function He(t){return!!(t!=null&&t.session&&(t!=null&&t.user))}function pe(){if(typeof window>"u")return!1;try{const t=window.sessionStorage.getItem(S);if(!t)return!1;window.sessionStorage.removeItem(S);const e=JSON.parse(t);return!e||typeof e!="object"||typeof e.createdAt!="number"?!1:Date.now()-e.createdAt<=Ie}catch{return!1}}function xe(){if(typeof window>"u")return!1;try{const t=window.sessionStorage.getItem(S);if(!t)return!1;const e=JSON.parse(t);return!e||typeof e!="object"||typeof e.createdAt!="number"||Date.now()-e.createdAt>Ie?(window.sessionStorage.removeItem(S),!1):!0}catch{return!1}}function We(t){if(!(t&&typeof t=="object")||"error"in t&&t.error)return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"token"in e&&typeof e.token=="string"&&e.token.length>0?!0:"session"in e&&"user"in e&&!!e.session&&!!e.user:!1}function Ge(t){if(!(t&&typeof t=="object")||"error"in t&&t.error)return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"url"in e&&typeof e.url=="string":!1}function Ye(t){if(R(t)||!(t&&typeof t=="object"))return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"user"in e&&!!e.user&&"token"in e&&e.token===null&&!("url"in e):!1}function Ke(t,e){if(t.length!==1||t[0]!=="changePassword")return!1;const[s]=e;return!!(s&&typeof s=="object"&&"revokeOtherSessions"in s&&s.revokeOtherSessions===!0)}function R(t){return!!(t&&typeof t=="object"&&"error"in t&&t.error)}function Je(t){if(R(t)||!(t&&typeof t=="object"))return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"message"in e&&e.message==="User deleted":!1}function Ze(t){return!!(t&&(typeof t=="object"||typeof t=="function")&&"then"in t&&typeof t.then=="function")}function W(t){if(t instanceof g)return t;const e=t;return new g((e==null?void 0:e.message)||"Failed to load the current session.",{code:(e==null?void 0:e.code)??"SESSION_LOOKUP_FAILED",cause:t,status:e==null?void 0:e.status})}async function Qe(t){var s,i;let e=null;try{await((s=T(t))==null?void 0:s.get().refetch())}catch(n){e=n}finally{(i=t[_e])==null||i.call(t)}if(e)throw e}function Xe(){const t=Ce(),e=`${Date.now()}-${Math.random().toString(36).slice(2)}`;je(e,t);const s=2,i=500;let n=null,a=!1,m;const w=o=>(m=o,o),P=()=>{var c;const o=(c=T(t))==null?void 0:c.get();return o!=null&&o.error&&!o.data&&m!==void 0?m:(o==null?void 0:o.data)??m??null},E=()=>a?Promise.resolve(P()):(n||(n=(async()=>{var l,u,p;let o=!1,c=null;try{for(let b=0;b<=s;b++){let d=null;try{d=await t.getSession()}catch(v){c=v}const y=((l=T(t))==null?void 0:l.get().data)??null;if((u=d==null?void 0:d.data)!=null&&u.session&&((p=d.data)!=null&&p.user))return a=!0,pe()&&_(e),w(d.data);if(y!=null&&y.session&&(y!=null&&y.user))return a=!0,pe()&&_(e),w(y);if(d!=null&&d.error?c=d.error:d&&(o=!0),d&&!d.error&&xe()&&b<s){await new Promise(v=>setTimeout(v,i));continue}if(d&&!d.error){const v=P();return a=!0,w(v)}b<s&&await new Promise(v=>setTimeout(v,i))}if(!o)throw n=null,new g("Failed to load the current session.",{code:"SESSION_LOOKUP_FAILED",cause:c});const f=P();return a=!0,w(f)}catch(f){throw n=null,W(f)}})()),n);E().catch(()=>{});const L=async()=>{var o,c;try{const l=await t.getSession();if((o=l.data)!=null&&o.session&&((c=l.data)!=null&&c.user))return l.data;throw l.error?W(l.error):new g("No authenticated session is available.",{code:"UNAUTHENTICATED"})}catch(l){throw W(l)}},$=async()=>{await ee(t),_(e)},Ae=async()=>{var l;const o=await ee(t),c=((l=T(t))==null?void 0:l.get().data)??null;He(c)?(U(),_(e)):o||_(e)},$e=o=>{let c=!1,l=!1,u;const p=d=>{d!==u&&(u=d,o(d))};E().then(d=>{c||(l=!0,p(w(d)))}).catch(()=>{c||(l=!0)});const f=T(t);if(!f)return()=>{c=!0};const b=f.subscribe(d=>{if(c||!l||d.error&&!d.data)return;const y=d.data??null;p(w(y))});return()=>{c=!0,b()}},Ue=async(o,c,l)=>{const u=o[0],p=o.length>=2&&u==="emailOtp"&&o[1]==="verifyEmail";return o.length===1&&(u==="deleteUser"||u==="deleteUserCallback")?(U(),Je(l)&&await $(),l):o.length===1&&u&&Ne.has(u)?(U(),R(l)||await $(),l):Ke(o,c)&&!R(l)?(U(),await $(),l):o.length===1&&u==="changeEmail"&&!R(l)?(await $(),l):((u==="signIn"||u==="signUp"||p)&&We(l)?(U(),await $()):(u==="signIn"||u==="signUp")&&Ge(l)||u==="signUp"&&Ye(l)?x(o):u==="verifyEmail"&&!R(l)&&(x(o),await Ae()),l)},ue=new WeakMap,he=(o,c)=>{if(!o||typeof o!="object"&&typeof o!="function")return o;const l=ue.get(o);if(l)return l;const u=new Proxy(o,{get(p,f,b){if(c.length===0){if(f==="requireSession")return L;if(f==="onSessionChange")return $e;if(f===_e)return()=>{_(e)}}const d=Reflect.get(p,f,b);return typeof f!="string"?d:he(d,[...c,f])},apply(p,f,b){const d=Reflect.apply(p,f,b);return Ze(d)?Promise.resolve(d).then(y=>Ue(c,b,y)):d}});return ue.set(o,u),u};return he(t,[])}function et(){return Ce({disableDefaultRedirectPlugin:!0})}function k(t){const e=(()=>{if(t instanceof URL)return t;const s=t.trim();if(!s)throw new h("redirectTo must not be an empty string.");try{return new URL(s,window.location.href)}catch{throw new h(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(t)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new h(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function tt(t,e){return e?{common:{...t.common,...e.common},signIn:{...t.signIn,...e.signIn},signUp:{...t.signUp,...e.signUp},verifyEmail:{...t.verifyEmail,...e.verifyEmail},forgotPassword:{...t.forgotPassword,...e.forgotPassword},resetPassword:{...t.resetPassword,...e.resetPassword},oauth:{...t.oauth,...e.oauth},errors:{...t.errors,...e.errors}}:t}const B={common:{loading:"Loading sign-in…",redirecting:"Redirecting…",backToSignIn:"Back to sign in"},signIn:{title:"Welcome back",subtitle:"Sign in to continue",emailLabel:"Email",passwordLabel:"Password",submitButton:"Sign in",forgotPassword:"Forgot password?",switchToSignUp:"Create an account",signUpPrompt:"Don’t have an account?"},signUp:{title:"Create your account",subtitle:"Start with your name, email, and password",nameLabel:"Name",emailLabel:"Email",passwordLabel:"Password",confirmPasswordLabel:"Confirm password",submitButton:"Create account",switchToSignIn:"Sign in",signInPrompt:"Already have an account?"},verifyEmail:{title:"Verify your email",subtitle:"Finish account setup from the verification email we sent.",sentToLabel:"Sent to",resendButton:"Resend verification email",resendCountdown:"Resend in {seconds}s",changeEmailButton:"Use a different email"},forgotPassword:{title:"Reset your password",subtitle:"Enter your email and we will send a reset code.",emailLabel:"Email",submitButton:"Send reset code"},resetPassword:{title:"Set a new password",subtitle:"Use the code from your email to finish resetting your password.",codeLabel:"Verification code",newPasswordLabel:"New password",confirmPasswordLabel:"Confirm password",submitButton:"Update password",resendCodeButton:"Resend code",resendCountdown:"Resend in {seconds}s"},oauth:{dividerText:"or",continueWith:"Continue with"},errors:{invalidEmail:"Enter a valid email address.",requiredField:"This field is required.",passwordTooShort:"Password must be at least {min} characters.",passwordMismatch:"Passwords do not match.",invalidCode:"Enter the 6-digit verification code.",generic:"Something went wrong. Please try again."}},z={common:{loading:"加载中…",redirecting:"跳转中…",backToSignIn:"返回登录"},signIn:{title:"欢迎回来",subtitle:"登录以继续",emailLabel:"邮箱",passwordLabel:"密码",submitButton:"登录",forgotPassword:"忘记密码?",switchToSignUp:"立即注册",signUpPrompt:"没有账号?"},signUp:{title:"创建账号",subtitle:"填写姓名、邮箱和密码开始使用",nameLabel:"姓名",emailLabel:"邮箱",passwordLabel:"密码",confirmPasswordLabel:"确认密码",submitButton:"注册",switchToSignIn:"去登录",signInPrompt:"已有账号?"},verifyEmail:{title:"验证邮箱",subtitle:"请查收邮件并点击验证链接",sentToLabel:"已发送至",resendButton:"重新发送验证邮件",resendCountdown:"{seconds}秒后可重发",changeEmailButton:"更换邮箱"},forgotPassword:{title:"重置密码",subtitle:"输入邮箱以接收重置验证码",emailLabel:"邮箱",submitButton:"发送重置码"},resetPassword:{title:"设置新密码",subtitle:"使用邮件中的验证码完成密码重置",codeLabel:"验证码",newPasswordLabel:"新密码",confirmPasswordLabel:"确认密码",submitButton:"更新密码",resendCodeButton:"重新发送",resendCountdown:"{seconds}秒后可重发"},oauth:{dividerText:"或",continueWith:"使用"},errors:{invalidEmail:"请输入有效的邮箱地址",requiredField:"此项为必填",passwordTooShort:"密码至少需要 {min} 个字符",passwordMismatch:"两次密码输入不一致",invalidCode:"请输入 6 位验证码",generic:"出现错误,请稍后重试"}},te={common:{loading:"サインインを読み込み中…",redirecting:"リダイレクト中…",backToSignIn:"サインインに戻る"},signIn:{title:"おかえりなさい",subtitle:"サインインして続行",emailLabel:"メールアドレス",passwordLabel:"パスワード",submitButton:"サインイン",forgotPassword:"パスワードをお忘れですか?",switchToSignUp:"アカウントを作成",signUpPrompt:"アカウントをお持ちでない方"},signUp:{title:"アカウントを作成",subtitle:"名前、メールアドレス、パスワードを入力してください",nameLabel:"名前",emailLabel:"メールアドレス",passwordLabel:"パスワード",confirmPasswordLabel:"パスワード(確認)",submitButton:"アカウント作成",switchToSignIn:"サインイン",signInPrompt:"既にアカウントをお持ちですか?"},verifyEmail:{title:"メールアドレスを確認",subtitle:"送信した確認メールからアカウント設定を完了してください",sentToLabel:"送信先",resendButton:"確認メールを再送信",resendCountdown:"{seconds}秒後に再送信可能",changeEmailButton:"別のメールアドレスを使用"},forgotPassword:{title:"パスワードをリセット",subtitle:"メールアドレスを入力するとリセットコードをお送りします",emailLabel:"メールアドレス",submitButton:"リセットコードを送信"},resetPassword:{title:"新しいパスワードを設定",subtitle:"メールで届いた認証コードを使ってパスワードをリセットしてください",codeLabel:"認証コード",newPasswordLabel:"新しいパスワード",confirmPasswordLabel:"パスワード(確認)",submitButton:"パスワードを更新",resendCodeButton:"コードを再送信",resendCountdown:"{seconds}秒後に再送信可能"},oauth:{dividerText:"または",continueWith:"で続行"},errors:{invalidEmail:"有効なメールアドレスを入力してください",requiredField:"この項目は必須です",passwordTooShort:"パスワードは {min} 文字以上で入力してください",passwordMismatch:"パスワードが一致しません",invalidCode:"6桁の認証コードを入力してください",generic:"エラーが発生しました。もう一度お試しください"}},se={common:{loading:"로그인 로딩 중…",redirecting:"리디렉션 중…",backToSignIn:"로그인으로 돌아가기"},signIn:{title:"다시 오신 것을 환영합니다",subtitle:"로그인하여 계속하기",emailLabel:"이메일",passwordLabel:"비밀번호",submitButton:"로그인",forgotPassword:"비밀번호를 잊으셨나요?",switchToSignUp:"계정 만들기",signUpPrompt:"계정이 없으신가요?"},signUp:{title:"계정 만들기",subtitle:"이름, 이메일, 비밀번호를 입력해 주세요",nameLabel:"이름",emailLabel:"이메일",passwordLabel:"비밀번호",confirmPasswordLabel:"비밀번호 확인",submitButton:"계정 생성",switchToSignIn:"로그인",signInPrompt:"이미 계정이 있으신가요?"},verifyEmail:{title:"이메일 인증",subtitle:"발송된 인증 이메일에서 계정 설정을 완료해 주세요",sentToLabel:"발송 대상",resendButton:"인증 이메일 재발송",resendCountdown:"{seconds}초 후 재발송 가능",changeEmailButton:"다른 이메일 사용"},forgotPassword:{title:"비밀번호 재설정",subtitle:"이메일을 입력하시면 재설정 코드를 보내드립니다",emailLabel:"이메일",submitButton:"재설정 코드 발송"},resetPassword:{title:"새 비밀번호 설정",subtitle:"이메일로 받은 인증 코드를 사용하여 비밀번호를 재설정하세요",codeLabel:"인증 코드",newPasswordLabel:"새 비밀번호",confirmPasswordLabel:"비밀번호 확인",submitButton:"비밀번호 변경",resendCodeButton:"코드 재발송",resendCountdown:"{seconds}초 후 재발송 가능"},oauth:{dividerText:"또는",continueWith:"으로 계속"},errors:{invalidEmail:"올바른 이메일 주소를 입력해 주세요",requiredField:"필수 입력 항목입니다",passwordTooShort:"비밀번호는 최소 {min}자 이상이어야 합니다",passwordMismatch:"비밀번호가 일치하지 않습니다",invalidCode:"6자리 인증 코드를 입력해 주세요",generic:"문제가 발생했습니다. 다시 시도해 주세요"}},D={common:{loading:"Cargando inicio de sesión…",redirecting:"Redirigiendo…",backToSignIn:"Volver a iniciar sesión"},signIn:{title:"Bienvenido de nuevo",subtitle:"Inicia sesión para continuar",emailLabel:"Correo electrónico",passwordLabel:"Contraseña",submitButton:"Iniciar sesión",forgotPassword:"¿Olvidaste tu contraseña?",switchToSignUp:"Crear una cuenta",signUpPrompt:"¿No tienes cuenta?"},signUp:{title:"Crea tu cuenta",subtitle:"Empieza con tu nombre, correo y contraseña",nameLabel:"Nombre",emailLabel:"Correo electrónico",passwordLabel:"Contraseña",confirmPasswordLabel:"Confirmar contraseña",submitButton:"Crear cuenta",switchToSignIn:"Iniciar sesión",signInPrompt:"¿Ya tienes una cuenta?"},verifyEmail:{title:"Verifica tu correo",subtitle:"Completa la configuración desde el correo de verificación que te enviamos.",sentToLabel:"Enviado a",resendButton:"Reenviar correo de verificación",resendCountdown:"Reenviar en {seconds}s",changeEmailButton:"Usar otro correo"},forgotPassword:{title:"Restablecer contraseña",subtitle:"Ingresa tu correo y te enviaremos un código de restablecimiento.",emailLabel:"Correo electrónico",submitButton:"Enviar código"},resetPassword:{title:"Establece una nueva contraseña",subtitle:"Usa el código de tu correo para completar el restablecimiento.",codeLabel:"Código de verificación",newPasswordLabel:"Nueva contraseña",confirmPasswordLabel:"Confirmar contraseña",submitButton:"Actualizar contraseña",resendCodeButton:"Reenviar código",resendCountdown:"Reenviar en {seconds}s"},oauth:{dividerText:"o",continueWith:"Continuar con"},errors:{invalidEmail:"Ingresa una dirección de correo válida.",requiredField:"Este campo es obligatorio.",passwordTooShort:"La contraseña debe tener al menos {min} caracteres.",passwordMismatch:"Las contraseñas no coinciden.",invalidCode:"Ingresa el código de verificación de 6 dígitos.",generic:"Algo salió mal. Por favor, inténtalo de nuevo."}},ie={common:{loading:"Carregando login…",redirecting:"Redirecionando…",backToSignIn:"Voltar para o login"},signIn:{title:"Bem-vindo de volta",subtitle:"Faça login para continuar",emailLabel:"E-mail",passwordLabel:"Senha",submitButton:"Entrar",forgotPassword:"Esqueceu a senha?",switchToSignUp:"Criar uma conta",signUpPrompt:"Não tem uma conta?"},signUp:{title:"Crie sua conta",subtitle:"Comece com seu nome, e-mail e senha",nameLabel:"Nome",emailLabel:"E-mail",passwordLabel:"Senha",confirmPasswordLabel:"Confirmar senha",submitButton:"Criar conta",switchToSignIn:"Entrar",signInPrompt:"Já tem uma conta?"},verifyEmail:{title:"Verifique seu e-mail",subtitle:"Conclua a configuração a partir do e-mail de verificação que enviamos.",sentToLabel:"Enviado para",resendButton:"Reenviar e-mail de verificação",resendCountdown:"Reenviar em {seconds}s",changeEmailButton:"Usar outro e-mail"},forgotPassword:{title:"Redefinir senha",subtitle:"Informe seu e-mail e enviaremos um código de redefinição.",emailLabel:"E-mail",submitButton:"Enviar código"},resetPassword:{title:"Defina uma nova senha",subtitle:"Use o código recebido por e-mail para concluir a redefinição.",codeLabel:"Código de verificação",newPasswordLabel:"Nova senha",confirmPasswordLabel:"Confirmar senha",submitButton:"Atualizar senha",resendCodeButton:"Reenviar código",resendCountdown:"Reenviar em {seconds}s"},oauth:{dividerText:"ou",continueWith:"Continuar com"},errors:{invalidEmail:"Insira um endereço de e-mail válido.",requiredField:"Este campo é obrigatório.",passwordTooShort:"A senha deve ter pelo menos {min} caracteres.",passwordMismatch:"As senhas não coincidem.",invalidCode:"Insira o código de verificação de 6 dígitos.",generic:"Algo deu errado. Por favor, tente novamente."}},ne={common:{loading:"Chargement de la connexion…",redirecting:"Redirection…",backToSignIn:"Retour à la connexion"},signIn:{title:"Bon retour",subtitle:"Connectez-vous pour continuer",emailLabel:"Adresse e-mail",passwordLabel:"Mot de passe",submitButton:"Se connecter",forgotPassword:"Mot de passe oublié ?",switchToSignUp:"Créer un compte",signUpPrompt:"Vous n’avez pas de compte ?"},signUp:{title:"Créez votre compte",subtitle:"Commencez par votre nom, e-mail et mot de passe",nameLabel:"Nom",emailLabel:"Adresse e-mail",passwordLabel:"Mot de passe",confirmPasswordLabel:"Confirmer le mot de passe",submitButton:"Créer le compte",switchToSignIn:"Se connecter",signInPrompt:"Vous avez déjà un compte ?"},verifyEmail:{title:"Vérifiez votre e-mail",subtitle:"Finalisez la création de votre compte depuis l’e-mail de vérification envoyé.",sentToLabel:"Envoyé à",resendButton:"Renvoyer l’e-mail de vérification",resendCountdown:"Renvoyer dans {seconds}s",changeEmailButton:"Utiliser un autre e-mail"},forgotPassword:{title:"Réinitialiser le mot de passe",subtitle:"Saisissez votre e-mail pour recevoir un code de réinitialisation.",emailLabel:"Adresse e-mail",submitButton:"Envoyer le code"},resetPassword:{title:"Définir un nouveau mot de passe",subtitle:"Utilisez le code reçu par e-mail pour réinitialiser votre mot de passe.",codeLabel:"Code de vérification",newPasswordLabel:"Nouveau mot de passe",confirmPasswordLabel:"Confirmer le mot de passe",submitButton:"Mettre à jour le mot de passe",resendCodeButton:"Renvoyer le code",resendCountdown:"Renvoyer dans {seconds}s"},oauth:{dividerText:"ou",continueWith:"Continuer avec"},errors:{invalidEmail:"Veuillez saisir une adresse e-mail valide.",requiredField:"Ce champ est requis.",passwordTooShort:"Le mot de passe doit contenir au moins {min} caractères.",passwordMismatch:"Les mots de passe ne correspondent pas.",invalidCode:"Saisissez le code de vérification à 6 chiffres.",generic:"Une erreur est survenue. Veuillez réessayer."}},re={common:{loading:"Anmeldung wird geladen…",redirecting:"Weiterleitung…",backToSignIn:"Zurück zur Anmeldung"},signIn:{title:"Willkommen zurück",subtitle:"Melden Sie sich an, um fortzufahren",emailLabel:"E-Mail-Adresse",passwordLabel:"Passwort",submitButton:"Anmelden",forgotPassword:"Passwort vergessen?",switchToSignUp:"Konto erstellen",signUpPrompt:"Noch kein Konto?"},signUp:{title:"Konto erstellen",subtitle:"Geben Sie Ihren Namen, Ihre E-Mail und ein Passwort ein",nameLabel:"Name",emailLabel:"E-Mail-Adresse",passwordLabel:"Passwort",confirmPasswordLabel:"Passwort bestätigen",submitButton:"Konto erstellen",switchToSignIn:"Anmelden",signInPrompt:"Bereits ein Konto?"},verifyEmail:{title:"E-Mail bestätigen",subtitle:"Schließen Sie die Einrichtung über die Bestätigungs-E-Mail ab, die wir Ihnen gesendet haben.",sentToLabel:"Gesendet an",resendButton:"Bestätigungs-E-Mail erneut senden",resendCountdown:"Erneut senden in {seconds}s",changeEmailButton:"Andere E-Mail verwenden"},forgotPassword:{title:"Passwort zurücksetzen",subtitle:"Geben Sie Ihre E-Mail ein und wir senden Ihnen einen Zurücksetzungscode.",emailLabel:"E-Mail-Adresse",submitButton:"Code senden"},resetPassword:{title:"Neues Passwort festlegen",subtitle:"Verwenden Sie den Code aus der E-Mail, um Ihr Passwort zurückzusetzen.",codeLabel:"Bestätigungscode",newPasswordLabel:"Neues Passwort",confirmPasswordLabel:"Passwort bestätigen",submitButton:"Passwort aktualisieren",resendCodeButton:"Code erneut senden",resendCountdown:"Erneut senden in {seconds}s"},oauth:{dividerText:"oder",continueWith:"Weiter mit"},errors:{invalidEmail:"Bitte geben Sie eine gültige E-Mail-Adresse ein.",requiredField:"Dieses Feld ist erforderlich.",passwordTooShort:"Das Passwort muss mindestens {min} Zeichen lang sein.",passwordMismatch:"Die Passwörter stimmen nicht überein.",invalidCode:"Geben Sie den 6-stelligen Bestätigungscode ein.",generic:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut."}},oe={common:{loading:"Caricamento accesso…",redirecting:"Reindirizzamento…",backToSignIn:"Torna all’accesso"},signIn:{title:"Bentornato",subtitle:"Accedi per continuare",emailLabel:"Indirizzo e-mail",passwordLabel:"Password",submitButton:"Accedi",forgotPassword:"Password dimenticata?",switchToSignUp:"Crea un account",signUpPrompt:"Non hai un account?"},signUp:{title:"Crea il tuo account",subtitle:"Inserisci nome, e-mail e password per iniziare",nameLabel:"Nome",emailLabel:"Indirizzo e-mail",passwordLabel:"Password",confirmPasswordLabel:"Conferma password",submitButton:"Crea account",switchToSignIn:"Accedi",signInPrompt:"Hai già un account?"},verifyEmail:{title:"Verifica la tua e-mail",subtitle:"Completa la configurazione dall’e-mail di verifica che ti abbiamo inviato.",sentToLabel:"Inviata a",resendButton:"Reinvia e-mail di verifica",resendCountdown:"Reinvia tra {seconds}s",changeEmailButton:"Usa un’altra e-mail"},forgotPassword:{title:"Reimposta la password",subtitle:"Inserisci la tua e-mail e ti invieremo un codice di reimpostazione.",emailLabel:"Indirizzo e-mail",submitButton:"Invia codice"},resetPassword:{title:"Imposta una nuova password",subtitle:"Usa il codice ricevuto via e-mail per reimpostare la password.",codeLabel:"Codice di verifica",newPasswordLabel:"Nuova password",confirmPasswordLabel:"Conferma password",submitButton:"Aggiorna password",resendCodeButton:"Reinvia codice",resendCountdown:"Reinvia tra {seconds}s"},oauth:{dividerText:"oppure",continueWith:"Continua con"},errors:{invalidEmail:"Inserisci un indirizzo e-mail valido.",requiredField:"Questo campo è obbligatorio.",passwordTooShort:"La password deve contenere almeno {min} caratteri.",passwordMismatch:"Le password non corrispondono.",invalidCode:"Inserisci il codice di verifica a 6 cifre.",generic:"Qualcosa è andato storto. Riprova."}},ae={common:{loading:"Загрузка входа…",redirecting:"Перенаправление…",backToSignIn:"Вернуться ко входу"},signIn:{title:"С возвращением",subtitle:"Войдите, чтобы продолжить",emailLabel:"Электронная почта",passwordLabel:"Пароль",submitButton:"Войти",forgotPassword:"Забыли пароль?",switchToSignUp:"Создать аккаунт",signUpPrompt:"Нет аккаунта?"},signUp:{title:"Создание аккаунта",subtitle:"Укажите имя, электронную почту и пароль",nameLabel:"Имя",emailLabel:"Электронная почта",passwordLabel:"Пароль",confirmPasswordLabel:"Подтвердите пароль",submitButton:"Создать аккаунт",switchToSignIn:"Войти",signInPrompt:"Уже есть аккаунт?"},verifyEmail:{title:"Подтвердите почту",subtitle:"Завершите настройку через письмо с подтверждением, которое мы отправили.",sentToLabel:"Отправлено на",resendButton:"Отправить повторно",resendCountdown:"Повторная отправка через {seconds}с",changeEmailButton:"Использовать другую почту"},forgotPassword:{title:"Сброс пароля",subtitle:"Введите электронную почту, и мы отправим код для сброса.",emailLabel:"Электронная почта",submitButton:"Отправить код"},resetPassword:{title:"Установите новый пароль",subtitle:"Используйте код из письма для завершения сброса пароля.",codeLabel:"Код подтверждения",newPasswordLabel:"Новый пароль",confirmPasswordLabel:"Подтвердите пароль",submitButton:"Обновить пароль",resendCodeButton:"Отправить код повторно",resendCountdown:"Повторная отправка через {seconds}с"},oauth:{dividerText:"или",continueWith:"Продолжить через"},errors:{invalidEmail:"Введите корректный адрес электронной почты.",requiredField:"Это поле обязательно.",passwordTooShort:"Пароль должен содержать не менее {min} символов.",passwordMismatch:"Пароли не совпадают.",invalidCode:"Введите 6-значный код подтверждения.",generic:"Произошла ошибка. Пожалуйста, попробуйте снова."}},le={common:{loading:"جارٍ تحميل تسجيل الدخول…",redirecting:"جارٍ إعادة التوجيه…",backToSignIn:"العودة إلى تسجيل الدخول"},signIn:{title:"مرحبًا بعودتك",subtitle:"سجّل الدخول للمتابعة",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",submitButton:"تسجيل الدخول",forgotPassword:"هل نسيت كلمة المرور؟",switchToSignUp:"إنشاء حساب",signUpPrompt:"ليس لديك حساب؟"},signUp:{title:"أنشئ حسابك",subtitle:"ابدأ بإدخال اسمك وبريدك الإلكتروني وكلمة المرور",nameLabel:"الاسم",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",confirmPasswordLabel:"تأكيد كلمة المرور",submitButton:"إنشاء الحساب",switchToSignIn:"تسجيل الدخول",signInPrompt:"لديك حساب بالفعل؟"},verifyEmail:{title:"تحقّق من بريدك الإلكتروني",subtitle:"أكمل إعداد حسابك من رسالة التحقّق التي أرسلناها.",sentToLabel:"أُرسل إلى",resendButton:"إعادة إرسال رسالة التحقّق",resendCountdown:"إعادة الإرسال خلال {seconds} ثانية",changeEmailButton:"استخدام بريد إلكتروني آخر"},forgotPassword:{title:"إعادة تعيين كلمة المرور",subtitle:"أدخل بريدك الإلكتروني وسنرسل لك رمز إعادة التعيين.",emailLabel:"البريد الإلكتروني",submitButton:"إرسال رمز إعادة التعيين"},resetPassword:{title:"تعيين كلمة مرور جديدة",subtitle:"استخدم الرمز المرسل إلى بريدك لإكمال إعادة تعيين كلمة المرور.",codeLabel:"رمز التحقّق",newPasswordLabel:"كلمة المرور الجديدة",confirmPasswordLabel:"تأكيد كلمة المرور",submitButton:"تحديث كلمة المرور",resendCodeButton:"إعادة إرسال الرمز",resendCountdown:"إعادة الإرسال خلال {seconds} ثانية"},oauth:{dividerText:"أو",continueWith:"المتابعة باستخدام"},errors:{invalidEmail:"يرجى إدخال عنوان بريد إلكتروني صالح.",requiredField:"هذا الحقل مطلوب.",passwordTooShort:"يجب أن تتكوّن كلمة المرور من {min} حرفًا على الأقل.",passwordMismatch:"كلمتا المرور غير متطابقتين.",invalidCode:"يرجى إدخال رمز التحقّق المكوّن من 6 أرقام.",generic:"حدث خطأ. يرجى المحاولة مرة أخرى."}},de={common:{loading:"सधाइन की जुलातीअ लोड हो रही है…",redirecting:"रीडायरेक्ट हो रहا है…",backToSignIn:"साइन इन पर वापस जाएँ"},signIn:{title:"वापसी आपका स्वागत है",subtitle:"जारी रखने के लिए साइन इन करें",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",submitButton:"साइन इन",forgotPassword:"पासवर्ड भूल गए?",switchToSignUp:"खाता बनाएँ",signUpPrompt:"खाता नहीं है?"},signUp:{title:"अपना खाता बनाएँ",subtitle:"अपना नाम, ईमेल और पासवर्ड दर्ज करें",nameLabel:"नाम",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",confirmPasswordLabel:"पासवर्ड की पुष्टि",submitButton:"खाता बनाएँ",switchToSignIn:"साइन इन",signInPrompt:"पहले से खाता है?"},verifyEmail:{title:"अपना ईमेल सत्यापित करें",subtitle:"हमने जो सत्यापन ईमेल भेजा है उससे सेटअप पूरा करें।",sentToLabel:"भेजा गया",resendButton:"सत्यापन ईमेल फिर से भेजें",resendCountdown:"{seconds} सेकंड में फिर से भेजें",changeEmailButton:"दूसरा ईमेल इस्तेमाल करें"},forgotPassword:{title:"पासवर्ड रीसेट करें",subtitle:"अपना ईमेल दर्ज करें और हम रीसेट कोड भेजेंगे।",emailLabel:"ईमेल",submitButton:"रीसेट कोड भेजें"},resetPassword:{title:"नया पासवर्ड सेट करें",subtitle:"पासवर्ड रीसेट पूरा करने के लिए ईमेल में प्राप्त कोड का उपयोग करें।",codeLabel:"सत्यापन कोड",newPasswordLabel:"नया पासवर्ड",confirmPasswordLabel:"पासवर्ड की पुष्टि",submitButton:"पासवर्ड अपडेट करें",resendCodeButton:"कोड फिर से भेजें",resendCountdown:"{seconds} सेकंड में फिर से भेजें"},oauth:{dividerText:"या",continueWith:"से जारी रखें"},errors:{invalidEmail:"कृपया एक वैध ईमेल पता दर्ज करें।",requiredField:"यह फ़ील्ड आवश्यक है।",passwordTooShort:"पासवर्ड कम से कम {min} अक्षरों का होना चाहिए।",passwordMismatch:"पासवर्ड मेल नहीं खाते।",invalidCode:"कृपया 6 अंकों का सत्यापन कोड दर्ज करें।",generic:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।"}},be={en:B,"en-US":B,zh:z,"zh-CN":z,"zh-TW":z,ja:te,"ja-JP":te,ko:se,"ko-KR":se,es:D,"es-ES":D,"es-MX":D,pt:ie,"pt-BR":ie,fr:ne,"fr-FR":ne,de:re,"de-DE":re,it:oe,"it-IT":oe,ru:ae,"ru-RU":ae,ar:le,"ar-SA":le,hi:de,"hi-IN":de};function Re(){if(typeof navigator>"u")return B;const t=navigator.languages??[navigator.language];for(const e of t){const s=be[e]??be[e.split("-")[0]];if(s)return s}return B}function G(t,e="Authentication failed."){if(t instanceof g)return t;if(typeof t=="object"&&t!==null){const s=t;return new g(s.message||e,{code:s.code,status:s.status,cause:t})}return typeof t=="string"?new g(t):new g(e,{cause:t})}async function M(t){var s,i;const e=await t.getSession();if(e.error)throw new g(e.error.message||"Failed to load the current session.",{code:e.error.code??"SESSION_LOOKUP_FAILED",status:e.error.status,cause:e.error});return(s=e.data)!=null&&s.user&&((i=e.data)!=null&&i.session)?{user:e.data.user,session:e.data}:{user:null,session:null}}const st="data-edgespark-auth",r="edgespark-auth",Y="es_auth_completion",O="es_auth_email",ye="oauth",V="verify-sign-in",I="verify-sign-up",ve=200,K=2,J={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function C(t){return"redirectTo"in t}function Z(t){return"onSuccess"in t&&!("redirectTo"in t)}function Q(t){return!t||typeof t!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function it(t){return/^\d{6}$/.test(t.trim())}function nt(t){return t==="email"||t==="name"||t==="password"||t==="confirmPassword"||t==="code"||t==="newPassword"}function rt(t){return!!(t.error||t.errorDescription)}class ot{constructor(e,s,i,n,a){if(this.container=e,this.auth=s,this.options=i,this.loadConfig=n,this.runtimeOptions=a,this.state={view:"loading",busy:!0,busyLabel:void 0,error:null,notice:null,email:"",name:"",password:"",confirmPassword:"",code:"",newPassword:""},this.destroyed=!1,this.terminalActionInProgress=!1,this.config=null,this.countdownUntil=null,this.countdownTimer=null,this.pendingFocusSnapshot=null,this.focusRestoreTimer=null,this.verificationCompletionAction=null,!(e instanceof HTMLElement))throw new h("authUI.mount(container, options) requires a real HTMLElement container.");this.labels=tt(Re(),i.labels),this.root=document.createElement("div"),this.root.setAttribute(st,""),e.innerHTML="",e.appendChild(this.root),this.render(),this.initialize()}destroy(){this.destroyed||(this.destroyed=!0,this.clearCountdown(),this.clearFocusRestoreTimer(),this.container.innerHTML="")}async initialize(){const e=this.consumeManagedReturnContext();try{const[s,i]=await Promise.allSettled([this.loadConfig(),this.readMountSession(e)]);if(this.destroyed)return;if(i.status==="rejected"){if(e.marker&&!rt(e)&&C(this.options)){this.redirectAfterManagedReturnLookupFailure();return}}else{const a=i.value;if(a.user&&a.session){switch(e.marker){case ye:case V:await this.completeAuth("sign-in",a);return;case I:await this.completeAuth("sign-up",a);return;default:break}this.handleExistingSessionOnMount(a);return}}if(s.status==="rejected")throw i.status==="rejected"?i.reason:s.reason;if(this.config=s.value,this.handleSessionlessManagedReturn(e))return;if(i.status==="rejected")throw i.reason;const n=i.value;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(s){this.handleError(s,"Failed to load the authentication UI.")}}redirectAfterManagedReturnLookupFailure(){C(this.options)&&(this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(k(this.options.redirectTo).toString()))}async readMountSession(e){if(!e.marker)return M(this.auth);let s=null;for(let i=0;i<=K;i++){try{const n=await M(this.auth);if(n.user&&n.session)return n}catch(n){s=n}i<K&&await new Promise(n=>setTimeout(n,ve))}if(s)throw s;return{user:null,session:null}}render(){if(this.destroyed)return;const e=this.captureFocusSnapshot();if(e&&(this.pendingFocusSnapshot=e),!this.config){this.root.innerHTML=this.renderLoading();return}this.root.innerHTML=`
2
+ <div class="${r}__shell">
3
+ <div class="${r}__card">
4
4
  ${this.renderStatus()}
5
5
  ${this.renderCurrentView()}
6
6
  </div>
7
7
  </div>
8
8
  `,this.bindDOM(),this.scheduleFocusRestore()}renderLoading(){const e=this.renderStatus();return`
9
- <div class="${n}__shell">
10
- <div class="${n}__card">
11
- ${e||`<div class="${n}__status ${n}__status--info">${this.escape(this.labels.common.loading)}</div>`}
9
+ <div class="${r}__shell">
10
+ <div class="${r}__card">
11
+ ${e||`<div class="${r}__status ${r}__status--info">${this.escape(this.labels.common.loading)}</div>`}
12
12
  </div>
13
13
  </div>
14
- `}renderStatus(){const e=[];return this.state.error&&e.push(`<div class="${n}__status ${n}__status--error">${this.escape(this.state.error)}</div>`),this.state.notice&&e.push(`<div class="${n}__status ${n}__status--info">${this.escape(this.state.notice)}</div>`),this.state.busy&&this.state.busyLabel&&e.push(`<div class="${n}__status ${n}__status--muted">${this.escape(this.state.busyLabel)}</div>`),e.join("")}renderCurrentView(){switch(this.state.view){case"sign-in":return this.renderSignInView();case"sign-up":return this.renderSignUpView();case"verify-email":return this.renderVerifyEmailView();case"forgot-password":return this.renderForgotPasswordView();case"reset-password":return this.renderResetPasswordView();case"loading":default:return`<p class="${n}__copy">${this.escape(this.labels.common.loading)}</p>`}}renderSignInView(){var i,r;const e=this.renderOAuthProviders(),t=((i=this.config)==null?void 0:i.emailPasswordEnabled)??!0;return`
15
- <section class="${n}__section">
16
- <header class="${n}__header">
17
- <h1 class="${n}__title">${this.escape(this.labels.signIn.title)}</h1>
18
- <p class="${n}__copy">${this.escape(this.labels.signIn.subtitle)}</p>
14
+ `}renderStatus(){const e=[];return this.state.error&&e.push(`<div class="${r}__status ${r}__status--error">${this.escape(this.state.error)}</div>`),this.state.notice&&e.push(`<div class="${r}__status ${r}__status--info">${this.escape(this.state.notice)}</div>`),this.state.busy&&this.state.busyLabel&&e.push(`<div class="${r}__status ${r}__status--muted">${this.escape(this.state.busyLabel)}</div>`),e.join("")}renderCurrentView(){switch(this.state.view){case"sign-in":return this.renderSignInView();case"sign-up":return this.renderSignUpView();case"verify-email":return this.renderVerifyEmailView();case"forgot-password":return this.renderForgotPasswordView();case"reset-password":return this.renderResetPasswordView();case"loading":default:return`<p class="${r}__copy">${this.escape(this.labels.common.loading)}</p>`}}renderSignInView(){var i,n;const e=this.renderOAuthProviders(),s=((i=this.config)==null?void 0:i.emailPasswordEnabled)??!0;return`
15
+ <section class="${r}__section">
16
+ <header class="${r}__header">
17
+ <h1 class="${r}__title">${this.escape(this.labels.signIn.title)}</h1>
18
+ <p class="${r}__copy">${this.escape(this.labels.signIn.subtitle)}</p>
19
19
  </header>
20
20
  ${e}
21
- ${e&&t?`<div class="${n}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>`:""}
22
- ${t?`
23
- <form class="${n}__form" data-view="sign-in" novalidate>
21
+ ${e&&s?`<div class="${r}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>`:""}
22
+ ${s?`
23
+ <form class="${r}__form" data-view="sign-in" novalidate>
24
24
  ${this.renderInput("email",this.labels.signIn.emailLabel,"email",this.state.email,"email")}
25
25
  ${this.renderInput("password",this.labels.signIn.passwordLabel,"password",this.state.password,"current-password")}
26
- <button class="${n}__button ${n}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
26
+ <button class="${r}__button ${r}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
27
27
  ${this.escape(this.labels.signIn.submitButton)}
28
28
  </button>
29
29
  </form>
30
- <div class="${n}__actions">
30
+ <div class="${r}__actions">
31
31
  ${this.canUsePasswordResetEmailOtp()?`
32
- <button class="${n}__link" type="button" data-action="forgot-password" ${this.state.busy?"disabled":""}>
32
+ <button class="${r}__link" type="button" data-action="forgot-password" ${this.state.busy?"disabled":""}>
33
33
  ${this.escape(this.labels.signIn.forgotPassword)}
34
34
  </button>
35
35
  `:""}
36
- ${(r=this.config)!=null&&r.disableSignUp?"":`
37
- <p class="${n}__meta">
36
+ ${(n=this.config)!=null&&n.disableSignUp?"":`
37
+ <p class="${r}__meta">
38
38
  ${this.escape(this.labels.signIn.signUpPrompt)}
39
- <button class="${n}__link" type="button" data-action="switch-sign-up" ${this.state.busy?"disabled":""}>
39
+ <button class="${r}__link" type="button" data-action="switch-sign-up" ${this.state.busy?"disabled":""}>
40
40
  ${this.escape(this.labels.signIn.switchToSignUp)}
41
41
  </button>
42
42
  </p>
@@ -45,103 +45,103 @@
45
45
  `:""}
46
46
  </section>
47
47
  `}renderSignUpView(){const e=this.renderOAuthProviders();return`
48
- <section class="${n}__section">
49
- <header class="${n}__header">
50
- <h1 class="${n}__title">${this.escape(this.labels.signUp.title)}</h1>
51
- <p class="${n}__copy">${this.escape(this.labels.signUp.subtitle)}</p>
48
+ <section class="${r}__section">
49
+ <header class="${r}__header">
50
+ <h1 class="${r}__title">${this.escape(this.labels.signUp.title)}</h1>
51
+ <p class="${r}__copy">${this.escape(this.labels.signUp.subtitle)}</p>
52
52
  </header>
53
53
  ${e}
54
- ${e?`<div class="${n}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>`:""}
55
- <form class="${n}__form" data-view="sign-up" novalidate>
54
+ ${e?`<div class="${r}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>`:""}
55
+ <form class="${r}__form" data-view="sign-up" novalidate>
56
56
  ${this.renderInput("name",this.labels.signUp.nameLabel,"text",this.state.name,"name")}
57
57
  ${this.renderInput("email",this.labels.signUp.emailLabel,"email",this.state.email,"email")}
58
58
  ${this.renderInput("password",this.labels.signUp.passwordLabel,"password",this.state.password,"new-password")}
59
59
  ${this.renderInput("confirmPassword",this.labels.signUp.confirmPasswordLabel,"password",this.state.confirmPassword,"new-password")}
60
- <button class="${n}__button ${n}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
60
+ <button class="${r}__button ${r}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
61
61
  ${this.escape(this.labels.signUp.submitButton)}
62
62
  </button>
63
63
  </form>
64
- <p class="${n}__meta">
64
+ <p class="${r}__meta">
65
65
  ${this.escape(this.labels.signUp.signInPrompt)}
66
- <button class="${n}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
66
+ <button class="${r}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
67
67
  ${this.escape(this.labels.signUp.switchToSignIn)}
68
68
  </button>
69
69
  </p>
70
70
  </section>
71
71
  `}renderVerifyEmailView(){const e=this.countdownText(this.labels.verifyEmail.resendButton,this.labels.verifyEmail.resendCountdown);return`
72
- <section class="${n}__section">
73
- <header class="${n}__header">
74
- <h1 class="${n}__title">${this.escape(this.labels.verifyEmail.title)}</h1>
75
- <p class="${n}__copy">${this.escape(this.labels.verifyEmail.subtitle)}</p>
72
+ <section class="${r}__section">
73
+ <header class="${r}__header">
74
+ <h1 class="${r}__title">${this.escape(this.labels.verifyEmail.title)}</h1>
75
+ <p class="${r}__copy">${this.escape(this.labels.verifyEmail.subtitle)}</p>
76
76
  </header>
77
- <p class="${n}__copy">
77
+ <p class="${r}__copy">
78
78
  <strong>${this.escape(this.labels.verifyEmail.sentToLabel)}:</strong>
79
79
  ${this.escape(this.state.email)}
80
80
  </p>
81
- <div class="${n}__stack">
82
- <button class="${n}__button ${n}__button--secondary" type="button" data-action="resend-verification" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
81
+ <div class="${r}__stack">
82
+ <button class="${r}__button ${r}__button--secondary" type="button" data-action="resend-verification" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
83
83
  ${this.escape(e)}
84
84
  </button>
85
- <button class="${n}__link" type="button" data-action="use-different-email" ${this.state.busy?"disabled":""}>
85
+ <button class="${r}__link" type="button" data-action="use-different-email" ${this.state.busy?"disabled":""}>
86
86
  ${this.escape(this.labels.verifyEmail.changeEmailButton)}
87
87
  </button>
88
88
  </div>
89
89
  </section>
90
90
  `}renderForgotPasswordView(){return`
91
- <section class="${n}__section">
92
- <header class="${n}__header">
93
- <h1 class="${n}__title">${this.escape(this.labels.forgotPassword.title)}</h1>
94
- <p class="${n}__copy">${this.escape(this.labels.forgotPassword.subtitle)}</p>
91
+ <section class="${r}__section">
92
+ <header class="${r}__header">
93
+ <h1 class="${r}__title">${this.escape(this.labels.forgotPassword.title)}</h1>
94
+ <p class="${r}__copy">${this.escape(this.labels.forgotPassword.subtitle)}</p>
95
95
  </header>
96
- <form class="${n}__form" data-view="forgot-password" novalidate>
96
+ <form class="${r}__form" data-view="forgot-password" novalidate>
97
97
  ${this.renderInput("email",this.labels.forgotPassword.emailLabel,"email",this.state.email,"email")}
98
- <button class="${n}__button ${n}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
98
+ <button class="${r}__button ${r}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
99
99
  ${this.escape(this.labels.forgotPassword.submitButton)}
100
100
  </button>
101
101
  </form>
102
- <button class="${n}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
102
+ <button class="${r}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
103
103
  ${this.escape(this.labels.common.backToSignIn)}
104
104
  </button>
105
105
  </section>
106
106
  `}renderResetPasswordView(){const e=this.countdownText(this.labels.resetPassword.resendCodeButton,this.labels.resetPassword.resendCountdown);return`
107
- <section class="${n}__section">
108
- <header class="${n}__header">
109
- <h1 class="${n}__title">${this.escape(this.labels.resetPassword.title)}</h1>
110
- <p class="${n}__copy">${this.escape(this.labels.resetPassword.subtitle)}</p>
107
+ <section class="${r}__section">
108
+ <header class="${r}__header">
109
+ <h1 class="${r}__title">${this.escape(this.labels.resetPassword.title)}</h1>
110
+ <p class="${r}__copy">${this.escape(this.labels.resetPassword.subtitle)}</p>
111
111
  </header>
112
- <form class="${n}__form" data-view="reset-password" novalidate>
112
+ <form class="${r}__form" data-view="reset-password" novalidate>
113
113
  ${this.renderInput("code",this.labels.resetPassword.codeLabel,"text",this.state.code,"one-time-code")}
114
114
  ${this.renderInput("newPassword",this.labels.resetPassword.newPasswordLabel,"password",this.state.newPassword,"new-password")}
115
115
  ${this.renderInput("confirmPassword",this.labels.resetPassword.confirmPasswordLabel,"password",this.state.confirmPassword,"new-password")}
116
- <button class="${n}__button ${n}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
116
+ <button class="${r}__button ${r}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
117
117
  ${this.escape(this.labels.resetPassword.submitButton)}
118
118
  </button>
119
119
  </form>
120
- <button class="${n}__button ${n}__button--secondary" type="button" data-action="resend-reset-code" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
120
+ <button class="${r}__button ${r}__button--secondary" type="button" data-action="resend-reset-code" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
121
121
  ${this.escape(e)}
122
122
  </button>
123
- <button class="${n}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
123
+ <button class="${r}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
124
124
  ${this.escape(this.labels.common.backToSignIn)}
125
125
  </button>
126
126
  </section>
127
- `}renderOAuthProviders(){var t;const e=((t=this.config)==null?void 0:t.oauthProviders)??[];return e.length===0?"":`
128
- <div class="${n}__stack">
127
+ `}renderOAuthProviders(){var s;const e=((s=this.config)==null?void 0:s.oauthProviders)??[];return e.length===0?"":`
128
+ <div class="${r}__stack">
129
129
  ${e.map(i=>`
130
- <button class="${n}__button ${n}__button--secondary" type="button" data-action="oauth" data-provider="${i}" ${this.state.busy?"disabled":""}>
131
- ${this.escape(`${this.labels.oauth.continueWith} ${q[i]}`)}
130
+ <button class="${r}__button ${r}__button--secondary" type="button" data-action="oauth" data-provider="${i}" ${this.state.busy?"disabled":""}>
131
+ ${this.escape(`${this.labels.oauth.continueWith} ${J[i]}`)}
132
132
  </button>
133
133
  `).join("")}
134
134
  </div>
135
- `}renderInput(e,t,i,r,o){return`
136
- <label class="${n}__field">
137
- <span class="${n}__label">${this.escape(t)}</span>
135
+ `}renderInput(e,s,i,n,a){return`
136
+ <label class="${r}__field">
137
+ <span class="${r}__label">${this.escape(s)}</span>
138
138
  <input
139
- class="${n}__input"
139
+ class="${r}__input"
140
140
  name="${this.escape(e)}"
141
141
  type="${this.escape(i)}"
142
- value="${this.escape(r)}"
143
- autocomplete="${this.escape(o)}"
142
+ value="${this.escape(n)}"
143
+ autocomplete="${this.escape(a)}"
144
144
  ${this.state.busy?"disabled":""}
145
145
  />
146
146
  </label>
147
- `}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(r=>{r.addEventListener("submit",o=>{o.preventDefault();const u=r.dataset.view;u==="sign-in"&&this.handleSignIn(),u==="sign-up"&&this.handleSignUp(),u==="forgot-password"&&this.handleForgotPassword(),u==="reset-password"&&this.handleResetPassword()})}),this.root.querySelectorAll("input[name]").forEach(r=>{r.addEventListener("input",()=>{ve(r.name)&&(this.state[r.name]=r.value)})}),this.root.querySelectorAll("[data-action]").forEach(r=>{r.addEventListener("click",()=>{const o=r.dataset.action;o==="switch-sign-up"&&this.switchView("sign-up"),o==="switch-sign-in"&&this.switchView("sign-in"),o==="forgot-password"&&this.switchView("forgot-password"),o==="resend-verification"&&this.resendVerificationEmail(),o==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),o==="resend-reset-code"&&this.resendResetCode(),o==="oauth"&&this.handleOAuthSignIn(r.dataset.provider)})})}switchView(e){this.clearCountdown(),e!=="verify-email"&&(this.verificationCompletionAction=null),this.state.view=e,this.state.error=null,this.state.notice=null,this.state.busy=!1,this.state.busyLabel=void 0,this.terminalActionInProgress=!1,this.render()}async handleSignIn(){if(!H(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}await this.runAction("Signing in…",async()=>{const e=await this.auth.signIn.email({email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(I,this.state.email.trim())});if(e.error)throw e.error;await this.completeAuth("sign-in")})}async handleSignUp(){var e,t;if(!this.state.name.trim()){this.failValidation(this.labels.errors.requiredField);return}if(!H(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}if(this.state.password.length<(((e=this.config)==null?void 0:e.minPasswordLength)??8)){this.failValidation(this.labels.errors.passwordTooShort.replace("{min}",String(((t=this.config)==null?void 0:t.minPasswordLength)??8)));return}if(this.state.password!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Creating account…",async()=>{var r;const i=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(g,this.state.email.trim())});if(i.error)throw i.error;if((r=this.config)!=null&&r.requireEmailVerification){this.verificationCompletionAction="sign-up",this.state.view="verify-email",this.state.notice="Check your inbox to verify your email address.",this.startCountdown();return}await this.completeAuth("sign-up",await this.resolveAuthCompletionData(i.data))})}async handleOAuthSignIn(e){await this.runAction(`Redirecting to ${q[e]}…`,async()=>{const t=await this.auth.signIn.social({provider:e,callbackURL:this.getManagedReturnURL("oauth"),errorCallbackURL:this.getManagedReturnURL("oauth")});if(t.error)throw t.error;const i=this.extractRedirectURL(t.data);if(!i)throw new d(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=`Opening ${q[e]}…`,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(i)})}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new d("Password reset via email OTP is not enabled for this project."));return}if(!H(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}await this.runAction("Sending reset code…",async()=>{const e=await this.passwordResetEndpoints().forgetPassword.emailOtp({email:this.state.email.trim()});if(e.error)throw e.error;this.state.view="reset-password",this.state.notice=`We sent a reset code to ${this.state.email.trim()}.`,this.startCountdown()})}async resendResetCode(){this.isCountdownActive()||await this.handleForgotPassword()}async handleResetPassword(){var e,t;if(!this.canUsePasswordResetEmailOtp()){this.handleError(new d("Password reset via email OTP is not enabled for this project."));return}if(!ge(this.state.code)){this.failValidation(this.labels.errors.invalidCode);return}if(!this.state.newPassword){this.failValidation(this.labels.errors.requiredField);return}if(this.state.newPassword.length<(((e=this.config)==null?void 0:e.minPasswordLength)??8)){this.failValidation(this.labels.errors.passwordTooShort.replace("{min}",String(((t=this.config)==null?void 0:t.minPasswordLength)??8)));return}if(this.state.newPassword!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const i=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(i.error)throw i.error;await this.completePasswordReset()})}async resendVerificationEmail(){await this.sendVerificationEmail(!1)}async sendVerificationEmail(e){!e&&this.isCountdownActive()||await this.runAction("Sending verification email…",async()=>{const t=await this.auth.sendVerificationEmail({email:this.state.email.trim(),callbackURL:this.getManagedReturnURL(this.verificationCompletionAction==="sign-up"?g:I,this.state.email.trim())});if(t.error)throw t.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,t){const i=await this.retryAuthCompletionDataIfNeeded(t??await this.resolveAuthCompletionData());if(!i.user||!i.session){if(i.lookupError&&R(this.options)){this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(V(this.options.redirectTo).toString());return}if(e==="sign-in")throw i.lookupError??new ee("Managed sign-in completed without an authenticated session.");this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.error=null,this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice="Account created. Sign in to continue.",this.render();return}const r={action:e,user:i.user,session:i.session};if(await this.syncPublicSessionBestEffort(),R(this.options)){this.terminalActionInProgress=!0,this.invokeRedirectModeSuccessHook(r),this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(V(this.options.redirectTo).toString());return}if(D(this.options)){this.destroy(),this.options.onSuccess(r);return}}async retryAuthCompletionDataIfNeeded(e){if(e.session)return e;let t=e.lookupError;for(let i=0;i<N;i++){await new Promise(r=>setTimeout(r,ie));try{const r=await C(this.auth);if(r.user&&r.session)return{user:r.user,session:r.session}}catch(r){t=r}}return{...e,lookupError:t??e.lookupError}}async syncPublicSessionBestEffort(){var e,t;try{await((t=(e=this.runtimeOptions)==null?void 0:e.syncPublicSession)==null?void 0:t.call(e))}catch{}}async resolveAuthCompletionData(e){try{const t=await C(this.auth),i=this.extractUser(e);return{user:t.user??i,session:t.session}}catch(t){return{user:this.extractUser(e),session:null,lookupError:t}}}async completePasswordReset(){const e={action:"password-reset",user:null,session:null};if(D(this.options)){this.destroy(),this.options.onSuccess(e);return}this.invokeRedirectModeSuccessHook(e),this.clearCountdown(),this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.newPassword="",this.state.code="",this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=null,this.state.notice="Password updated. Sign in with your new password.",this.render()}handleExistingSessionOnMount(e){if(R(this.options)){this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(V(this.options.redirectTo).toString());return}if(D(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new d("authUI.mount(container, { onSuccess }) cannot run while a session already exists. Check es.auth.getSession() before mounting controlled auth UI.")}async runAction(e,t){this.state.busy=!0,this.state.busyLabel=e,this.state.error=null,this.state.notice=null,this.render();try{await t()}catch(i){if(this.maybeHandleVerificationRequired(i))return;this.handleError(i);return}!this.destroyed&&!this.terminalActionInProgress&&(this.state.busy=!1,this.state.busyLabel=void 0,this.render())}maybeHandleVerificationRequired(e){return F(e).code!=="EMAIL_NOT_VERIFIED"?!1:(this.verificationCompletionAction="sign-in",this.state.view="verify-email",this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=null,this.state.notice=`Verify your email to finish signing in as ${this.state.email.trim()}.`,this.render(),this.sendVerificationEmail(!0),!0)}handleVerificationEmailSent(e,t){this.state.notice=t?`We sent another verification email to ${e}.`:`We sent a verification email to ${e}.`,this.startCountdown()}invokeRedirectModeSuccessHook(e){var t,i;if(!(!R(this.options)||!this.options.onSuccess))try{this.options.onSuccess(e)}catch(r){const o=F(r,"Post-auth callback failed.");try{(i=(t=this.options).onError)==null||i.call(t,o)}catch{}}}handleError(e,t){var r,o;const i=F(e,t);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=i.message,this.render(),(o=(r=this.options).onError)==null||o.call(r,i)}failValidation(e){this.state.error=e,this.state.notice=null,this.render()}getManagedReturnURL(e,t){if(!e)return window.location.href;const i=new URL(window.location.href);return i.searchParams.set(z,e),t?i.searchParams.set(T,t):i.searchParams.delete(T),i.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),t=e.searchParams.get(z),i=e.searchParams.get(T),r=t?e.searchParams.get("error"):null,o=t?e.searchParams.get("error_description"):null;return(t||i)&&(e.searchParams.delete(z),e.searchParams.delete(T),t&&(e.searchParams.delete("error"),e.searchParams.delete("error_description")),window.history.replaceState(null,"",e.toString())),{marker:t,email:i,error:r,errorDescription:o}}startCountdown(e=60){this.countdownUntil=Date.now()+e*1e3,this.countdownTimer&&window.clearInterval(this.countdownTimer),this.countdownTimer=window.setInterval(()=>{if(!this.isCountdownActive()){this.countdownTimer&&(window.clearInterval(this.countdownTimer),this.countdownTimer=null),this.render();return}this.render()},1e3)}clearCountdown(){this.countdownUntil=null,this.countdownTimer&&(window.clearInterval(this.countdownTimer),this.countdownTimer=null)}captureFocusSnapshot(){const e=document.activeElement;return!(e instanceof HTMLInputElement)||!this.root.contains(e)||!e.name?null:{name:e.name,type:e.type,selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}scheduleFocusRestore(){this.pendingFocusSnapshot&&(this.clearFocusRestoreTimer(),this.focusRestoreTimer=window.setTimeout(()=>{if(this.focusRestoreTimer=null,this.destroyed||!this.pendingFocusSnapshot)return;const e=this.pendingFocusSnapshot,t=`input[name="${this.escape(e.name)}"][type="${this.escape(e.type)}"]`,i=this.root.querySelector(t);if(!(!i||i.disabled)){if(i.focus(),e.selectionStart!==null&&e.selectionEnd!==null)try{i.setSelectionRange(e.selectionStart,e.selectionEnd)}catch{const r=i.value.length;i.setSelectionRange(r,r)}this.pendingFocusSnapshot=null}},0))}clearFocusRestoreTimer(){this.focusRestoreTimer!==null&&(window.clearTimeout(this.focusRestoreTimer),this.focusRestoreTimer=null)}passwordResetEndpoints(){return this.auth}extractRedirectURL(e){if(!e||typeof e!="object")return null;const t=e;return t.redirect&&typeof t.url=="string"&&t.url.length>0?t.url:null}extractUser(e){if(!e||typeof e!="object")return null;const t=e;return t.user&&typeof t.user=="object"?t.user:null}canUsePasswordResetEmailOtp(){var e;return!!((e=this.config)!=null&&e.passwordResetEmailOtpEnabled)}handleSessionlessManagedReturn(e){return e.email&&(this.state.email=e.email),e.marker===g&&!e.error?(this.verificationCompletionAction=null,this.clearCountdown(),this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.error=null,this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice="Account created. Sign in to continue.",this.render(),!0):e.marker===I||e.marker===g?(this.verificationCompletionAction=e.marker===g?"sign-up":"sign-in",this.state.view="verify-email",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,e.error||e.errorDescription?this.handleError(new m(e.errorDescription??"Verification failed. Request a new verification email and try again.",{code:e.error??"VERIFY_EMAIL_ERROR"})):this.render(),!0):e.marker===se&&(e.error||e.errorDescription)?(this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,this.handleError(new m(e.errorDescription??"OAuth sign-in failed.",{code:e.error??"OAUTH_ERROR"})),!0):!1}isCountdownActive(){return this.getCountdownSecondsRemaining()>0}getCountdownSecondsRemaining(){return this.countdownUntil?Math.max(0,Math.ceil((this.countdownUntil-Date.now())/1e3)):0}countdownText(e,t){const i=this.getCountdownSecondsRemaining();return i<=0?e:t.replace("{seconds}",String(i))}escape(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}}function Le(s){return"data"in s&&s.data?s.data:s}const ye=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],ne=2,Ee=500;async function Se(){const s=`${window.location.origin}${oe}/config`;let e;for(let t=0;t<=ne;t++)try{const i=await fetch(s,{method:"GET",credentials:"include"});if(!i.ok)throw new d(`Failed to load auth config: HTTP ${i.status}`);const r=await i.json();return Ce(Le(r))}catch(i){e=i,t<ne&&await new Promise(r=>setTimeout(r,Ee))}throw e}let $=null;async function _e(){return $||($=Se().catch(s=>{throw $=null,s})),$}function Ce(s){var t,i,r,o,u,w,S;const e=ye.filter(({key:c})=>{const a=s[c];return typeof a=="object"&&a!==null&&"enabled"in a&&!!a.enabled}).map(({id:c})=>c);return{disableSignUp:!!s.disableSignUp,emailPasswordEnabled:!!((t=s.providerEmailPassword)!=null&&t.enabled),minPasswordLength:((r=(i=s.providerEmailPassword)==null?void 0:i.config)==null?void 0:r.minPasswordLength)??8,requireEmailVerification:!!((u=(o=s.providerEmailPassword)==null?void 0:o.config)!=null&&u.requireEmailVerification),passwordResetEmailOtpEnabled:!!((S=(w=s.providerEmailPassword)==null?void 0:w.config)!=null&&S.requirePasswordResetEmailVerification),oauthProviders:e}}const U=new WeakMap;function Te(s){if(!s)throw new d("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");const e="redirectTo"in s,t="onSuccess"in s&&typeof s.onSuccess=="function";if(!e&&!t)throw new d("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");if("redirectTo"in s){const i=s.redirectTo;if(!(typeof i=="string"||i instanceof URL))throw new d("authUI.mount(container, options) expected redirectTo to be a string or URL.")}if("onSuccess"in s&&s.onSuccess!==void 0&&typeof s.onSuccess!="function")throw new d("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in s&&s.onError!==void 0&&typeof s.onError!="function")throw new d("authUI.mount(container, options) expected onError to be a function.")}function Ie(s){if(!(s instanceof HTMLElement))throw new d("authUI.mount(container, options) requires a real HTMLElement container.")}function Re(s,e){return{mount(t,i){var w;Te(i),Ie(t),(w=U.get(t))==null||w.destroy();const r=new Pe(t,s,i,_e,e),o=r.destroy.bind(r),u={destroy(){o(),U.get(t)===u&&U.delete(t)}};return U.set(t,u),u}}}function $e(){re();const s=we(),e=be(),t=he(),i=Re(e,{syncPublicSession:async()=>{await me(s)}});return{auth:s,api:t,authUI:i}}exports.EdgeSparkAuthError=m;exports.EdgeSparkConfigError=d;exports.EdgeSparkError=k;exports.EdgeSparkRuntimeError=ee;exports.ar=Q;exports.createEdgeSpark=$e;exports.de=K;exports.detectLocale=le;exports.enUS=E;exports.es=B;exports.fr=Y;exports.hi=X;exports.it=J;exports.ja=W;exports.ko=j;exports.ptBR=G;exports.ru=Z;exports.zhCN=A;
147
+ `}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(n=>{n.addEventListener("submit",a=>{a.preventDefault();const m=n.dataset.view;m==="sign-in"&&this.handleSignIn(),m==="sign-up"&&this.handleSignUp(),m==="forgot-password"&&this.handleForgotPassword(),m==="reset-password"&&this.handleResetPassword()})}),this.root.querySelectorAll("input[name]").forEach(n=>{n.addEventListener("input",()=>{nt(n.name)&&(this.state[n.name]=n.value)})}),this.root.querySelectorAll("[data-action]").forEach(n=>{n.addEventListener("click",()=>{const a=n.dataset.action;a==="switch-sign-up"&&this.switchView("sign-up"),a==="switch-sign-in"&&this.switchView("sign-in"),a==="forgot-password"&&this.switchView("forgot-password"),a==="resend-verification"&&this.resendVerificationEmail(),a==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),a==="resend-reset-code"&&this.resendResetCode(),a==="oauth"&&this.handleOAuthSignIn(n.dataset.provider)})})}switchView(e){this.clearCountdown(),e!=="verify-email"&&(this.verificationCompletionAction=null),this.state.view=e,this.state.error=null,this.state.notice=null,this.state.busy=!1,this.state.busyLabel=void 0,this.terminalActionInProgress=!1,this.render()}async handleSignIn(){if(!Q(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}await this.runAction("Signing in…",async()=>{const e=await this.auth.signIn.email({email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(V,this.state.email.trim())});if(e.error)throw e.error;await this.completeAuth("sign-in")})}async handleSignUp(){var e,s;if(!this.state.name.trim()){this.failValidation(this.labels.errors.requiredField);return}if(!Q(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}if(this.state.password.length<(((e=this.config)==null?void 0:e.minPasswordLength)??8)){this.failValidation(this.labels.errors.passwordTooShort.replace("{min}",String(((s=this.config)==null?void 0:s.minPasswordLength)??8)));return}if(this.state.password!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Creating account…",async()=>{var n;const i=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(I,this.state.email.trim())});if(i.error)throw i.error;if((n=this.config)!=null&&n.requireEmailVerification){this.verificationCompletionAction="sign-up",this.state.view="verify-email",this.state.notice="Check your inbox to verify your email address.",this.startCountdown();return}await this.completeAuth("sign-up",await this.resolveAuthCompletionData(i.data))})}async handleOAuthSignIn(e){await this.runAction(`Redirecting to ${J[e]}…`,async()=>{const s=await this.auth.signIn.social({provider:e,callbackURL:this.getManagedReturnURL("oauth"),errorCallbackURL:this.getManagedReturnURL("oauth")});if(s.error)throw s.error;const i=this.extractRedirectURL(s.data);if(!i)throw new h(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=`Opening ${J[e]}…`,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(i)})}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new h("Password reset via email OTP is not enabled for this project."));return}if(!Q(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}await this.runAction("Sending reset code…",async()=>{const e=await this.passwordResetEndpoints().forgetPassword.emailOtp({email:this.state.email.trim()});if(e.error)throw e.error;this.state.view="reset-password",this.state.notice=`We sent a reset code to ${this.state.email.trim()}.`,this.startCountdown()})}async resendResetCode(){this.isCountdownActive()||await this.handleForgotPassword()}async handleResetPassword(){var e,s;if(!this.canUsePasswordResetEmailOtp()){this.handleError(new h("Password reset via email OTP is not enabled for this project."));return}if(!it(this.state.code)){this.failValidation(this.labels.errors.invalidCode);return}if(!this.state.newPassword){this.failValidation(this.labels.errors.requiredField);return}if(this.state.newPassword.length<(((e=this.config)==null?void 0:e.minPasswordLength)??8)){this.failValidation(this.labels.errors.passwordTooShort.replace("{min}",String(((s=this.config)==null?void 0:s.minPasswordLength)??8)));return}if(this.state.newPassword!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const i=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(i.error)throw i.error;await this.completePasswordReset()})}async resendVerificationEmail(){await this.sendVerificationEmail(!1)}async sendVerificationEmail(e){!e&&this.isCountdownActive()||await this.runAction("Sending verification email…",async()=>{const s=await this.auth.sendVerificationEmail({email:this.state.email.trim(),callbackURL:this.getManagedReturnURL(this.verificationCompletionAction==="sign-up"?I:V,this.state.email.trim())});if(s.error)throw s.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,s){const i=await this.retryAuthCompletionDataIfNeeded(s??await this.resolveAuthCompletionData());if(this.destroyed)return;if(!i.user||!i.session){if(this.destroyed)return;if(i.lookupError&&C(this.options)){this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(k(this.options.redirectTo).toString());return}if(e==="sign-in")throw i.lookupError??new ce("Managed sign-in completed without an authenticated session.");this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.error=null,this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice="Account created. Sign in to continue.",this.render();return}const n={action:e,user:i.user,session:i.session};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(C(this.options)){this.terminalActionInProgress=!0,this.invokeRedirectModeSuccessHook(n),this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(k(this.options.redirectTo).toString());return}if(Z(this.options)){this.options.onSuccess(n),this.terminalActionInProgress=!0;return}}}async retryAuthCompletionDataIfNeeded(e){if(e.session)return e;let s=e.lookupError;for(let i=0;i<K;i++){await new Promise(n=>setTimeout(n,ve));try{const n=await M(this.auth);if(n.user&&n.session)return{user:n.user,session:n.session}}catch(n){s=n}}return{...e,lookupError:s??e.lookupError}}async syncPublicSessionBestEffort(){var e,s;try{await((s=(e=this.runtimeOptions)==null?void 0:e.syncPublicSession)==null?void 0:s.call(e))}catch{}}async resolveAuthCompletionData(e){try{const s=await M(this.auth),i=this.extractUser(e);return{user:s.user??i,session:s.session}}catch(s){return{user:this.extractUser(e),session:null,lookupError:s}}}async completePasswordReset(){const e={action:"password-reset",user:null,session:null};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(Z(this.options)){this.clearCountdown(),this.options.onSuccess(e),this.terminalActionInProgress=!0;return}this.invokeRedirectModeSuccessHook(e),this.clearCountdown(),this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.newPassword="",this.state.code="",this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=null,this.state.notice="Password updated. Sign in with your new password.",this.render()}}handleExistingSessionOnMount(e){if(C(this.options)){this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(k(this.options.redirectTo).toString());return}if(Z(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new h("authUI.mount(container, { onSuccess }) cannot run while a session already exists. Check es.auth.getSession() before mounting controlled auth UI.")}async runAction(e,s){this.state.busy=!0,this.state.busyLabel=e,this.state.error=null,this.state.notice=null,this.render();try{await s()}catch(i){if(this.maybeHandleVerificationRequired(i))return;this.handleError(i);return}!this.destroyed&&!this.terminalActionInProgress&&(this.state.busy=!1,this.state.busyLabel=void 0,this.render())}maybeHandleVerificationRequired(e){return G(e).code!=="EMAIL_NOT_VERIFIED"?!1:(this.verificationCompletionAction="sign-in",this.state.view="verify-email",this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=null,this.state.notice=`Verify your email to finish signing in as ${this.state.email.trim()}.`,this.render(),this.sendVerificationEmail(!0),!0)}handleVerificationEmailSent(e,s){this.state.notice=s?`We sent another verification email to ${e}.`:`We sent a verification email to ${e}.`,this.startCountdown()}invokeRedirectModeSuccessHook(e){var s,i;if(!(!C(this.options)||!this.options.onSuccess))try{this.options.onSuccess(e)}catch(n){const a=G(n,"Post-auth callback failed.");try{(i=(s=this.options).onError)==null||i.call(s,a)}catch{}}}handleError(e,s){var n,a;const i=G(e,s);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=i.message,this.render(),(a=(n=this.options).onError)==null||a.call(n,i)}failValidation(e){this.state.error=e,this.state.notice=null,this.render()}getManagedReturnURL(e,s){if(!e)return window.location.href;const i=new URL(window.location.href);return i.searchParams.set(Y,e),s?i.searchParams.set(O,s):i.searchParams.delete(O),i.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),s=e.searchParams.get(Y),i=e.searchParams.get(O),n=s?e.searchParams.get("error"):null,a=s?e.searchParams.get("error_description"):null;return(s||i)&&(e.searchParams.delete(Y),e.searchParams.delete(O),s&&(e.searchParams.delete("error"),e.searchParams.delete("error_description")),window.history.replaceState(null,"",e.toString())),{marker:s,email:i,error:n,errorDescription:a}}startCountdown(e=60){this.countdownUntil=Date.now()+e*1e3,this.countdownTimer&&window.clearInterval(this.countdownTimer),this.countdownTimer=window.setInterval(()=>{if(!this.isCountdownActive()){this.countdownTimer&&(window.clearInterval(this.countdownTimer),this.countdownTimer=null),this.render();return}this.render()},1e3)}clearCountdown(){this.countdownUntil=null,this.countdownTimer&&(window.clearInterval(this.countdownTimer),this.countdownTimer=null)}captureFocusSnapshot(){const e=document.activeElement;return!(e instanceof HTMLInputElement)||!this.root.contains(e)||!e.name?null:{name:e.name,type:e.type,selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}scheduleFocusRestore(){this.pendingFocusSnapshot&&(this.clearFocusRestoreTimer(),this.focusRestoreTimer=window.setTimeout(()=>{if(this.focusRestoreTimer=null,this.destroyed||!this.pendingFocusSnapshot)return;const e=this.pendingFocusSnapshot,s=`input[name="${this.escape(e.name)}"][type="${this.escape(e.type)}"]`,i=this.root.querySelector(s);if(!(!i||i.disabled)){if(i.focus(),e.selectionStart!==null&&e.selectionEnd!==null)try{i.setSelectionRange(e.selectionStart,e.selectionEnd)}catch{const n=i.value.length;i.setSelectionRange(n,n)}this.pendingFocusSnapshot=null}},0))}clearFocusRestoreTimer(){this.focusRestoreTimer!==null&&(window.clearTimeout(this.focusRestoreTimer),this.focusRestoreTimer=null)}passwordResetEndpoints(){return this.auth}extractRedirectURL(e){if(!e||typeof e!="object")return null;const s=e;return s.redirect&&typeof s.url=="string"&&s.url.length>0?s.url:null}extractUser(e){if(!e||typeof e!="object")return null;const s=e;return s.user&&typeof s.user=="object"?s.user:null}canUsePasswordResetEmailOtp(){var e;return!!((e=this.config)!=null&&e.passwordResetEmailOtpEnabled)}handleSessionlessManagedReturn(e){return e.email&&(this.state.email=e.email),e.marker===I&&!e.error?(this.verificationCompletionAction=null,this.clearCountdown(),this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.error=null,this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice="Account created. Sign in to continue.",this.render(),!0):e.marker===V||e.marker===I?(this.verificationCompletionAction=e.marker===I?"sign-up":"sign-in",this.state.view="verify-email",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,e.error||e.errorDescription?this.handleError(new g(e.errorDescription??"Verification failed. Request a new verification email and try again.",{code:e.error??"VERIFY_EMAIL_ERROR"})):this.render(),!0):e.marker===ye&&(e.error||e.errorDescription)?(this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,this.handleError(new g(e.errorDescription??"OAuth sign-in failed.",{code:e.error??"OAUTH_ERROR"})),!0):!1}isCountdownActive(){return this.getCountdownSecondsRemaining()>0}getCountdownSecondsRemaining(){return this.countdownUntil?Math.max(0,Math.ceil((this.countdownUntil-Date.now())/1e3)):0}countdownText(e,s){const i=this.getCountdownSecondsRemaining();return i<=0?e:s.replace("{seconds}",String(i))}escape(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}}function at(t){return"data"in t&&t.data?t.data:t}const lt=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],Se=2,dt=500;async function ct(){const t=`${window.location.origin}${Ee}/config`;let e;for(let s=0;s<=Se;s++)try{const i=await fetch(t,{method:"GET",credentials:"include"});if(!i.ok)throw new h(`Failed to load auth config: HTTP ${i.status}`);const n=await i.json();return ht(at(n))}catch(i){e=i,s<Se&&await new Promise(n=>setTimeout(n,dt))}throw e}let N=null;async function ut(){return N||(N=ct().catch(t=>{throw N=null,t})),N}function ht(t){var s,i,n,a,m,w,P;const e=lt.filter(({key:E})=>{const L=t[E];return typeof L=="object"&&L!==null&&"enabled"in L&&!!L.enabled}).map(({id:E})=>E);return{disableSignUp:!!t.disableSignUp,emailPasswordEnabled:!!((s=t.providerEmailPassword)!=null&&s.enabled),minPasswordLength:((n=(i=t.providerEmailPassword)==null?void 0:i.config)==null?void 0:n.minPasswordLength)??8,requireEmailVerification:!!((m=(a=t.providerEmailPassword)==null?void 0:a.config)!=null&&m.requireEmailVerification),passwordResetEmailOtpEnabled:!!((P=(w=t.providerEmailPassword)==null?void 0:w.config)!=null&&P.requirePasswordResetEmailVerification),oauthProviders:e}}const F=new WeakMap;function mt(t){if(!t)throw new h("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");const e="redirectTo"in t,s="onSuccess"in t&&typeof t.onSuccess=="function";if(!e&&!s)throw new h("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");if("redirectTo"in t){const i=t.redirectTo;if(!(typeof i=="string"||i instanceof URL))throw new h("authUI.mount(container, options) expected redirectTo to be a string or URL.")}if("onSuccess"in t&&t.onSuccess!==void 0&&typeof t.onSuccess!="function")throw new h("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in t&&t.onError!==void 0&&typeof t.onError!="function")throw new h("authUI.mount(container, options) expected onError to be a function.")}function ft(t){if(!(t instanceof HTMLElement))throw new h("authUI.mount(container, options) requires a real HTMLElement container.")}function wt(t,e){return{mount(s,i){var w;mt(i),ft(s),(w=F.get(s))==null||w.destroy();const n=new ot(s,t,i,ut,e),a=n.destroy.bind(n),m={destroy(){a(),F.get(s)===m&&F.delete(s)}};return F.set(s,m),m}}}function gt(){Pe();const t=Xe(),e=et(),s=Oe(),i=wt(e,{syncPublicSession:async()=>{await Qe(t)}});return{auth:t,api:s,authUI:i}}exports.EdgeSparkAuthError=g;exports.EdgeSparkConfigError=h;exports.EdgeSparkError=q;exports.EdgeSparkRuntimeError=ce;exports.ar=le;exports.createEdgeSpark=gt;exports.de=re;exports.detectLocale=Re;exports.enUS=B;exports.es=D;exports.fr=ne;exports.hi=de;exports.it=oe;exports.ja=te;exports.ko=se;exports.ptBR=ie;exports.ru=ae;exports.zhCN=z;