@donotdev/auth 0.0.3 → 0.0.4

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.
Files changed (38) hide show
  1. package/dist/AuthStore.js +1 -1
  2. package/dist/FirebaseAccountLinking.js +1 -1
  3. package/dist/FirebaseAuth.js +1 -1
  4. package/dist/FirebaseSmartRecovery.js +1 -1
  5. package/dist/authHelpers.js +1 -1
  6. package/dist/components/AccountLinking.js +1 -1
  7. package/dist/components/AuthFallback.js +1 -1
  8. package/dist/components/AuthPartnerButton.js +2 -2
  9. package/dist/components/DeleteAccountDialogs.js +1 -1
  10. package/dist/components/EmailLinkForm.js +1 -1
  11. package/dist/components/EmailPasswordForm.js +1 -1
  12. package/dist/components/EmailVerification.js +1 -1
  13. package/dist/components/Feature.js +1 -1
  14. package/dist/components/FeatureGuard.js +1 -1
  15. package/dist/components/FeaturePlaceholder.js +1 -1
  16. package/dist/components/GoogleOneTap.js +1 -1
  17. package/dist/components/LoginModal.js +1 -1
  18. package/dist/components/MultipleAuthProviders.js +1 -1
  19. package/dist/components/NetworkStatusIndicator.js +1 -1
  20. package/dist/components/PasswordUpdateDialog.js +1 -1
  21. package/dist/components/RateLimitAlert.js +1 -1
  22. package/dist/components/index.js +1 -1
  23. package/dist/constants.js +1 -1
  24. package/dist/hooks/useAccountLinking.js +1 -1
  25. package/dist/hooks/useAuthMethodToggle.js +1 -1
  26. package/dist/hooks/useAuthPartner.js +1 -1
  27. package/dist/hooks/useDeleteAccount.js +1 -1
  28. package/dist/hooks/useEmailLinkAuth.js +1 -1
  29. package/dist/hooks/useEmailLinkForm.js +1 -1
  30. package/dist/hooks/useFedCM.js +1 -1
  31. package/dist/hooks/useGoogleOneTap.d.ts.map +1 -1
  32. package/dist/hooks/useGoogleOneTap.js +1 -1
  33. package/dist/hooks/useNetworkStatus.js +1 -1
  34. package/dist/index.js +1 -1
  35. package/dist/tsconfig.tsbuildinfo +1 -1
  36. package/dist/useAuth.d.ts.map +1 -1
  37. package/dist/useAuth.js +1 -1
  38. package/package.json +5 -5
package/dist/AuthStore.js CHANGED
@@ -1 +1 @@
1
- import{createDoNotDevStore as n,FEATURE_STATUS as u}from"@donotdev/core";import{PARTNER_STATE as i}from"./constants";const o={user:null,authenticated:!1,userId:null,loading:!1,error:null,userProfile:null,userSubscription:null,partnerStates:{},partnerError:null,authService:null,emailVerification:{status:"pending"},status:u.INITIALIZING},c=n({name:"auth-store",createStore:(t,a)=>({...o,setStatus:r=>{t({status:r})},setPartnerState:(r,e,s)=>{t(l=>({partnerStates:{...l.partnerStates,[r]:e},partnerError:e==="error"&&s?{partnerId:r,error:s}:l.partnerError?.partnerId===r?null:l.partnerError}))},getPartnerState:r=>a().partnerStates[r]||i.IDLE,clearAllPartnerStates:()=>t(r=>({partnerStates:Object.keys(r.partnerStates).reduce((e,s)=>(e[s]=i.IDLE,e),{}),partnerError:null})),setAuthenticated:(r,e,s)=>{t({user:r,authenticated:!0,userId:r.id,loading:!1,error:null,status:u.READY,userSubscription:e,userProfile:s})},setUnauthenticated:()=>{t({user:null,authenticated:!1,userId:null,loading:!1,error:null,status:u.READY,userSubscription:null,userProfile:null})},setAuthLoading:r=>{t({loading:r})},setAuthError:r=>{t({error:r,loading:!1})},clearAuthError:()=>{t({error:null})},getCustomClaim:r=>a().getCustomClaimLocal(r),getCustomClaims:()=>a().getCustomClaimsLocal(),setAuthService:r=>t({authService:r}),getCustomClaimLocal:r=>{const e=a();return e.userProfile?.claims&&r in e.userProfile.claims?e.userProfile.claims[r]:e.userProfile&&r in e.userProfile?e.userProfile[r]:e.user&&r in e.user?e.user[r]:null},getCustomClaimsLocal:()=>{const r=a(),e={};return r.userProfile?.claims&&Object.assign(e,r.userProfile.claims),r.userProfile&&Object.assign(e,r.userProfile),r.user&&Object.assign(e,r.user),e},setEmailVerificationStatus:(r,e)=>t({emailVerification:{status:r,error:e}}),setUserProfile:r=>t({userProfile:r}),setUserSubscription:r=>t({userSubscription:r}),setLoading:r=>t({loading:r}),setError:r=>t({error:r}),clearError:()=>t({error:null}),reset:()=>t(o)})});export{c as useAuthStore};
1
+ import{createDoNotDevStore as o,FEATURE_STATUS as l}from"@donotdev/core";import{PARTNER_STATE as n}from"./constants";const i={user:null,authenticated:!1,userId:null,loading:!1,error:null,userProfile:null,userSubscription:null,partnerStates:{},partnerError:null,authService:null,emailVerification:{status:"pending"},status:l.INITIALIZING},S=o({name:"auth-store",createStore:(t,u)=>({...i,setStatus:r=>{t({status:r})},setPartnerState:(r,e,s)=>{t(a=>({partnerStates:{...a.partnerStates,[r]:e},partnerError:e==="error"&&s?{partnerId:r,error:s}:a.partnerError?.partnerId===r?null:a.partnerError}))},getPartnerState:r=>u().partnerStates[r]||n.IDLE,clearAllPartnerStates:()=>t(r=>({partnerStates:Object.keys(r.partnerStates).reduce((e,s)=>(e[s]=n.IDLE,e),{}),partnerError:null})),setAuthenticated:(r,e,s)=>{t({user:r,authenticated:!0,userId:r.id,loading:!1,error:null,status:l.READY,userSubscription:e,userProfile:s})},setUnauthenticated:()=>{t({user:null,authenticated:!1,userId:null,loading:!1,error:null,status:l.READY,userSubscription:null,userProfile:null})},setAuthLoading:r=>{t({loading:r})},setAuthError:r=>{t({error:r,loading:!1})},clearAuthError:()=>{t({error:null})},getCustomClaim:r=>u().getCustomClaimLocal(r),getCustomClaims:()=>u().getCustomClaimsLocal(),setAuthService:r=>t({authService:r}),getCustomClaimLocal:r=>{const e=u();return e.userProfile?.claims&&r in e.userProfile.claims?e.userProfile.claims[r]:e.userProfile&&r in e.userProfile?e.userProfile[r]:e.user&&r in e.user?e.user[r]:null},getCustomClaimsLocal:()=>{const r=u(),e={};return r.userProfile?.claims&&Object.assign(e,r.userProfile.claims),r.userProfile&&Object.assign(e,r.userProfile),r.user&&Object.assign(e,r.user),e},setEmailVerificationStatus:(r,e)=>t({emailVerification:{status:r,error:e}}),setUserProfile:r=>t({userProfile:r}),setUserSubscription:r=>t({userSubscription:r}),setLoading:r=>t({loading:r}),setError:r=>t({error:r}),clearError:()=>t({error:null}),reset:()=>t(i)})});export{S as useAuthStore};
@@ -1 +1 @@
1
- import{toast as r}from"@donotdev/components";import{safeSessionStorage as a}from"@donotdev/core";import{OAuthProvider as l}from"@donotdev/firebase";import{getAuthMethod as m}from"./constants";async function d(i,n,s,t){const o=i.customData?.email||i.email;if(!o)throw r("error","Could not determine account email"),i;const u=l.credentialFromError(i);if(u)try{const c=u.toJSON();a.setItem("originalCredential",JSON.stringify(c))}catch{}const e=await t.getExistingProvider(t.sdk,i,o);if(!e)throw r("error","Could not determine existing account type"),i;return e==="password"?await g(o,n,t):e==="emailLink"?await p(o,n,t):n==="password"&&e!=="password"?await w(o,e,s,t):n==="emailLink"&&e!=="emailLink"?await k(o,e,s,t):await f(o,e,s,n,t)}async function g(i,n,s){const t={email:i,existingProvider:"password",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(t)),r("info",`Please sign in with your password to link your ${n} account`),null}async function p(i,n,s){const t={email:i,existingProvider:"emailLink",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(t)),r("info",`Please check your email for a sign-in link to link your ${n} account`),null}async function f(i,n,s,t,o){r("info",`Account linking required. Signing you in with ${n} to link your ${t} account...`);const u={email:i,existingProvider:n,newProvider:t,timestamp:Date.now()};a.setItem("accountLinkingInfo",JSON.stringify(u));const e=o.createProviderFromConfig(n);if(m(s)==="popup"){r("info",`You have an existing ${n} account. Opening popup to link accounts...`);try{const c=await o.sdk.signInWithPopup(e);return o.createAuthResult(c.user,!1)}catch(c){throw c.code==="auth/popup-blocked"||c.code==="auth/popup-closed-by-user"?(r("error","Popup was blocked. Please allow popups for this site and try again, or use a different browser."),a.removeItem("accountLinkingInfo"),a.removeItem("originalCredential"),new Error("Popup blocked. Please allow popups to complete account linking in development mode.")):c}}else return r("info",`You have an existing ${n} account. Redirecting to link accounts...`),await o.sdk.signInWithRedirect(e),null}async function w(i,n,s,t){r("info","We can't automatically link password/email accounts. First sign in using your original method, then go to Profile \u2192 Link accounts to connect this provider.");const o={email:i,existingProvider:"password",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(o)),null}async function k(i,n,s,t){r("info","We can't automatically link password/email accounts. First sign in using your original method, then go to Profile \u2192 Link accounts to connect this provider.");const o={email:i,existingProvider:"emailLink",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(o)),null}function h(){a.removeItem("accountLinkingInfo"),a.removeItem("originalCredential")}export{h as clearAccountLinkingState,d as handleOAuthLinking};
1
+ import{toast as r}from"@donotdev/components";import{safeSessionStorage as a}from"@donotdev/core";import{OAuthProvider as g}from"@donotdev/firebase";import{getAuthMethod as m}from"./constants";async function v(i,n,c,o){const e=i.customData?.email||i.email;if(!e)throw r("error","Could not determine account email"),i;const l=g.credentialFromError(i);if(l)try{const u=l.toJSON();a.setItem("originalCredential",JSON.stringify(u))}catch{}const t=await o.getExistingProvider(o.sdk,i,e);if(!t)throw r("error","Could not determine existing account type"),i;return t==="password"?await d(e,n,o):t==="emailLink"?await f(e,n,o):n==="password"&&t!=="password"?await p(e,t,c,o):n==="emailLink"&&t!=="emailLink"?await h(e,t,c,o):await k(e,t,c,n,o)}async function d(i,n,c){const o={email:i,existingProvider:"password",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(o)),r("info",`Please sign in with your password to link your ${n} account`),null}async function f(i,n,c){const o={email:i,existingProvider:"emailLink",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(o)),r("info",`Please check your email for a sign-in link to link your ${n} account`),null}async function k(i,n,c,o,e){r("info",`Account linking required. Signing you in with ${n} to link your ${o} account...`);const l={email:i,existingProvider:n,newProvider:o,timestamp:Date.now()};a.setItem("accountLinkingInfo",JSON.stringify(l));const t=e.createProviderFromConfig(n);if(m(c)==="popup"){r("info",`You have an existing ${n} account. Opening popup to link accounts...`);try{const s=await e.sdk.signInWithPopup(t);return e.createAuthResult(s.user,!1)}catch(s){throw s.code==="auth/popup-blocked"||s.code==="auth/popup-closed-by-user"?(r("error","Popup was blocked. Please allow popups for this site and try again, or use a different browser."),a.removeItem("accountLinkingInfo"),a.removeItem("originalCredential"),new Error("Popup blocked. Please allow popups to complete account linking in development mode.")):s}}else return r("info",`You have an existing ${n} account. Redirecting to link accounts...`),await e.sdk.signInWithRedirect(t),null}async function p(i,n,c,o){r("info","We can't automatically link password/email accounts. First sign in using your original method, then go to Profile \u2192 Link accounts to connect this provider.");const e={email:i,existingProvider:"password",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(e)),null}async function h(i,n,c,o){r("info","We can't automatically link password/email accounts. First sign in using your original method, then go to Profile \u2192 Link accounts to connect this provider.");const e={email:i,existingProvider:"emailLink",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(e)),null}function O(){a.removeItem("accountLinkingInfo"),a.removeItem("originalCredential")}export{O as clearAccountLinkingState,v as handleOAuthLinking};
@@ -1 +1 @@
1
- import{toast as c}from"@donotdev/components";import{createSingleton as C,safeSessionStorage as h,handleError as n,isClient as g,ClaimsCache as R,getAuthPartnerIdByFirebaseId as f}from"@donotdev/core";import{AUTH_PARTNERS as m,SUBSCRIPTION_TIERS as k,createDefaultUserProfile as E}from"@donotdev/core";import{getFirebaseSDK as y,GoogleAuthProvider as v,GithubAuthProvider as b,FacebookAuthProvider as T,TwitterAuthProvider as L,OAuthProvider as p,EmailAuthProvider as N}from"@donotdev/firebase";import{getAuthMethod as w}from"./constants";import{PARTNER_STATE as o,EMAIL_VERIFICATION_STATUS as S}from"./constants";import{handleOAuthLinking as D,clearAccountLinkingState as F}from"./FirebaseAccountLinking";import{handleSmartRecovery as l}from"./FirebaseSmartRecovery";async function U(P,t,e){const i=p.credentialFromError(t),s=t.customData?._tokenResponse?.verifiedProvider?.[0]||i?.providerId||t.customData?.providerId;return s?f(s):null}class I{sdk;initialized=!1;store=null;popupTimeout=null;claimsCache=null;constructor(){this.sdk=y()}setStore(t){this.store=t}get storeState(){if(!this.store)throw new Error("[FirebaseAuth] Store not set. Call setStore() first.");return this.store}async initialize(){if(!this.initialized)try{await this.sdk.initialize();try{await this.processRedirectResult(!0)}catch(t){n(t,{userMessage:"Redirect processing failed",context:{operation:"processRedirectResult"},severity:"warning",showNotification:!1})}this.initialized=!0}catch(t){throw n(t,{userMessage:"Failed to initialize authentication",showNotification:!1})}}async processRedirectResult(t=!1){this.store&&this.store.setLoading(!0);try{const e=new Promise((s,r)=>setTimeout(()=>r(new Error("Redirect check timeout")),1e4)),i=await Promise.race([this.sdk.getRedirectResult(),e]).catch(s=>{if(s.message==="Redirect check timeout")return null;throw s});i?.user&&(await this.handleAuthStateChange(i.user),await this.checkPendingLinking(),h.removeItem("pendingAuthPartnerId"),c("success","Signed in successfully!"))}catch(e){if(e.code==="auth/account-exists-with-different-credential"){const i=p.credentialFromError(e)?.providerId||e.customData?._tokenResponse?.providerId,s=i?f(i):h.getItem("pendingAuthPartnerId");if(s)try{await l(e,()=>Promise.resolve(),{partnerId:s,method:"redirect"},this.getSmartRecoveryDeps());return}catch(r){n(r,{userMessage:"Failed to link accounts. Please try again.",showNotification:!t})}}if(n(e,{userMessage:"Authentication failed. Please try again.",showNotification:!t,context:{operation:"processRedirectResult"}}),e.code!=="auth/account-exists-with-different-credential")try{this.clearAccountLinkingState(),h.removeItem("pendingAuthPartnerId")}catch(i){n(i)}}finally{this.store&&this.store.setLoading(!1)}}ensureInitialized(){if(!this.initialized)throw new Error("FirebaseAuth not initialized. Call initialize() first.")}getAppConfig(){if(typeof globalThis<"u"){const t=globalThis._DNDEV_APP_CONFIG_;if(t)return t}return null}initializeClaimsCache(){if(this.claimsCache)return;const t=this.getAppConfig()?.features?.offlineTrustEnabled??!1;this.claimsCache=new R({offlineTrustEnabled:t,userId:this.storeState?.userId??null})}onAuthStateChanged(t){return this.sdk.onAuthStateChanged(async e=>{e?await this.handleAuthStateChange(e):this.handleSignOut(),e&&await this.checkPendingLinking();const i=e?this.convertToAuthUser(e):null;t(i)})}async handleAuthStateChange(t){if(!this.store)return;const e=this.convertToAuthUser(t);this.initializeClaimsCache(),this.claimsCache&&this.claimsCache.setUserId(e.id),this.storeState.clearAllPartnerStates();let i={userId:e.id,tier:k.FREE,status:"active",isActive:!0,features:[],subscriptionId:null,customerId:e.id,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{const r=await this.sdk.getIdTokenResult(t,!0);if(r?.claims?.subscription){const a=r.claims.subscription;i={userId:e.id,tier:a.tier||k.FREE,status:a.status||"active",isActive:a.status==="active",features:a.features||[],subscriptionId:a.subscriptionId||null,customerId:a.customerId||e.id,subscriptionEnd:a.subscriptionEnd||null,cancelAtPeriodEnd:!!a.cancelAtPeriodEnd,updatedAt:a.updatedAt||new Date().toISOString()}}}catch(r){r?.code==="auth/network-request-failed"||r?.originalCode==="auth/network-request-failed"||r?.message?.includes("network")||n(r,{userMessage:"Failed to get custom claims",context:{operation:"getCustomClaims"},severity:"warning"})}const s=E(e.id);this.storeState.setAuthenticated(e,i,s)}handleSignOut(){this.store&&(this.claimsCache&&this.claimsCache.setUserId(null),this.storeState.clearAllPartnerStates(),this.storeState.setUnauthenticated())}async signInWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.signInWithEmail(t,e);return c("success","Signed in successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user)}catch(i){if(i.code==="auth/user-not-found"){c("info","Creating your account...");try{const s=await this.sdk.createUserWithEmail(t,e);return c("success","Account created successfully!"),this.createAuthResult(s.user,!0)}catch(s){throw this.storeState.setPartnerState("password",o.ERROR),n(s,{userMessage:"Failed to create account",showNotification:!0})}}try{return await l(i,()=>this.sdk.signInWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps())}catch(s){throw this.storeState.setPartnerState("password",o.ERROR),s}}}async createUserWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.createUserWithEmail(t,e);return c("success","Account created successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user,!0)}catch(i){try{const s=await l(i,()=>this.sdk.createUserWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps());if(!s)throw new Error("Account creation failed");return s}catch(s){throw this.storeState.setPartnerState("password",o.ERROR),s}}}async signInWithPartner(t,e){const i=w(e);this.ensureInitialized(),this.storeState.setPartnerState(t,o.LOADING);try{const s=this.createProviderFromConfig(t);let r;return i==="popup"?(r=await this.handlePopupAuth(t,async()=>await this.sdk.signInWithPopup(s)),r===null?(this.storeState.setPartnerState(t,o.IDLE),null):(c("success","Signed in successfully!"),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(r.user))):(h.setItem("pendingAuthPartnerId",t),await this.sdk.signInWithRedirect(s),null)}catch(s){try{const r=await l(s,()=>{const a=this.createProviderFromConfig(t);return i==="popup"?this.sdk.signInWithPopup(a):this.sdk.signInWithRedirect(a)},{partnerId:t,method:i},this.getSmartRecoveryDeps());return r===null?(this.storeState.setPartnerState(t,o.IDLE),null):r}catch(r){throw this.storeState.setPartnerState(t,o.ERROR),r}}}async linkWithPartner(t,e){const i=w(e);this.ensureInitialized();const s=this.sdk.getCurrentUser();if(!s)throw n(new Error("No authenticated user"),{userMessage:"You must be signed in to link accounts",context:{operation:"linkWithPartner",partnerId:t},showNotification:!0});this.storeState.setPartnerState(t,o.LOADING);try{const r=this.createProviderFromConfig(t);if(i==="popup"){const a=await this.sdk.linkWithPopup(s,r);return c("success",`Successfully linked ${t} account!`),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(a.user)}else return await this.sdk.linkWithRedirect(s,r),null}catch(r){const a=r;let u="Failed to link account",d={operation:"linkWithPartner",partnerId:t,errorCode:a.code};switch(a.code){case"auth/operation-not-allowed":u="Account linking is disabled. Contact support for assistance.";break;case"auth/provider-already-linked":u="This account is already linked to your profile.";break;case"auth/credential-already-in-use":u="This account is already linked to another profile.";break;case"auth/requires-recent-login":u="Please sign out and sign back in, then try linking again.";break;default:u=`Failed to link ${t} account. Please try again.`}throw this.storeState.setPartnerState(t,o.ERROR),n(r,{userMessage:u,context:d,showNotification:!0})}}async handlePopupAuth(t,e){this.clearPopupMonitoring(),this.popupTimeout=setTimeout(()=>{this.storeState.setPartnerState(t,o.IDLE),this.clearPopupMonitoring()},3e4);try{const i=await e();return this.clearPopupMonitoring(),i}catch(i){if(this.clearPopupMonitoring(),i.code==="auth/popup-closed-by-user"||i.code==="auth/cancelled-popup-request")return null;throw i}}clearPopupMonitoring(){this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}async signInWithGoogleCredential(t){this.ensureInitialized(),this.storeState.setPartnerState("google",o.LOADING);try{const e=await this.sdk.signInWithGoogleCredential(t);return c("success","Signed in with Google!"),this.storeState.setPartnerState("google",o.IDLE),this.createAuthResult(e.user)}catch(e){try{return await l(e,()=>this.sdk.signInWithGoogleCredential(t),{partnerId:"google",method:"redirect"},this.getSmartRecoveryDeps())}catch(i){throw this.storeState.setPartnerState("google",o.ERROR),i}}}async getRedirectResult(){this.ensureInitialized();try{const t=await this.sdk.getRedirectResult();return t?.user?(c("success","Signed in successfully!"),this.createAuthResult(t.user)):null}catch(t){try{return await l(t,()=>this.sdk.getRedirectResult(),{method:"redirect"},this.getSmartRecoveryDeps())}catch(e){throw e}}}async checkPendingLinking(){const t=h.getItem("accountLinkingInfo"),e=h.getItem("originalCredential");if(!(!t||!e))try{const i=JSON.parse(t),s=JSON.parse(e),r=await this.sdk.getCurrentUser();if(!r)return;const a=this.convertToAuthUser(r),u=m[i.newProvider];if(!u)return;if(a.providerData?.some(A=>A.providerId===u.firebaseProviderId)){this.clearAccountLinkingState();return}const d=this.createCredentialFromStoredData(s);if(!d){this.clearAccountLinkingState();return}await this.sdk.linkWithCredential(r,d),this.clearAccountLinkingState(),c("success","Accounts linked successfully!")}catch(i){throw this.clearAccountLinkingState(),n(i,{userMessage:"Account linking failed",showNotification:!0})}}async sendSignInLinkToEmail(t,e){this.ensureInitialized();try{await this.sdk.sendSignInLinkToEmail(t,e||{url:"",handleCodeInApp:!1}),c("success","Sign-in link sent to your email!")}catch(i){throw n(i,{userMessage:"Failed to send sign-in link",showNotification:!0})}}async signInWithEmailLink(t,e){this.ensureInitialized(),this.storeState.setPartnerState("emailLink",o.LOADING);try{const i=await this.sdk.signInWithEmailLink(t,e);return c("success","Signed in successfully!"),this.storeState.setPartnerState("emailLink",o.IDLE),this.createAuthResult(i.user)}catch(i){try{return await l(i,()=>this.sdk.signInWithEmailLink(t,e),{email:t,partnerId:"emailLink"},this.getSmartRecoveryDeps())}catch(s){throw this.storeState.setPartnerState("emailLink",o.ERROR),s}}}isSignInWithEmailLink(t){if(!t&&!g())return!1;const e=t||(g()?window.location.href:"");return this.sdk.isSignInWithEmailLink(e)}async sendPasswordResetEmail(t){this.ensureInitialized();try{await this.sdk.sendPasswordResetEmail(t),c("success","Password reset email sent!")}catch(e){throw n(e,{userMessage:"Failed to send password reset email",showNotification:!0})}}async updatePassword(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)throw n(new Error("No authenticated user"),{userMessage:"You must be signed in to update your password",showNotification:!0});try{await this.sdk.updatePassword(e,t),c("success","Password updated successfully!")}catch(i){throw n(i,{userMessage:"Failed to update password",showNotification:!0})}}async sendEmailVerification(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();if(!t)throw n(new Error("No authenticated user"),{userMessage:"You must be signed in to verify your email",showNotification:!0});try{this.storeState.setEmailVerificationStatus(S.PENDING),await this.sdk.sendEmailVerification(t),c("success","Verification email sent!")}catch(e){throw this.storeState.setEmailVerificationStatus(S.PENDING),n(e,{userMessage:"Failed to send verification email",showNotification:!0})}}async getEmailVerificationStatus(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();return t?{status:t.emailVerified?"verified":"pending"}:{status:"pending",error:"No authenticated user"}}async isEmailVerificationEnabled(){return!0}async getIdTokenResult(t=!1){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)return null;try{return await this.sdk.getIdTokenResult(e,t)}catch(i){throw n(i,{userMessage:"Failed to get authentication token"})}}async getCustomClaims(){this.ensureInitialized(),this.initializeClaimsCache();const t=await this.sdk.getCurrentUser();if(!t)return{};if(!this.claimsCache)try{return(await this.sdk.getIdTokenResult(t,!0))?.claims||{}}catch(e){throw n(e,{userMessage:"Failed to get user permissions"})}return this.claimsCache.getClaims(async()=>(await this.sdk.getIdTokenResult(t,!0))?.claims||{})}async getCustomClaim(t){this.ensureInitialized();try{return(await this.getCustomClaims())[t]||null}catch(e){throw n(e,{userMessage:"Failed to get user permission"})}}async hasRole(t){this.ensureInitialized();try{const e=await this.getCustomClaim("role");if(this.store&&e){const i=this.storeState.userProfile;i&&this.storeState.setAuthenticated(this.storeState.user,this.storeState.userSubscription,{...i,role:e})}return e===t}catch(e){throw n(e,{userMessage:"Failed to verify user role"})}}async hasTier(t){this.ensureInitialized(),this.initializeClaimsCache();try{const e=(await this.getCustomClaims()).subscription?.tier;if(this.store&&e){const i=this.storeState.userSubscription;i&&this.storeState.setAuthenticated(this.storeState.user,{...i,tier:e},this.storeState.userProfile)}return e===t}catch(e){const i=this.getAppConfig()?.features?.offlineTrustEnabled??!0,s=g()?navigator.onLine:!1;if(!i&&!s)throw n(e,{userMessage:"Failed to verify subscription tier"});return!1}}async hasFeature(t){this.ensureInitialized(),this.initializeClaimsCache();const e=this.storeState.getCustomClaimsLocal()?.features||[],i=Array.isArray(e)&&e.includes(t);if(!this.claimsCache)try{const a=(await this.getCustomClaims()).features||[];return Array.isArray(a)&&a.includes(t)}catch(a){throw n(a,{userMessage:"Failed to verify feature access"})}const s=g()?navigator.onLine:!1,r=this.getAppConfig()?.features?.offlineTrustEnabled??!1;if(s)try{const a=(await this.getCustomClaims()).features||[];return Array.isArray(a)&&a.includes(t)}catch{return i}else return r?i:!1}async getCurrentUser(){const t=await this.sdk.getCurrentUser();return t?this.convertToAuthUser(t):null}async signOut(){this.ensureInitialized(),this.clearPopupMonitoring();try{h.removeItem("accountLinkingInfo"),await this.clearCachedClaims(),await this.sdk.signOut(),c("info","Signed out successfully")}catch(t){throw n(t,{userMessage:"Failed to sign out",showNotification:!0})}}async reauthenticateWithPassword(t){this.ensureInitialized();const e=this.sdk.getCurrentUser();if(!e||!e.email)throw new Error("No authenticated user");try{const i=N.credential(e.email,t);await this.sdk.reauthenticateWithCredential(e,i)}catch(i){throw n(i,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}async reauthenticateWithProvider(t,e){this.ensureInitialized();const i=this.sdk.getCurrentUser();if(!i)throw new Error("No authenticated user");const s=w(e);try{const r=this.createProviderFromConfig(t);if(s==="popup")await this.sdk.reauthenticateWithPopup(i,r);else{await this.sdk.reauthenticateWithRedirect(i,r);return}}catch(r){throw r.code==="auth/popup-closed-by-user"||r.code==="auth/cancelled-popup-request"||r.code==="auth/popup-blocked"?new Error("REAUTH_CANCELLED"):n(r,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}}getPrimaryProvider(t){if(!t.providerData||t.providerData.length===0)return null;const e=t.providerData[0]?.providerId;return e?e==="password"||e==="emailLink"?"password":e.startsWith("google.com")?"google":e.startsWith("github.com")?"github":e.startsWith("microsoft.com")?"microsoft":e.startsWith("apple.com")?"apple":e.startsWith("facebook.com")?"facebook":e.startsWith("twitter.com")?"twitter":null:null}async deleteAccount(t){this.ensureInitialized();const e=this.sdk.getCurrentUser();if(!e)throw new Error("No authenticated user");const i=async()=>{const s=this.getAppConfig()?.auth,r=s&&typeof s=="object"?s.deleteUserFunction:void 0;if(r)try{await r(e.uid)}catch{}await this.sdk.deleteUser(e),c("success","Account deleted successfully")};try{await i()}catch(s){if(s.code==="auth/requires-recent-login"){const r=this.getPrimaryProvider(e);if(!r)throw n(s,{userMessage:"Unable to determine authentication provider",showNotification:!0});if(r!=="password")try{await this.reauthenticateWithProvider(r),await i();return}catch(a){throw a.message==="REAUTH_CANCELLED"?new Error("REAUTH_CANCELLED"):n(a,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}if(!t)throw new Error("REQUIRES_PASSWORD");try{await this.reauthenticateWithPassword(t),await i();return}catch(a){throw n(a,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}throw n(s,{userMessage:"Failed to delete account",showNotification:!0})}}async clearCachedClaims(){this.claimsCache&&await this.claimsCache.clearClaims()}async setCachedClaims(t){this.initializeClaimsCache(),this.claimsCache&&await this.claimsCache.setClaims(t)}clearAccountLinkingState(){F()}resetAuthState(){this.store&&(Object.keys(m).forEach(t=>{this.storeState.setPartnerState(t,o.IDLE)}),this.storeState.clearAuthError())}async fetchSignInMethodsForEmail(t){this.ensureInitialized();try{return await this.sdk.fetchSignInMethodsForEmail(t)}catch(e){throw n(e,{userMessage:"Failed to check sign-in methods"})}}getSmartRecoveryDeps(){return{sdk:this.sdk,handleAccountLinking:this.handleAccountLinking.bind(this),createAuthResult:this.createAuthResult.bind(this)}}getAccountLinkingDeps(){return{sdk:this.sdk,createProviderFromConfig:this.createProviderFromConfig.bind(this),createAuthResult:this.createAuthResult.bind(this),getExistingProvider:U}}async handleAccountLinking(t,e,i){return await D(t,e,i,this.getAccountLinkingDeps())}createProviderFromConfig(t){const e=m[t];if(!e||!e.firebaseProviderId)throw new Error(`Unsupported partner: ${t}`);let i;switch(t){case"google":i=this.sdk.createGoogleProvider();break;case"github":i=this.sdk.createGithubProvider();break;case"facebook":i=this.sdk.createFacebookProvider();break;case"twitter":i=this.sdk.createTwitterProvider();break;case"microsoft":i=this.sdk.createMicrosoftProvider();break;case"apple":i=this.sdk.createAppleProvider();break;default:i=this.sdk.createOAuthProvider(e.firebaseProviderId)}return e.customParameters&&i.setCustomParameters(e.customParameters),e.scopes&&e.scopes.length>0&&e.scopes.forEach(s=>i.addScope(s)),i}convertToAuthUser(t){return{id:t.uid,email:t.email||null,displayName:t.displayName||null,photoURL:t.photoURL||null,emailVerified:t.emailVerified||!1,lastLoginAt:t.metadata.lastSignInTime||new Date().toISOString(),providerData:t.providerData.map(e=>({providerId:e.providerId,uid:e.uid,displayName:e.displayName,email:e.email,photoURL:e.photoURL,phoneNumber:e.phoneNumber}))}}createAuthResult(t,e=!1){return{user:this.convertToAuthUser(t),success:!0,isNewUser:e}}createCredentialFromStoredData(t){try{if(!t||!t.providerId)return null;switch(t.providerId){case"google.com":return v.credential(t.idToken||null,t.accessToken||null);case"github.com":return b.credential(t.accessToken);case"facebook.com":return T.credential(t.accessToken);case"twitter.com":return L.credential(t.accessToken,t.secret||t.oauthTokenSecret);default:return t.idToken?new p(t.providerId).credential({idToken:t.idToken,accessToken:t.accessToken}):t.accessToken?new p(t.providerId).credential({accessToken:t.accessToken}):null}}catch(e){return n(e,{showNotification:!1,severity:"warning",context:{operation:"_getCredentialFromData"}}),null}}reset(){this.initialized=!1,this.sdk=y(),this.store=null,this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}}const z=C(()=>new I);export{I as FirebaseAuth,z as getFirebaseAuth};
1
+ import{toast as c}from"@donotdev/components";import{createSingleton as A,safeSessionStorage as d,handleError as a,isClient as p,ClaimsCache as I,getAuthPartnerIdByFirebaseId as y}from"@donotdev/core";import{AUTH_PARTNERS as w,SUBSCRIPTION_TIERS as S,createDefaultUserProfile as R}from"@donotdev/core";import{getFirebaseSDK as P,GoogleAuthProvider as v,GithubAuthProvider as T,FacebookAuthProvider as b,TwitterAuthProvider as L,OAuthProvider as m,EmailAuthProvider as N}from"@donotdev/firebase";import{getAuthMethod as k}from"./constants";import{PARTNER_STATE as o,EMAIL_VERIFICATION_STATUS as C}from"./constants";import{handleOAuthLinking as D,clearAccountLinkingState as F}from"./FirebaseAccountLinking";import{handleSmartRecovery as g}from"./FirebaseSmartRecovery";async function M(E,t,e){const i=m.credentialFromError(t),r=t.customData?._tokenResponse?.verifiedProvider?.[0]||i?.providerId||t.customData?.providerId;return r?y(r):null}class z{sdk;initialized=!1;store=null;popupTimeout=null;claimsCache=null;constructor(){this.sdk=P()}setStore(t){this.store=t}get storeState(){if(!this.store)throw new Error("[FirebaseAuth] Store not set. Call setStore() first.");return this.store}async initialize(){if(!this.initialized)try{await this.sdk.initialize();try{await this.processRedirectResult(!0)}catch(t){a(t,{userMessage:"Redirect processing failed",context:{operation:"processRedirectResult"},severity:"warning",showNotification:!1})}this.initialized=!0}catch(t){throw a(t,{userMessage:"Failed to initialize authentication",showNotification:!1})}}async processRedirectResult(t=!1){this.store&&this.store.setLoading(!0);try{const e=new Promise((r,s)=>setTimeout(()=>s(new Error("Redirect check timeout")),1e4)),i=await Promise.race([this.sdk.getRedirectResult(),e]).catch(r=>{if(r.message==="Redirect check timeout")return null;throw r});i?.user&&(await this.handleAuthStateChange(i.user),await this.checkPendingLinking(),d.removeItem("pendingAuthPartnerId"),c("success","Signed in successfully!"))}catch(e){if(e.code==="auth/account-exists-with-different-credential"){const i=m.credentialFromError(e)?.providerId||e.customData?._tokenResponse?.providerId,r=i?y(i):d.getItem("pendingAuthPartnerId");if(r)try{await g(e,()=>Promise.resolve(),{partnerId:r,method:"redirect"},this.getSmartRecoveryDeps());return}catch(s){a(s,{userMessage:"Failed to link accounts. Please try again.",showNotification:!t})}}if(a(e,{userMessage:"Authentication failed. Please try again.",showNotification:!t,context:{operation:"processRedirectResult"}}),e.code!=="auth/account-exists-with-different-credential")try{this.clearAccountLinkingState(),d.removeItem("pendingAuthPartnerId")}catch(i){a(i)}}finally{this.store&&this.store.setLoading(!1)}}ensureInitialized(){if(!this.initialized)throw new Error("FirebaseAuth not initialized. Call initialize() first.")}getAppConfig(){if(typeof globalThis<"u"){const t=globalThis._DNDEV_APP_CONFIG_;if(t)return t}return null}initializeClaimsCache(){if(this.claimsCache)return;const e=this.getAppConfig()?.features?.offlineTrustEnabled??!1;this.claimsCache=new I({offlineTrustEnabled:e,userId:this.storeState?.userId??null})}onAuthStateChanged(t){return this.sdk.onAuthStateChanged(async e=>{e?await this.handleAuthStateChange(e):this.handleSignOut(),e&&await this.checkPendingLinking();const i=e?this.convertToAuthUser(e):null;t(i)})}async handleAuthStateChange(t){if(!this.store)return;const e=this.convertToAuthUser(t);this.initializeClaimsCache(),this.claimsCache&&this.claimsCache.setUserId(e.id),this.storeState.clearAllPartnerStates();let i={userId:e.id,tier:S.FREE,status:"active",isActive:!0,features:[],subscriptionId:null,customerId:e.id,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{const s=await this.sdk.getIdTokenResult(t,!0);if(s?.claims?.subscription){const n=s.claims.subscription;i={userId:e.id,tier:n.tier||S.FREE,status:n.status||"active",isActive:n.status==="active",features:n.features||[],subscriptionId:n.subscriptionId||null,customerId:n.customerId||e.id,subscriptionEnd:n.subscriptionEnd||null,cancelAtPeriodEnd:!!n.cancelAtPeriodEnd,updatedAt:n.updatedAt||new Date().toISOString()}}}catch(s){s?.code==="auth/network-request-failed"||s?.originalCode==="auth/network-request-failed"||s?.message?.includes("network")||a(s,{userMessage:"Failed to get custom claims",context:{operation:"getCustomClaims"},severity:"warning"})}const r=R(e.id);this.storeState.setAuthenticated(e,i,r)}handleSignOut(){this.store&&(this.claimsCache&&this.claimsCache.setUserId(null),this.storeState.clearAllPartnerStates(),this.storeState.setUnauthenticated())}async signInWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.signInWithEmail(t,e);return c("success","Signed in successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user)}catch(i){if(i.code==="auth/user-not-found"){c("info","Creating your account...");try{const r=await this.sdk.createUserWithEmail(t,e);return c("success","Account created successfully!"),this.createAuthResult(r.user,!0)}catch(r){throw this.storeState.setPartnerState("password",o.ERROR),a(r,{userMessage:"Failed to create account",showNotification:!0})}}try{return await g(i,()=>this.sdk.signInWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps())}catch(r){throw this.storeState.setPartnerState("password",o.ERROR),r}}}async createUserWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.createUserWithEmail(t,e);return c("success","Account created successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user,!0)}catch(i){try{const r=await g(i,()=>this.sdk.createUserWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps());if(!r)throw new Error("Account creation failed");return r}catch(r){throw this.storeState.setPartnerState("password",o.ERROR),r}}}async signInWithPartner(t,e){const i=k(e);this.ensureInitialized(),this.storeState.setPartnerState(t,o.LOADING);try{const r=this.createProviderFromConfig(t);let s;return i==="popup"?(s=await this.handlePopupAuth(t,async()=>await this.sdk.signInWithPopup(r)),s===null?(this.storeState.setPartnerState(t,o.IDLE),null):(c("success","Signed in successfully!"),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(s.user))):(d.setItem("pendingAuthPartnerId",t),await this.sdk.signInWithRedirect(r),null)}catch(r){try{const s=await g(r,()=>{const n=this.createProviderFromConfig(t);return i==="popup"?this.sdk.signInWithPopup(n):this.sdk.signInWithRedirect(n)},{partnerId:t,method:i},this.getSmartRecoveryDeps());return s===null?(this.storeState.setPartnerState(t,o.IDLE),null):s}catch(s){throw this.storeState.setPartnerState(t,o.ERROR),s}}}async linkWithPartner(t,e){const i=k(e);this.ensureInitialized();const r=this.sdk.getCurrentUser();if(!r)throw a(new Error("No authenticated user"),{userMessage:"You must be signed in to link accounts",context:{operation:"linkWithPartner",partnerId:t},showNotification:!0});this.storeState.setPartnerState(t,o.LOADING);try{const s=this.createProviderFromConfig(t);if(i==="popup"){const n=await this.sdk.linkWithPopup(r,s);return c("success",`Successfully linked ${t} account!`),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(n.user)}else return await this.sdk.linkWithRedirect(r,s),null}catch(s){const n=s;let u="Failed to link account",l={operation:"linkWithPartner",partnerId:t,errorCode:n.code};switch(n.code){case"auth/operation-not-allowed":u="Account linking is disabled. Contact support for assistance.";break;case"auth/provider-already-linked":u="This account is already linked to your profile.";break;case"auth/credential-already-in-use":u="This account is already linked to another profile.";break;case"auth/requires-recent-login":u="Please sign out and sign back in, then try linking again.";break;default:u=`Failed to link ${t} account. Please try again.`}throw this.storeState.setPartnerState(t,o.ERROR),a(s,{userMessage:u,context:l,showNotification:!0})}}async handlePopupAuth(t,e){this.clearPopupMonitoring(),this.popupTimeout=setTimeout(()=>{this.storeState.setPartnerState(t,o.IDLE),this.clearPopupMonitoring()},3e4);try{const i=await e();return this.clearPopupMonitoring(),i}catch(i){if(this.clearPopupMonitoring(),i.code==="auth/popup-closed-by-user"||i.code==="auth/cancelled-popup-request")return null;throw i}}clearPopupMonitoring(){this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}async signInWithGoogleCredential(t){this.ensureInitialized(),this.storeState.setPartnerState("google",o.LOADING);try{const e=await this.sdk.signInWithGoogleCredential(t);return c("success","Signed in with Google!"),this.storeState.setPartnerState("google",o.IDLE),this.createAuthResult(e.user)}catch(e){try{return await g(e,()=>this.sdk.signInWithGoogleCredential(t),{partnerId:"google",method:"redirect"},this.getSmartRecoveryDeps())}catch(i){throw this.storeState.setPartnerState("google",o.ERROR),i}}}async getRedirectResult(){this.ensureInitialized();try{const t=await this.sdk.getRedirectResult();return t?.user?(c("success","Signed in successfully!"),this.createAuthResult(t.user)):null}catch(t){try{return await g(t,()=>this.sdk.getRedirectResult(),{method:"redirect"},this.getSmartRecoveryDeps())}catch(e){throw e}}}async checkPendingLinking(){const t=d.getItem("accountLinkingInfo"),e=d.getItem("originalCredential");if(!(!t||!e))try{const i=JSON.parse(t),r=JSON.parse(e),s=await this.sdk.getCurrentUser();if(!s)return;const n=this.convertToAuthUser(s),u=w[i.newProvider];if(!u)return;if(n.providerData?.some(f=>f.providerId===u.firebaseProviderId)||!1){this.clearAccountLinkingState();return}const h=this.createCredentialFromStoredData(r);if(!h){this.clearAccountLinkingState();return}await this.sdk.linkWithCredential(s,h),this.clearAccountLinkingState(),c("success","Accounts linked successfully!")}catch(i){throw this.clearAccountLinkingState(),a(i,{userMessage:"Account linking failed",showNotification:!0})}}async sendSignInLinkToEmail(t,e){this.ensureInitialized();try{await this.sdk.sendSignInLinkToEmail(t,e||{url:"",handleCodeInApp:!1}),c("success","Sign-in link sent to your email!")}catch(i){throw a(i,{userMessage:"Failed to send sign-in link",showNotification:!0})}}async signInWithEmailLink(t,e){this.ensureInitialized(),this.storeState.setPartnerState("emailLink",o.LOADING);try{const i=await this.sdk.signInWithEmailLink(t,e);return c("success","Signed in successfully!"),this.storeState.setPartnerState("emailLink",o.IDLE),this.createAuthResult(i.user)}catch(i){try{return await g(i,()=>this.sdk.signInWithEmailLink(t,e),{email:t,partnerId:"emailLink"},this.getSmartRecoveryDeps())}catch(r){throw this.storeState.setPartnerState("emailLink",o.ERROR),r}}}isSignInWithEmailLink(t){if(!t&&!p())return!1;const e=t||(p()?window.location.href:"");return this.sdk.isSignInWithEmailLink(e)}async sendPasswordResetEmail(t){this.ensureInitialized();try{await this.sdk.sendPasswordResetEmail(t),c("success","Password reset email sent!")}catch(e){throw a(e,{userMessage:"Failed to send password reset email",showNotification:!0})}}async updatePassword(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)throw a(new Error("No authenticated user"),{userMessage:"You must be signed in to update your password",showNotification:!0});try{await this.sdk.updatePassword(e,t),c("success","Password updated successfully!")}catch(i){throw a(i,{userMessage:"Failed to update password",showNotification:!0})}}async sendEmailVerification(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();if(!t)throw a(new Error("No authenticated user"),{userMessage:"You must be signed in to verify your email",showNotification:!0});try{this.storeState.setEmailVerificationStatus(C.PENDING),await this.sdk.sendEmailVerification(t),c("success","Verification email sent!")}catch(e){throw this.storeState.setEmailVerificationStatus(C.PENDING),a(e,{userMessage:"Failed to send verification email",showNotification:!0})}}async getEmailVerificationStatus(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();return t?{status:t.emailVerified?"verified":"pending"}:{status:"pending",error:"No authenticated user"}}async isEmailVerificationEnabled(){return!0}async getIdTokenResult(t=!1){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)return null;try{return await this.sdk.getIdTokenResult(e,t)}catch(i){throw a(i,{userMessage:"Failed to get authentication token"})}}async getCustomClaims(){this.ensureInitialized(),this.initializeClaimsCache();const t=await this.sdk.getCurrentUser();if(!t)return{};if(!this.claimsCache)try{return(await this.sdk.getIdTokenResult(t,!0))?.claims||{}}catch(e){throw a(e,{userMessage:"Failed to get user permissions"})}return this.claimsCache.getClaims(async()=>(await this.sdk.getIdTokenResult(t,!0))?.claims||{})}async getCustomClaim(t){this.ensureInitialized();try{return(await this.getCustomClaims())[t]||null}catch(e){throw a(e,{userMessage:"Failed to get user permission"})}}async hasRole(t){this.ensureInitialized();try{const e=await this.getCustomClaim("role");if(this.store&&e){const i=this.storeState.userProfile;i&&this.storeState.setAuthenticated(this.storeState.user,this.storeState.userSubscription,{...i,role:e})}return e===t}catch(e){throw a(e,{userMessage:"Failed to verify user role"})}}async hasTier(t){this.ensureInitialized(),this.initializeClaimsCache();try{const i=(await this.getCustomClaims()).subscription?.tier;if(this.store&&i){const r=this.storeState.userSubscription;r&&this.storeState.setAuthenticated(this.storeState.user,{...r,tier:i},this.storeState.userProfile)}return i===t}catch(e){const r=this.getAppConfig()?.features?.offlineTrustEnabled??!0,s=p()?navigator.onLine:!1;if(!r&&!s)throw a(e,{userMessage:"Failed to verify subscription tier"});return!1}}async hasFeature(t){this.ensureInitialized(),this.initializeClaimsCache();const i=this.storeState.getCustomClaimsLocal()?.features||[],r=Array.isArray(i)&&i.includes(t);if(!this.claimsCache)try{const h=(await this.getCustomClaims()).features||[];return Array.isArray(h)&&h.includes(t)}catch(l){throw a(l,{userMessage:"Failed to verify feature access"})}const s=p()?navigator.onLine:!1,u=this.getAppConfig()?.features?.offlineTrustEnabled??!1;if(s)try{const h=(await this.getCustomClaims()).features||[],f=Array.isArray(h)&&h.includes(t);return f}catch{return r}else return u?r:!1}async getCurrentUser(){const t=await this.sdk.getCurrentUser();return t?this.convertToAuthUser(t):null}async signOut(){this.ensureInitialized(),this.clearPopupMonitoring();try{d.removeItem("accountLinkingInfo"),await this.clearCachedClaims(),await this.sdk.signOut(),c("info","Signed out successfully")}catch(t){throw a(t,{userMessage:"Failed to sign out",showNotification:!0})}}async reauthenticateWithPassword(t){this.ensureInitialized();const e=this.sdk.getCurrentUser();if(!e||!e.email)throw new Error("No authenticated user");try{const i=N.credential(e.email,t);await this.sdk.reauthenticateWithCredential(e,i)}catch(i){throw a(i,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}async reauthenticateWithProvider(t,e){this.ensureInitialized();const i=this.sdk.getCurrentUser();if(!i)throw new Error("No authenticated user");const r=k(e);try{const s=this.createProviderFromConfig(t);if(r==="popup")await this.sdk.reauthenticateWithPopup(i,s);else{await this.sdk.reauthenticateWithRedirect(i,s);return}}catch(s){throw s.code==="auth/popup-closed-by-user"||s.code==="auth/cancelled-popup-request"||s.code==="auth/popup-blocked"?new Error("REAUTH_CANCELLED"):a(s,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}}getPrimaryProvider(t){if(!t.providerData||t.providerData.length===0)return null;const e=t.providerData[0]?.providerId;return e?e==="password"||e==="emailLink"?"password":e.startsWith("google.com")?"google":e.startsWith("github.com")?"github":e.startsWith("microsoft.com")?"microsoft":e.startsWith("apple.com")?"apple":e.startsWith("facebook.com")?"facebook":e.startsWith("twitter.com")?"twitter":null:null}async deleteAccount(t){this.ensureInitialized();const e=this.sdk.getCurrentUser();if(!e)throw new Error("No authenticated user");const i=async()=>{const r=this.getAppConfig()?.auth,s=r&&typeof r=="object"?r.deleteUserFunction:void 0;if(s)try{await s(e.uid)}catch{}await this.sdk.deleteUser(e),c("success","Account deleted successfully")};try{await i()}catch(r){if(r.code==="auth/requires-recent-login"){const s=this.getPrimaryProvider(e);if(!s)throw a(r,{userMessage:"Unable to determine authentication provider",showNotification:!0});if(s!=="password")try{await this.reauthenticateWithProvider(s),await i();return}catch(n){throw n.message==="REAUTH_CANCELLED"?new Error("REAUTH_CANCELLED"):a(n,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}if(!t)throw new Error("REQUIRES_PASSWORD");try{await this.reauthenticateWithPassword(t),await i();return}catch(n){throw a(n,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}throw a(r,{userMessage:"Failed to delete account",showNotification:!0})}}async clearCachedClaims(){this.claimsCache&&await this.claimsCache.clearClaims()}async setCachedClaims(t){this.initializeClaimsCache(),this.claimsCache&&await this.claimsCache.setClaims(t)}clearAccountLinkingState(){F()}resetAuthState(){this.store&&(Object.keys(w).forEach(t=>{this.storeState.setPartnerState(t,o.IDLE)}),this.storeState.clearAuthError())}async fetchSignInMethodsForEmail(t){this.ensureInitialized();try{return await this.sdk.fetchSignInMethodsForEmail(t)}catch(e){throw a(e,{userMessage:"Failed to check sign-in methods"})}}getSmartRecoveryDeps(){return{sdk:this.sdk,handleAccountLinking:this.handleAccountLinking.bind(this),createAuthResult:this.createAuthResult.bind(this)}}getAccountLinkingDeps(){return{sdk:this.sdk,createProviderFromConfig:this.createProviderFromConfig.bind(this),createAuthResult:this.createAuthResult.bind(this),getExistingProvider:M}}async handleAccountLinking(t,e,i){return await D(t,e,i,this.getAccountLinkingDeps())}createProviderFromConfig(t){const e=w[t];if(!e||!e.firebaseProviderId)throw new Error(`Unsupported partner: ${t}`);let i;switch(t){case"google":i=this.sdk.createGoogleProvider();break;case"github":i=this.sdk.createGithubProvider();break;case"facebook":i=this.sdk.createFacebookProvider();break;case"twitter":i=this.sdk.createTwitterProvider();break;case"microsoft":i=this.sdk.createMicrosoftProvider();break;case"apple":i=this.sdk.createAppleProvider();break;default:i=this.sdk.createOAuthProvider(e.firebaseProviderId)}return e.customParameters&&i.setCustomParameters(e.customParameters),e.scopes&&e.scopes.length>0&&e.scopes.forEach(r=>i.addScope(r)),i}convertToAuthUser(t){return{id:t.uid,email:t.email||null,displayName:t.displayName||null,photoURL:t.photoURL||null,emailVerified:t.emailVerified||!1,lastLoginAt:t.metadata.lastSignInTime||new Date().toISOString(),providerData:t.providerData.map(e=>({providerId:e.providerId,uid:e.uid,displayName:e.displayName,email:e.email,photoURL:e.photoURL,phoneNumber:e.phoneNumber}))}}createAuthResult(t,e=!1){return{user:this.convertToAuthUser(t),success:!0,isNewUser:e}}createCredentialFromStoredData(t){try{if(!t||!t.providerId)return null;switch(t.providerId){case"google.com":return v.credential(t.idToken||null,t.accessToken||null);case"github.com":return T.credential(t.accessToken);case"facebook.com":return b.credential(t.accessToken);case"twitter.com":return L.credential(t.accessToken,t.secret||t.oauthTokenSecret);default:return t.idToken?new m(t.providerId).credential({idToken:t.idToken,accessToken:t.accessToken}):t.accessToken?new m(t.providerId).credential({accessToken:t.accessToken}):null}}catch(e){return a(e,{showNotification:!1,severity:"warning",context:{operation:"_getCredentialFromData"}}),null}}reset(){this.initialized=!1,this.sdk=P(),this.store=null,this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}}const Y=A(()=>new z);export{z as FirebaseAuth,Y as getFirebaseAuth};
@@ -1 +1 @@
1
- import{toast as s}from"@donotdev/components";import{handleError as c}from"@donotdev/core";import{getAuthMethod as u}from"./constants";async function d(e,o,r,a){if(e.code==="auth/network-request-failed"){s("info","Connection issue - retrying...");try{return await l(o,a)}catch(t){throw c(t,{userMessage:"Network connection failed. Please check your internet and try again.",context:{operation:"network-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/too-many-requests"){s("info","Rate limited - retrying with backoff...");try{return await h(o,a)}catch(t){throw c(t,{userMessage:"Too many attempts. Please wait a moment and try again.",context:{operation:"rate-limit-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/internal-error"){s("info","Temporary issue - retrying...");try{return await w(o,a)}catch(t){throw c(t,{userMessage:"A temporary error occurred. Please try again.",context:{operation:"internal-error-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/account-exists-with-different-credential")try{return await a.handleAccountLinking(e,r.partnerId,r.method?u(r.method):u())}catch(t){throw c(t,{userMessage:"Failed to link accounts. Please try again.",context:{operation:"account-linking",originalError:e.code},showNotification:!0})}if(e.code==="auth/popup-closed-by-user"||e.code==="auth/cancelled-popup-request"||e.code==="auth/popup-blocked"||e.message?.includes("popup")||e.message?.includes("cancelled")||e.message?.includes("closed"))return null;throw c(e,{userMessage:p(e.code),context:{operation:"smart-recovery",errorCode:e.code},showNotification:!0})}async function l(e,o,r=3){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/network-request-failed")throw t;const i=a*1e3;await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}async function h(e,o,r=3){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/too-many-requests")throw t;const i=Math.pow(2,a)*1e3;await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}async function w(e,o,r=2){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/internal-error")throw t;const i=2e3;await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}function p(e){return{"auth/invalid-email":"Invalid email address","auth/user-disabled":"This account has been disabled","auth/user-not-found":"No account found with this email","auth/wrong-password":"Incorrect password","auth/email-already-in-use":"An account already exists with this email","auth/weak-password":"Password is too weak","auth/operation-not-allowed":"This sign-in method is not enabled","auth/invalid-credential":"Invalid credentials provided","auth/invalid-verification-code":"Invalid verification code","auth/invalid-verification-id":"Invalid verification ID","auth/expired-action-code":"This link has expired","auth/invalid-action-code":"Invalid or expired link","auth/credential-already-in-use":"This credential is already associated with another account","auth/requires-recent-login":"Please sign in again to continue","auth/popup-blocked":"Popup was blocked by your browser. Please allow popups and try again."}[e]||"An authentication error occurred"}export{d as handleSmartRecovery};
1
+ import{toast as c}from"@donotdev/components";import{handleError as s}from"@donotdev/core";import{getAuthMethod as u}from"./constants";async function f(e,o,r,a){if(e.code==="auth/network-request-failed"){c("info","Connection issue - retrying...");try{return await d(o,a)}catch(t){throw s(t,{userMessage:"Network connection failed. Please check your internet and try again.",context:{operation:"network-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/too-many-requests"){c("info","Rate limited - retrying with backoff...");try{return await l(o,a)}catch(t){throw s(t,{userMessage:"Too many attempts. Please wait a moment and try again.",context:{operation:"rate-limit-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/internal-error"){c("info","Temporary issue - retrying...");try{return await h(o,a)}catch(t){throw s(t,{userMessage:"A temporary error occurred. Please try again.",context:{operation:"internal-error-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/account-exists-with-different-credential")try{return await a.handleAccountLinking(e,r.partnerId,r.method?u(r.method):u())}catch(t){throw s(t,{userMessage:"Failed to link accounts. Please try again.",context:{operation:"account-linking",originalError:e.code},showNotification:!0})}if(e.code==="auth/popup-closed-by-user"||e.code==="auth/cancelled-popup-request"||e.code==="auth/popup-blocked"||e.message?.includes("popup")||e.message?.includes("cancelled")||e.message?.includes("closed"))return null;throw s(e,{userMessage:y(e.code),context:{operation:"smart-recovery",errorCode:e.code},showNotification:!0})}async function d(e,o,r=3){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/network-request-failed")throw t;const i=a*1e3;await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}async function l(e,o,r=3){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/too-many-requests")throw t;const i=Math.pow(2,a)*1e3;await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}async function h(e,o,r=2){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/internal-error")throw t;const i=2e3;await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}function y(e){return{"auth/invalid-email":"Invalid email address","auth/user-disabled":"This account has been disabled","auth/user-not-found":"No account found with this email","auth/wrong-password":"Incorrect password","auth/email-already-in-use":"An account already exists with this email","auth/weak-password":"Password is too weak","auth/operation-not-allowed":"This sign-in method is not enabled","auth/invalid-credential":"Invalid credentials provided","auth/invalid-verification-code":"Invalid verification code","auth/invalid-verification-id":"Invalid verification ID","auth/expired-action-code":"This link has expired","auth/invalid-action-code":"Invalid or expired link","auth/credential-already-in-use":"This credential is already associated with another account","auth/requires-recent-login":"Please sign in again to continue","auth/popup-blocked":"Popup was blocked by your browser. Please allow popups and try again."}[e]||"An authentication error occurred"}export{f as handleSmartRecovery};
@@ -1 +1 @@
1
- import{isClient as r}from"@donotdev/core";import{useAuthStore as t}from"./AuthStore";function s(){return t.getState()}function u(e){return r()?t.subscribe(e):()=>{}}export{s as getAuthState,u as subscribeToAuth};
1
+ import{isClient as e}from"@donotdev/core";import{useAuthStore as t}from"./AuthStore";function i(){return t.getState()}function n(r){return e()?t.subscribe(r):()=>{}}export{i as getAuthState,n as subscribeToAuth};
@@ -1 +1 @@
1
- "use client";import{jsx as i,jsxs as t}from"react/jsx-runtime";import{Suspense as L,lazy as A}from"react";import{Alert as p,ALERT_VARIANT as h,Button as o,BUTTON_VARIANT as c,Stack as a}from"@donotdev/components";import{useTranslation as T,safeSessionStorage as k,handleError as I}from"@donotdev/core";import{EmailLinkForm as R}from"./EmailLinkForm";import S from"./EmailPasswordForm";import{useAccountLinking as y}from"../hooks/useAccountLinking";const N=({className:r="",id:l})=>{const{t:e}=T("dndev"),{isRequired:v,email:d,existingProvider:n,newProvider:m,handleSignInWithExistingProvider:f}=y();if(!v)return null;if(n==="password"||n==="emailLink"){const s=()=>{k.removeItem("accountLinkingInfo")},u=()=>{},g=w=>{I(w)};return i("div",{className:r,id:l,children:i(p,{variant:h.WARNING,role:"alert","aria-live":"polite",title:e("accountLinking.title","Account Linking Required"),description:t(a,{gap:"medium",children:[i("p",{children:e("accountLinking.message",`An account with email ${d} already exists with ${n==="password"?"email/password":"email link"}. To link your ${m} account, please sign in with your ${n==="password"?"email and password":"email link"} first.`)}),n==="password"?i("div",{style:{marginTop:"var(--gap-md)"},children:i(S,{mode:"signin",onSuccess:u,onError:g})}):i("div",{style:{marginTop:"var(--gap-md)"},children:i(R,{onSuccess:u,onError:g})}),i(a,{direction:"row",justify:"end",children:i(o,{onClick:s,variant:c.GHOST,children:e("accountLinking.dismiss","Dismiss")})})]})})})}else{const s=()=>{k.removeItem("accountLinkingInfo")};return i("div",{className:r,id:l,children:i(p,{variant:h.WARNING,role:"alert","aria-live":"polite",title:e("accountLinking.title","Account Linking Required"),description:t(a,{gap:"medium",children:[i("p",{children:e("accountLinking.message",`An account with email ${d} already exists with ${n}. To link your ${m} account, please sign in with ${n} first.`)}),t(a,{direction:"row",gap:"medium",children:[i(o,{onClick:f,variant:c.PRIMARY,children:e("accountLinking.signInWith",`Sign in with ${n}`)}),i(o,{onClick:s,variant:c.GHOST,children:e("accountLinking.dismiss","Dismiss")})]})]})})})}},$=A(()=>Promise.resolve({default:N}));function x(r){return i(L,{fallback:null,children:i($,{...r})})}var E=x;export{E as default};
1
+ "use client";import{jsx as i,jsxs as s}from"react/jsx-runtime";import{Suspense as A,lazy as w}from"react";import{Alert as h,ALERT_VARIANT as p,Button as a,BUTTON_VARIANT as c,Stack as r}from"@donotdev/components";import{useTranslation as I,safeSessionStorage as k,handleError as T}from"@donotdev/core";import{EmailLinkForm as x}from"./EmailLinkForm";import y from"./EmailPasswordForm";import{useAccountLinking as E}from"../hooks/useAccountLinking";const S=({className:o="",id:l})=>{const{t:e}=I("dndev"),{isRequired:v,email:d,existingProvider:n,newProvider:m,handleSignInWithExistingProvider:L}=E();if(!v)return null;if(n==="password"||n==="emailLink"){const t=()=>{k.removeItem("accountLinkingInfo")},u=()=>{},g=f=>{T(f)};return i("div",{className:o,id:l,children:i(h,{variant:p.WARNING,role:"alert","aria-live":"polite",title:e("accountLinking.title","Account Linking Required"),description:s(r,{gap:"medium",children:[i("p",{children:e("accountLinking.message",`An account with email ${d} already exists with ${n==="password"?"email/password":"email link"}. To link your ${m} account, please sign in with your ${n==="password"?"email and password":"email link"} first.`)}),n==="password"?i("div",{style:{marginTop:"var(--gap-md)"},children:i(y,{mode:"signin",onSuccess:u,onError:g})}):i("div",{style:{marginTop:"var(--gap-md)"},children:i(x,{onSuccess:u,onError:g})}),i(r,{direction:"row",justify:"end",children:i(a,{onClick:t,variant:c.GHOST,children:e("accountLinking.dismiss","Dismiss")})})]})})})}else{const t=()=>{k.removeItem("accountLinkingInfo")};return i("div",{className:o,id:l,children:i(h,{variant:p.WARNING,role:"alert","aria-live":"polite",title:e("accountLinking.title","Account Linking Required"),description:s(r,{gap:"medium",children:[i("p",{children:e("accountLinking.message",`An account with email ${d} already exists with ${n}. To link your ${m} account, please sign in with ${n} first.`)}),s(r,{direction:"row",gap:"medium",children:[i(a,{onClick:L,variant:c.PRIMARY,children:e("accountLinking.signInWith",`Sign in with ${n}`)}),i(a,{onClick:t,variant:c.GHOST,children:e("accountLinking.dismiss","Dismiss")})]})]})})})}},$=w(()=>Promise.resolve({default:S}));function R(o){return i(A,{fallback:null,children:i($,{...o})})}var W=R;export{W as default};
@@ -1 +1 @@
1
- import{jsx as e}from"react/jsx-runtime";import"react";import{FeatureFallback as s,withFeatureFallback as r}from"@donotdev/components";import{isFeatureAvailable as n,FRAMEWORK_FEATURES as i}from"@donotdev/core";function o({message:t="Authentication is not available",showLoginButton:a=!1,className:u=""}){return e(s,{featureName:"Authentication",message:t,icon:"\u{1F512}",showActionButton:a,actionButtonText:"Sign In (Unavailable)",className:u,helpText:"This feature requires authentication to be configured."})}function l(t,a){return r(t,"Authentication",()=>n(i.AUTH),{message:a?.message,showActionButton:a?.showLoginButton,actionButtonText:"Sign In (Unavailable)",icon:"\u{1F512}",helpText:"This feature requires authentication to be configured."})}function c(t){return{isAuthAvailable:n(i.AUTH),AuthFallbackComponent:()=>e(o,{...t})}}export{o as AuthFallback,c as useAuthComponent,l as withAuthFallback};
1
+ import{jsx as a}from"react/jsx-runtime";import"react";import{FeatureFallback as u,withFeatureFallback as r}from"@donotdev/components";import{isFeatureAvailable as n,FRAMEWORK_FEATURES as i}from"@donotdev/core";function l({message:t="Authentication is not available",showLoginButton:e=!1,className:o=""}){return a(u,{featureName:"Authentication",message:t,icon:"\u{1F512}",showActionButton:e,actionButtonText:"Sign In (Unavailable)",className:o,helpText:"This feature requires authentication to be configured."})}function m(t,e){return r(t,"Authentication",()=>n(i.AUTH),{message:e?.message,showActionButton:e?.showLoginButton,actionButtonText:"Sign In (Unavailable)",icon:"\u{1F512}",helpText:"This feature requires authentication to be configured."})}function b(t){return{isAuthAvailable:n(i.AUTH),AuthFallbackComponent:()=>a(l,{...t})}}export{l as AuthFallback,b as useAuthComponent,m as withAuthFallback};
@@ -1,5 +1,5 @@
1
- "use client";import{jsx as a}from"react/jsx-runtime";import{useMemo as y,useState as L}from"react";if(typeof document<"u"&&!document.getElementById("auth-partner-button-styles")){const t=document.createElement("style");t.id="auth-partner-button-styles",t.textContent=`
1
+ "use client";import{jsx as i}from"react/jsx-runtime";import{useMemo as k,useState as O}from"react";if(typeof document<"u"&&!document.getElementById("auth-partner-button-styles")){const t=document.createElement("style");t.id="auth-partner-button-styles",t.textContent=`
2
2
  .dndev-interactive.auth-partner-button-custom[data-variant='outline']:hover {
3
3
  background-color: var(--partner-hover-bg);
4
4
  }
5
- `,document.head.appendChild(t)}import{cn as R,DISPLAY as C,PROVIDER_ICONS as B,DefaultProviderIcon as D,Button as M,BUTTON_VARIANT as U,Spinner as _}from"@donotdev/components";import{AUTH_PARTNERS as $,useTranslation as V}from"@donotdev/core";import{EmailLinkForm as W}from"./EmailLinkForm";import j from"./EmailPasswordForm";import{getAuthMethod as S}from"../constants";import{useAuth as s}from"../useAuth";function F({partnerId:t,method:p,onSuccess:u,onError:l,className:d="",children:b,disabled:h=!1,emailMode:k="signin",display:f=C.AUTO,...H}){const{t:i}=V("auth"),v=s("user"),E=s("signInWithPartner"),I=s("linkWithPartner"),A=s("isAvailable"),[o,g]=L(!1),n=y(()=>$[t],[t]);if(t==="password")return a("div",{className:d,children:a(j,{mode:k,onSuccess:()=>u?.(null),onError:l,compact:!0})});if(t==="emailLink")return a("div",{className:d,children:a(W,{onSuccess:()=>u?.(null),onError:l})});const N=y(()=>B[t]||D,[t]),c=!!v?.providerData?.some(r=>r.providerId===t),m=v&&!c,T=async()=>{if(!(o||h)){g(!0);try{let r;if(m)r=await I(t,S(p));else{const x=S(p);r=await E(t,x)}r&&u?.(r)}catch(r){l?.(r instanceof Error?r:new Error(String(r)))}finally{g(!1)}}},e=n?.name,w=()=>{if(b)return b;if(m)return o?i("buttons.linking",{partner:e}):c?i("buttons.linked",{partner:e}):i("buttons.link",{partner:e});if(o)return i("buttons.signingIn",{partner:e});const r=n?.button?.textKey;return r?i(r):`Sign in with ${e}`},P=h||o||!A||m&&c||!1,O=n?.button?{backgroundColor:n.button.backgroundColor,color:n.button.textColor,borderColor:n.button.borderColor,"--partner-hover-bg":n.button.hoverBackgroundColor}:void 0;return a(M,{variant:U.OUTLINE,onClick:T,disabled:P,"aria-busy":o,display:f,"aria-label":o?`Signing in with ${e}...`:`Sign in with ${e}`,tooltip:void 0,style:O,className:R(n?.button&&"auth-partner-button-custom",d),icon:o?a(_,{"aria-label":"Loading"}):N,children:f!==C.COMPACT&&w()})}var K=F;export{K as default};
5
+ `,document.head.appendChild(t)}import{cn as D,DISPLAY as y,PROVIDER_ICONS as I,DefaultProviderIcon as R,Button as M,BUTTON_VARIANT as U,Spinner as W}from"@donotdev/components";import{AUTH_PARTNERS as _,useTranslation as $}from"@donotdev/core";import{EmailLinkForm as j}from"./EmailLinkForm";import F from"./EmailPasswordForm";import{getAuthMethod as C}from"../constants";import{useAuth as s}from"../useAuth";function K({partnerId:t,method:f,onSuccess:u,onError:l,className:c="",children:b,disabled:h=!1,emailMode:A="signin",display:g=y.AUTO,...V}){const{t:a}=$("auth"),p=s("user"),P=s("signInWithPartner"),S=s("linkWithPartner"),T=s("isAvailable"),[r,v]=O(!1),o=k(()=>_[t],[t]);if(t==="password")return i("div",{className:c,children:i(F,{mode:A,onSuccess:()=>u?.(null),onError:l,compact:!0})});if(t==="emailLink")return i("div",{className:c,children:i(j,{onSuccess:()=>u?.(null),onError:l})});const E=k(()=>I[t]||R,[t]),d=!!p?.providerData?.some(n=>n.providerId===t),m=p&&!d,L=async()=>{if(!(r||h)){v(!0);try{let n;if(m)n=await S(t,C(f));else{const N=C(f);n=await P(t,N)}n&&u?.(n)}catch(n){l?.(n instanceof Error?n:new Error(String(n)))}finally{v(!1)}}},e=o?.name,w=()=>{if(b)return b;if(m)return r?a("buttons.linking",{partner:e}):d?a("buttons.linked",{partner:e}):a("buttons.link",{partner:e});if(r)return a("buttons.signingIn",{partner:e});const n=o?.button?.textKey;return n?a(n):`Sign in with ${e}`},x=h||r||!T||m&&d||!1,B=o?.button?{backgroundColor:o.button.backgroundColor,color:o.button.textColor,borderColor:o.button.borderColor,"--partner-hover-bg":o.button.hoverBackgroundColor}:void 0;return i(M,{variant:U.OUTLINE,onClick:L,disabled:x,"aria-busy":r,display:g,"aria-label":r?`Signing in with ${e}...`:`Sign in with ${e}`,tooltip:void 0,style:B,className:D(o?.button&&"auth-partner-button-custom",c),icon:r?i(W,{"aria-label":"Loading"}):E,children:g!==y.COMPACT&&w()})}var Z=K;export{Z as default};
@@ -1 +1 @@
1
- "use client";import{jsx as t,jsxs as o,Fragment as f}from"react/jsx-runtime";import{Trash2 as R}from"lucide-react";import{useState as A}from"react";import{Dialog as g,Button as d,BUTTON_VARIANT as s,Input as k,Label as C,Checkbox as D,Alert as v,ALERT_VARIANT as w,Stack as r,Text as b,List as T}from"@donotdev/components";import{useTranslation as y}from"@donotdev/core";function x({open:u,isLoading:n,error:a,onReauth:h,onCancel:l}){const{t:e}=y("dndev"),[i,m]=A(""),p=async()=>{await h(i)};return t(g,{open:u,onOpenChange:c=>!c&&l(),title:e("deleteAccount.reauth.title","Confirm Your Identity"),description:e("deleteAccount.reauth.description","For security, please re-enter your password to continue."),footer:o(f,{children:[t(d,{variant:s.OUTLINE,onClick:l,disabled:n,children:e("deleteAccount.reauth.cancel","Cancel")}),t(d,{variant:s.DEFAULT,onClick:p,disabled:n||!i,children:n?e("deleteAccount.reauth.verifying","Verifying..."):e("deleteAccount.reauth.continue","Continue")})]}),children:o(r,{gap:"medium",children:[o(r,{gap:"tight",children:[t(C,{htmlFor:"reauth-password",children:e("deleteAccount.reauth.password","Password")}),t(k,{id:"reauth-password",type:"password",value:i,onChange:c=>m(c.target.value),disabled:n,placeholder:e("deleteAccount.reauth.passwordPlaceholder","Enter your password"),required:!0})]}),a&&t(v,{variant:w.ERROR,description:a})]})})}function E({open:u,isLoading:n,error:a,onConfirm:h,onCancel:l}){const{t:e}=y("dndev"),[i,m]=A(!1),p=async()=>{i&&await h()};return t(g,{open:u,onOpenChange:c=>!c&&l(),"data-content-size":"text",title:e("deleteAccount.confirm.title","Delete Your Account?"),description:e("deleteAccount.confirm.description","This action cannot be undone. This will permanently delete your account."),footer:o(f,{children:[t(d,{variant:s.OUTLINE,onClick:l,disabled:n,children:e("deleteAccount.confirm.cancel","Cancel")}),t(d,{variant:s.DESTRUCTIVE,icon:R,onClick:p,disabled:n||!i,children:n?e("deleteAccount.confirm.deleting","Deleting..."):e("deleteAccount.confirm.delete","Delete My Account")})]}),children:o(r,{gap:"large",children:[o(r,{gap:"medium",children:[t(b,{as:"h4",level:"h4",children:e("deleteAccount.confirm.whatDeleted","What will be deleted:")}),t(T,{items:[e("deleteAccount.confirm.credentials","Your account and authentication credentials"),e("deleteAccount.confirm.profile","Your profile information"),e("deleteAccount.confirm.oauth","All connected OAuth providers"),e("deleteAccount.confirm.subscriptions","Active subscriptions (will be canceled)")]})]}),o(r,{gap:"medium",children:[t(b,{as:"h4",level:"h4",children:e("deleteAccount.confirm.whatKept","What will be kept (anonymized):")}),t(T,{items:[e("deleteAccount.confirm.billing","Billing history for tax/accounting purposes"),e("deleteAccount.confirm.invoices","Past invoices and transaction records")]})]}),o(r,{direction:"row",align:"start",gap:"medium",children:[t(D,{id:"confirm-delete",checked:i,onCheckedChange:c=>m(c===!0)}),t(C,{htmlFor:"confirm-delete",children:e("deleteAccount.confirm.checkbox","I understand this action cannot be undone")})]}),a&&t(v,{variant:w.ERROR,description:a})]})})}export{E as ConfirmDeleteDialog,x as ReauthDialog};
1
+ "use client";import{jsx as t,jsxs as c,Fragment as f}from"react/jsx-runtime";import{Trash2 as x}from"lucide-react";import{useState as A}from"react";import{Dialog as g,Button as d,BUTTON_VARIANT as s,Input as R,Label as w,Checkbox as k,Alert as b,ALERT_VARIANT as v,Stack as r,Text as C,List as T}from"@donotdev/components";import{useTranslation as y}from"@donotdev/core";function N({open:u,isLoading:n,error:l,onReauth:h,onCancel:a}){const{t:e}=y("dndev"),[o,m]=A(""),p=async()=>{await h(o)};return t(g,{open:u,onOpenChange:i=>!i&&a(),title:e("deleteAccount.reauth.title","Confirm Your Identity"),description:e("deleteAccount.reauth.description","For security, please re-enter your password to continue."),footer:c(f,{children:[t(d,{variant:s.OUTLINE,onClick:a,disabled:n,children:e("deleteAccount.reauth.cancel","Cancel")}),t(d,{variant:s.DEFAULT,onClick:p,disabled:n||!o,children:n?e("deleteAccount.reauth.verifying","Verifying..."):e("deleteAccount.reauth.continue","Continue")})]}),children:c(r,{gap:"medium",children:[c(r,{gap:"tight",children:[t(w,{htmlFor:"reauth-password",children:e("deleteAccount.reauth.password","Password")}),t(R,{id:"reauth-password",type:"password",value:o,onChange:i=>m(i.target.value),disabled:n,placeholder:e("deleteAccount.reauth.passwordPlaceholder","Enter your password"),required:!0})]}),l&&t(b,{variant:v.ERROR,description:l})]})})}function U({open:u,isLoading:n,error:l,onConfirm:h,onCancel:a}){const{t:e}=y("dndev"),[o,m]=A(!1),p=async()=>{o&&await h()};return t(g,{open:u,onOpenChange:i=>!i&&a(),"data-content-size":"text",title:e("deleteAccount.confirm.title","Delete Your Account?"),description:e("deleteAccount.confirm.description","This action cannot be undone. This will permanently delete your account."),footer:c(f,{children:[t(d,{variant:s.OUTLINE,onClick:a,disabled:n,children:e("deleteAccount.confirm.cancel","Cancel")}),t(d,{variant:s.DESTRUCTIVE,icon:x,onClick:p,disabled:n||!o,children:n?e("deleteAccount.confirm.deleting","Deleting..."):e("deleteAccount.confirm.delete","Delete My Account")})]}),children:c(r,{gap:"large",children:[c(r,{gap:"medium",children:[t(C,{as:"h4",level:"h4",children:e("deleteAccount.confirm.whatDeleted","What will be deleted:")}),t(T,{items:[e("deleteAccount.confirm.credentials","Your account and authentication credentials"),e("deleteAccount.confirm.profile","Your profile information"),e("deleteAccount.confirm.oauth","All connected OAuth providers"),e("deleteAccount.confirm.subscriptions","Active subscriptions (will be canceled)")]})]}),c(r,{gap:"medium",children:[t(C,{as:"h4",level:"h4",children:e("deleteAccount.confirm.whatKept","What will be kept (anonymized):")}),t(T,{items:[e("deleteAccount.confirm.billing","Billing history for tax/accounting purposes"),e("deleteAccount.confirm.invoices","Past invoices and transaction records")]})]}),c(r,{direction:"row",align:"start",gap:"medium",children:[t(k,{id:"confirm-delete",checked:o,onCheckedChange:i=>m(i===!0)}),t(w,{htmlFor:"confirm-delete",children:e("deleteAccount.confirm.checkbox","I understand this action cannot be undone")})]}),l&&t(b,{variant:v.ERROR,description:l})]})})}export{U as ConfirmDeleteDialog,N as ReauthDialog};
@@ -1 +1 @@
1
- "use client";import{jsx as e,jsxs as n}from"react/jsx-runtime";import{Mail as s,CheckCircle as S}from"lucide-react";import{Button as m,BUTTON_VARIANT as E,Input as y,Label as A,Alert as N,ALERT_VARIANT as R,Spinner as b,Stack as a}from"@donotdev/components";import{useTranslation as T}from"@donotdev/core";import{useEmailLinkForm as C}from"../hooks/useEmailLinkForm";function d({className:t="",onSuccess:c,onError:u,actionCodeSettings:g}){const{t:i}=T("dndev"),{email:o,setEmail:h,isLoading:r,isSent:p,error:l,handleSendLink:k,handleResend:v,canSubmit:L}=C({onSuccess:c,onError:u,actionCodeSettings:g});return p?n(a,{gap:"medium",className:t,children:[n("div",{style:{textAlign:"center"},children:[e(S,{style:{width:"var(--icon-touch)",height:"var(--icon-touch)",marginBottom:"var(--gap-md)",marginLeft:"auto",marginRight:"auto",color:"var(--primary)"}}),e("h3",{style:{marginBottom:"var(--gap-sm)",fontSize:"var(--font-size-lg)",fontWeight:600,color:"var(--foreground)"},children:i("emailLink.checkEmail","Check Your Email")}),e("p",{style:{marginBottom:"var(--gap-md)",color:"var(--muted-foreground)"},children:i("emailLink.sentMessage",`We've sent a sign-in link to ${o}. Click the link in your email to complete sign-in.`)})]}),e(a,{direction:"row",justify:"center",gap:"medium",children:e(m,{variant:E.OUTLINE,onClick:v,icon:s,iconEnd:!1,children:i("emailLink.resend","Resend Link")})})]}):e("form",{onSubmit:k,className:t,children:n(a,{gap:"medium",children:[n(a,{gap:"tight",children:[e(A,{htmlFor:"email",children:i("emailLink.emailLabel","Email Address")}),e(y,{id:"email",type:"email",value:o,onChange:f=>h(f.target.value),placeholder:i("emailLink.emailPlaceholder","Enter your email address"),required:!0,disabled:r,className:"dndev-w-full"})]}),l&&e(N,{variant:R.ERROR,description:l}),e(m,{type:"submit",disabled:!L,icon:r?e(b,{"aria-label":"Loading"}):s,iconEnd:!1,className:"dndev-w-full",children:r?i("emailLink.sending","Sending Link..."):i("emailLink.sendLink","Send Sign-In Link")}),e("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)",textAlign:"center"},children:i("emailLink.helpText","We'll send you a secure link to sign in without a password.")})]})})}var x=d;export{d as EmailLinkForm,x as default};
1
+ "use client";import{jsx as e,jsxs as n}from"react/jsx-runtime";import{Mail as m,CheckCircle as v}from"lucide-react";import{Button as d,BUTTON_VARIANT as y,Input as E,Label as S,Alert as x,ALERT_VARIANT as A,Spinner as R,Stack as a}from"@donotdev/components";import{useTranslation as b}from"@donotdev/core";import{useEmailLinkForm as T}from"../hooks/useEmailLinkForm";function N({className:l="",onSuccess:s,onError:c,actionCodeSettings:u}){const{t:i}=b("dndev"),{email:t,setEmail:g,isLoading:r,isSent:h,error:o,handleSendLink:p,handleResend:k,canSubmit:f}=T({onSuccess:s,onError:c,actionCodeSettings:u});return h?n(a,{gap:"medium",className:l,children:[n("div",{style:{textAlign:"center"},children:[e(v,{style:{width:"var(--icon-touch)",height:"var(--icon-touch)",marginBottom:"var(--gap-md)",marginLeft:"auto",marginRight:"auto",color:"var(--primary)"}}),e("h3",{style:{marginBottom:"var(--gap-sm)",fontSize:"var(--font-size-lg)",fontWeight:600,color:"var(--foreground)"},children:i("emailLink.checkEmail","Check Your Email")}),e("p",{style:{marginBottom:"var(--gap-md)",color:"var(--muted-foreground)"},children:i("emailLink.sentMessage",`We've sent a sign-in link to ${t}. Click the link in your email to complete sign-in.`)})]}),e(a,{direction:"row",justify:"center",gap:"medium",children:e(d,{variant:y.OUTLINE,onClick:k,icon:m,iconEnd:!1,children:i("emailLink.resend","Resend Link")})})]}):e("form",{onSubmit:p,className:l,children:n(a,{gap:"medium",children:[n(a,{gap:"tight",children:[e(S,{htmlFor:"email",children:i("emailLink.emailLabel","Email Address")}),e(E,{id:"email",type:"email",value:t,onChange:L=>g(L.target.value),placeholder:i("emailLink.emailPlaceholder","Enter your email address"),required:!0,disabled:r,className:"dndev-w-full"})]}),o&&e(x,{variant:A.ERROR,description:o}),e(d,{type:"submit",disabled:!f,icon:r?e(R,{"aria-label":"Loading"}):m,iconEnd:!1,className:"dndev-w-full",children:r?i("emailLink.sending","Sending Link..."):i("emailLink.sendLink","Send Sign-In Link")}),e("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)",textAlign:"center"},children:i("emailLink.helpText","We'll send you a secure link to sign in without a password.")})]})})}var _=N;export{N as EmailLinkForm,_ as default};
@@ -1 +1 @@
1
- "use client";import{jsx as r}from"react/jsx-runtime";import{Alert as g}from"@donotdev/components";import{useTranslation as w}from"@donotdev/core";import{EntityFormRenderer as f}from"@donotdev/crud";import{useAuth as i}from"../useAuth";function b({mode:s,onSuccess:n,onError:o,className:l="",compact:E=!1}){const{t:e}=w("dndev"),u=i("signInWithEmail"),m=i("createUserWithEmail"),d=i("isAvailable"),p=i("loading"),c=s==="signup",h={email:{name:"email",type:"email",label:e("auth.email","Email"),required:!0,options:{placeholder:e("auth.emailPlaceholder","Enter your email")}},password:{name:"password",type:"password",label:e("auth.password","Password"),required:!0,options:{placeholder:e("auth.passwordPlaceholder","Enter your password")}}};return d?r(f,{entity:h,onSubmit:async a=>{try{s==="signin"?await u(a.email,a.password):await m(a.email,a.password),n?.(void 0)}catch(t){o?.(t instanceof Error?t:new Error(String(t)))}},onSecondarySubmit:async a=>{try{s==="signin"?await m(a.email,a.password):await u(a.email,a.password),n?.(void 0)}catch(t){o?.(t instanceof Error?t:new Error(String(t)))}},className:l,submitText:c?e("auth:actions.sign_up_submit",{defaultValue:"Sign Up"}):e("auth:actions.sign_in_submit",{defaultValue:"Sign In"}),secondaryButtonText:c?e("auth:actions.sign_in_submit",{defaultValue:"Sign In"}):e("auth:actions.sign_up_submit",{defaultValue:"Sign Up"}),isLoading:p}):r("div",{className:l,children:r(g,{title:"Authentication Unavailable",description:"Please accept cookies to enable authentication."})})}var y=b;export{y as default};
1
+ "use client";import{jsx as s}from"react/jsx-runtime";import{Alert as w}from"@donotdev/components";import{useTranslation as b}from"@donotdev/core";import{EntityFormRenderer as y}from"@donotdev/crud";import{useAuth as a}from"../useAuth";function E({mode:n,onSuccess:r,onError:o,className:l="",compact:S=!1}){const{t:e}=b("dndev"),u=a("signInWithEmail"),c=a("createUserWithEmail"),d=a("isAvailable"),p=a("loading"),m=n==="signup",h={email:{name:"email",type:"email",label:e("auth.email","Email"),required:!0,options:{placeholder:e("auth.emailPlaceholder","Enter your email")}},password:{name:"password",type:"password",label:e("auth.password","Password"),required:!0,options:{placeholder:e("auth.passwordPlaceholder","Enter your password")}}},f=async i=>{try{n==="signin"?await u(i.email,i.password):await c(i.email,i.password),r?.(void 0)}catch(t){o?.(t instanceof Error?t:new Error(String(t)))}},g=async i=>{try{n==="signin"?await c(i.email,i.password):await u(i.email,i.password),r?.(void 0)}catch(t){o?.(t instanceof Error?t:new Error(String(t)))}};return d?s(y,{entity:h,onSubmit:f,onSecondarySubmit:g,className:l,submitText:m?e("auth:actions.sign_up_submit",{defaultValue:"Sign Up"}):e("auth:actions.sign_in_submit",{defaultValue:"Sign In"}),secondaryButtonText:m?e("auth:actions.sign_in_submit",{defaultValue:"Sign In"}):e("auth:actions.sign_up_submit",{defaultValue:"Sign Up"}),isLoading:p}):s("div",{className:l,children:s(w,{title:"Authentication Unavailable",description:"Please accept cookies to enable authentication."})})}var A=E;export{A as default};
@@ -1 +1 @@
1
- "use client";import{jsx as r,jsxs as o}from"react/jsx-runtime";import{Card as v,Button as h,BUTTON_VARIANT as y,Alert as V,Spinner as A,Stack as d}from"@donotdev/components";import{useTranslation as M,handleError as b}from"@donotdev/core";import{useAuth as n}from"../useAuth";function S({verifyButtonText:w,successMessage:x,sendingMessage:j,alreadyVerifiedMessage:E,notSignedInMessage:I,errorMessage:$,id:u}){const{t:e}=M("auth"),t=n("user"),i=n("emailVerification"),l=n("sendEmailVerification"),s=t?.id,a=u||`email-verification-${Math.random().toString(36).slice(2,9)}`,c=`${a}-heading`,f=`${a}-button`,g=async()=>{if(!(!t||!s))try{await l()}catch(p){b(p)}};if(!t||!s)return null;const m=()=>{if(i.status!=="pending"&&i.status==="error")return"error"};return r(v,{id:a,title:r("span",{id:c,children:e("emailVerification.title")}),children:o(d,{gap:"medium",children:[o(d,{direction:"row",justify:"between",align:"center",children:[r("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:e("emailVerification.status.unknown")}),r(h,{id:f,onClick:g,disabled:i.status==="pending","aria-busy":i.status==="pending",variant:y.PRIMARY,icon:i.status==="pending"?r(A,{"aria-label":"Loading"}):void 0,iconEnd:!1,children:i.status==="pending"?e("status.verifying"):e("buttons.verify","Verify")})]}),i.status!=="verified"&&r(V,{variant:m(),title:i.status==="error"?e("aria.errorAlert"):e("status.verifying"),description:i.status==="error"?("error"in i?i.error:void 0)||e("emailVerification.error","An error occurred"):e("emailVerification.sending","Sending verification email...")})]})})}var T=S;export{T as default};
1
+ "use client";import{jsx as r,jsxs as o}from"react/jsx-runtime";import{Card as h,Button as V,BUTTON_VARIANT as v,Alert as y,Spinner as A,Stack as d}from"@donotdev/components";import{useTranslation as b,handleError as I}from"@donotdev/core";import{useAuth as a}from"../useAuth";function M({verifyButtonText:S,successMessage:x,sendingMessage:j,alreadyVerifiedMessage:E,notSignedInMessage:T,errorMessage:w,id:c}){const{t:i}=b("auth"),n=a("user"),e=a("emailVerification"),u=a("sendEmailVerification"),s=n?.id,t=c||`email-verification-${Math.random().toString(36).slice(2,9)}`,l=`${t}-heading`,f=`${t}-button`,m=async()=>{if(!(!n||!s))try{await u()}catch(p){I(p)}};if(!n||!s)return null;const g=()=>{if(e.status!=="pending"&&e.status==="error")return"error"};return r(h,{id:t,title:r("span",{id:l,children:i("emailVerification.title")}),children:o(d,{gap:"medium",children:[o(d,{direction:"row",justify:"between",align:"center",children:[r("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:i("emailVerification.status.unknown")}),r(V,{id:f,onClick:m,disabled:e.status==="pending","aria-busy":e.status==="pending",variant:v.PRIMARY,icon:e.status==="pending"?r(A,{"aria-label":"Loading"}):void 0,iconEnd:!1,children:e.status==="pending"?i("status.verifying"):i("buttons.verify","Verify")})]}),e.status!=="verified"&&r(y,{variant:g(),title:e.status==="error"?i("aria.errorAlert"):i("status.verifying"),description:e.status==="error"?("error"in e?e.error:void 0)||i("emailVerification.error","An error occurred"):i("emailVerification.sending","Sending verification email...")})]})})}var $=M;export{$ as default};
@@ -1 +1 @@
1
- "use client";import{Fragment as a,jsx as n}from"react/jsx-runtime";import{useImperativeHandle as c,forwardRef as l}from"react";import{useAuth as o}from"../useAuth";const f=l(({featureId:r,fallback:e=null,children:u},i)=>{const t=o("userSubscription")?.features?.includes(r)||!1;return c(i,()=>({enabled:t}),[t]),t?n(a,{children:u}):e?n(a,{children:e}):null}),m=l(({tier:r,fallback:e=null,children:u},i)=>{const t=o("userSubscription"),d=r||"pro",s=t?.tier===d;return c(i,()=>({enabled:s}),[s]),s?n(a,{children:u}):e?n(a,{children:e}):null}),p=l((r,e)=>n(m,{ref:e,tier:"pro",...r})),h=l((r,e)=>n(m,{ref:e,tier:"premium",...r}));export{f as Feature,h as PremiumFeature,p as ProFeature};
1
+ "use client";import{Fragment as u,jsx as t}from"react/jsx-runtime";import{useImperativeHandle as l,forwardRef as s}from"react";import{useAuth as m}from"../useAuth";const h=s(({featureId:e,fallback:r=null,children:i},o)=>{const n=m("userSubscription")?.features?.includes(e)||!1;return l(o,()=>({enabled:n}),[n]),n?t(u,{children:i}):r?t(u,{children:r}):null}),a=s(({tier:e,fallback:r=null,children:i},o)=>{const p=m("userSubscription"),n=e||"pro",c=p?.tier===n;return l(o,()=>({enabled:c}),[c]),c?t(u,{children:i}):r?t(u,{children:r}):null}),x=s((e,r)=>t(a,{ref:r,tier:"pro",...e})),S=s((e,r)=>t(a,{ref:r,tier:"premium",...e}));export{h as Feature,S as PremiumFeature,x as ProFeature};
@@ -1 +1 @@
1
- "use client";import{jsx as e,jsxs as t,Fragment as q}from"react/jsx-runtime";import{Stack as f}from"@donotdev/components";import{useAuth as s}from"../useAuth";import{AuthFallback as F}from"./AuthFallback";function m({requiredTier:r,userTier:i}){return e("div",{className:"dndev-surface","data-variant":"default","data-shadow":"sm","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px solid var(--border)",backgroundColor:"var(--muted)"},children:t(f,{direction:"row",align:"center",gap:"medium",children:[e("span",{style:{color:"var(--accent)"},children:"\u{1F512}"}),t("div",{children:[e("p",{style:{fontWeight:500,fontSize:"var(--font-size-base)",color:"var(--foreground)"},children:r==="pro"?"Pro Feature":"Premium Feature"}),t("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:["Upgrade to ",r," to access this feature",i&&` (current: ${i})`]})]})]})})}function p({requiredRole:r,userRole:i}){const o=Array.isArray(r)?r.join(" or "):r;return e("div",{className:"dndev-surface","data-variant":"destructive","data-shadow":"sm","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px solid var(--destructive)",backgroundColor:"var(--muted)"},children:t(f,{direction:"row",align:"center",gap:"medium",children:[e("span",{style:{color:"var(--destructive)"},children:"\u{1F6AB}"}),t("div",{children:[e("p",{style:{fontWeight:500,fontSize:"var(--font-size-base)",color:"var(--destructive-foreground)"},children:"Access Denied"}),t("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:["This feature requires ",o," role",i&&` (current: ${i})`]})]})]})})}function h(){return e("div",{className:"dndev-surface","data-variant":"default","data-shadow":"sm","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px solid var(--border)",backgroundColor:"var(--muted)"},children:t(f,{direction:"row",align:"center",gap:"medium",children:[e("span",{style:{color:"var(--accent)"},children:"\u23F0"}),t("div",{children:[e("p",{style:{fontWeight:500,fontSize:"var(--font-size-base)",color:"var(--foreground)"},children:"Subscription Required"}),e("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:"This feature requires an active subscription"})]})]})})}function g({children:r,role:i,tier:o,subscription:c,validate:d,fallback:a,message:l,showUpgradePrompt:b=!0,showLoginPrompt:y=!0}){const A=s("user"),z=s("loading"),S=s("userProfile"),v=s("userSubscription"),x=s("hasRole"),P=s("hasTier"),n=S?.role,u=v?.tier;return z?e("div",{style:{height:"2rem",borderRadius:"var(--radius)",backgroundColor:"var(--muted)",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}):!A&&(i||o||c)?y?e(F,{message:l||"Please sign in to access this feature"}):null:i&&!(Array.isArray(i)?i:[i]).some(R=>n===R)?a?e(a,{requiredRole:i,userRole:n||void 0}):e(p,{requiredRole:i,userRole:n||void 0}):o&&u!==o?a?e(a,{requiredTier:o,userTier:u||"free"}):b?e(m,{requiredTier:o,userTier:u||"free"}):null:c&&!v?.isActive?a?e(a,{requiresSubscription:!0,hasSubscription:v?.isActive||!1}):e(h,{}):d&&n&&u&&!d(n,u)?a?e(a,{userRole:n,userTier:u}):e(p,{userRole:n}):e(q,{children:r})}function T(r){const i=s("user"),o=s("userProfile"),c=s("userSubscription"),d=o?.role,a=c?.tier;return!(!i&&(r.role||r.tier||r.subscription)||r.role&&!(Array.isArray(r.role)?r.role:[r.role]).some(l=>d===l)||r.tier&&a!==r.tier||r.subscription&&!c?.isActive||r.validate&&d&&a&&!r.validate(d,a))}function w(r,i){return o=>e(g,{...i,children:e(r,{...o})})}export{p as AccessDenied,g as FeatureGuard,h as SubscriptionExpired,m as UpgradePrompt,T as useCanAccessFeature,w as withFeatureGuard};
1
+ "use client";import{jsx as r,jsxs as o,Fragment as q}from"react/jsx-runtime";import{Stack as p}from"@donotdev/components";import{useAuth as n}from"../useAuth";import{AuthFallback as x}from"./AuthFallback";function g({requiredTier:e,userTier:i}){return r("div",{className:"dndev-surface","data-variant":"default","data-shadow":"sm","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px solid var(--border)",backgroundColor:"var(--muted)"},children:o(p,{direction:"row",align:"center",gap:"medium",children:[r("span",{style:{color:"var(--accent)"},children:"\u{1F512}"}),o("div",{children:[r("p",{style:{fontWeight:500,fontSize:"var(--font-size-base)",color:"var(--foreground)"},children:e==="pro"?"Pro Feature":"Premium Feature"}),o("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:["Upgrade to ",e," to access this feature",i&&` (current: ${i})`]})]})]})})}function v({requiredRole:e,userRole:i}){const s=Array.isArray(e)?e.join(" or "):e;return r("div",{className:"dndev-surface","data-variant":"destructive","data-shadow":"sm","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px solid var(--destructive)",backgroundColor:"var(--muted)"},children:o(p,{direction:"row",align:"center",gap:"medium",children:[r("span",{style:{color:"var(--destructive)"},children:"\u{1F6AB}"}),o("div",{children:[r("p",{style:{fontWeight:500,fontSize:"var(--font-size-base)",color:"var(--destructive-foreground)"},children:"Access Denied"}),o("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:["This feature requires ",s," role",i&&` (current: ${i})`]})]})]})})}function R(){return r("div",{className:"dndev-surface","data-variant":"default","data-shadow":"sm","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px solid var(--border)",backgroundColor:"var(--muted)"},children:o(p,{direction:"row",align:"center",gap:"medium",children:[r("span",{style:{color:"var(--accent)"},children:"\u23F0"}),o("div",{children:[r("p",{style:{fontWeight:500,fontSize:"var(--font-size-base)",color:"var(--foreground)"},children:"Subscription Required"}),r("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:"This feature requires an active subscription"})]})]})})}function z({children:e,role:i,tier:s,subscription:a,validate:d,fallback:t,message:h,showUpgradePrompt:m=!0,showLoginPrompt:l=!0}){const b=n("user"),y=n("loading"),A=n("userProfile"),f=n("userSubscription"),T=n("hasRole"),D=n("hasTier"),u=A?.role,c=f?.tier;return y?r("div",{style:{height:"2rem",borderRadius:"var(--radius)",backgroundColor:"var(--muted)",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}):!b&&(i||s||a)?l?r(x,{message:h||"Please sign in to access this feature"}):null:i&&!(Array.isArray(i)?i:[i]).some(S=>u===S)?t?r(t,{requiredRole:i,userRole:u||void 0}):r(v,{requiredRole:i,userRole:u||void 0}):s&&c!==s?t?r(t,{requiredTier:s,userTier:c||"free"}):m?r(g,{requiredTier:s,userTier:c||"free"}):null:a&&!f?.isActive?t?r(t,{requiresSubscription:!0,hasSubscription:f?.isActive||!1}):r(R,{}):d&&u&&c&&!d(u,c)?t?r(t,{userRole:u,userTier:c}):r(v,{userRole:u}):r(q,{children:e})}function E(e){const i=n("user"),s=n("userProfile"),a=n("userSubscription"),d=s?.role,t=a?.tier;return!(!i&&(e.role||e.tier||e.subscription)||e.role&&!(Array.isArray(e.role)?e.role:[e.role]).some(l=>d===l)||e.tier&&t!==e.tier||e.subscription&&!a?.isActive||e.validate&&d&&t&&!e.validate(d,t))}function F(e,i){return a=>r(z,{...i,children:r(e,{...a})})}export{v as AccessDenied,z as FeatureGuard,R as SubscriptionExpired,g as UpgradePrompt,E as useCanAccessFeature,F as withFeatureGuard};
@@ -1 +1 @@
1
- "use client";import{jsxs as o,jsx as d}from"react/jsx-runtime";import"react";import{cn as s}from"@donotdev/components";import{useAuth as i}from"../useAuth";function c({featureId:e,featureName:r,className:a="",children:t}){if(i("userSubscription")?.features?.includes(e))return null;const n=d("div",{className:s("dndev-surface",a),"data-variant":"muted","data-shadow":"none","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px dashed var(--border)",backgroundColor:"var(--muted)"},children:o("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)",textAlign:"center"},children:[r," is not available on your current plan."]})});return t||n}function u(e,r){return function({featureName:a,className:t="",children:n}){if(i("userSubscription")?.tier===e)return null;const l=d("div",{className:s("dndev-surface",t),"data-variant":"muted","data-shadow":"none","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px dashed var(--border)",backgroundColor:"var(--muted)"},children:o("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)",textAlign:"center"},children:[a," is only available on ",r," tier."]})});return n||l}}const m=u("pro","Pro"),f=u("premium","Premium");export{c as FeaturePlaceholder,f as PremiumFeaturePlaceholder,m as ProFeaturePlaceholder};
1
+ "use client";import{jsxs as d,jsx as i}from"react/jsx-runtime";import"react";import{cn as c}from"@donotdev/components";import{useAuth as u}from"../useAuth";function g({featureId:e,featureName:r,className:t="",children:a}){if(u("userSubscription")?.features?.includes(e)||!1)return null;const n=i("div",{className:c("dndev-surface",t),"data-variant":"muted","data-shadow":"none","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px dashed var(--border)",backgroundColor:"var(--muted)"},children:d("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)",textAlign:"center"},children:[r," is not available on your current plan."]})});return a||n}function l(e,r){return function({featureName:a,className:o="",children:s}){if(u("userSubscription")?.tier===e)return null;const m=i("div",{className:c("dndev-surface",o),"data-variant":"muted","data-shadow":"none","data-radius":"lg",style:{padding:"var(--gap-md)",border:"1px dashed var(--border)",backgroundColor:"var(--muted)"},children:d("p",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)",textAlign:"center"},children:[a," is only available on ",r," tier."]})});return s||m}}const x=l("pro","Pro"),P=l("premium","Premium");export{g as FeaturePlaceholder,P as PremiumFeaturePlaceholder,x as ProFeaturePlaceholder};
@@ -1 +1 @@
1
- "use client";import{jsx as e,jsxs as S}from"react/jsx-runtime";import"react";import{Card as i,Spinner as w,Stack as I}from"@donotdev/components";import{useTranslation as N}from"@donotdev/core";import{useGoogleOneTap as T}from"../hooks/useGoogleOneTap";function z({clientId:s,onSuccess:l,onError:c,autoSelect:p=!0,cancelOnTapOutside:m=!0,className:g="",disabled:r=!1,promptParentId:h,allowedParentOrigins:a,cspNonce:u,clientOnly:n=!1,showErrorDetails:L=!1,loadingComponent:d,errorComponent:b,browserNotSupportedComponent:j}){const{t:v}=N("dndev"),{shouldShow:f,isLoaded:E,isLoading:x,error:O,containerRef:y,fedcmSupported:o,isHydrated:t,browserInfo:P}=T({clientId:s,autoSelect:p,cancelOnTapOutside:m,promptParentId:h,disabled:r,onSuccess:l,onError:c,allowedParentOrigins:a,cspNonce:u,clientOnly:n});return r||!f||n&&!t?null:x?d?e("div",{className:"dndev-fixed",style:{right:"var(--gap-md)",zIndex:50,top:"calc(1rem + var(--header-height, 0px))"},children:e(i,{style:{padding:"var(--gap-md)"},children:e(d,{})})}):e("div",{className:"dndev-fixed",style:{right:"var(--gap-md)",zIndex:50,top:"calc(1rem + var(--header-height, 0px))"},children:e(i,{style:{padding:"var(--gap-md)"},children:S(I,{direction:"row",align:"center",gap:"medium",children:[e(w,{}),e("span",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:v("auth.googleOneTapLoading","Loading Google One Tap...")})]})})}):!o||O?null:e("div",{className:"dndev-fixed",style:{right:"var(--gap-md)",zIndex:50,top:"calc(1rem + var(--header-height, 0px))"},children:e("div",{ref:y,className:`google-one-tap-container ${g}`.trim(),"data-testid":"google-one-tap","data-fedcm-supported":o,"data-hydrated":t,...a&&{"data-allowed-parent-origins":a.join(",")}})})}var C=z;export{C as default};
1
+ "use client";import{jsx as e,jsxs as N}from"react/jsx-runtime";import"react";import{Card as i,Spinner as j,Stack as w}from"@donotdev/components";import{useTranslation as z}from"@donotdev/core";import{useGoogleOneTap as C}from"../hooks/useGoogleOneTap";function T({clientId:s,onSuccess:p,onError:l,autoSelect:m=!0,cancelOnTapOutside:c=!0,className:g="",disabled:o=!1,promptParentId:f,allowedParentOrigins:r,cspNonce:u,clientOnly:a=!1,showErrorDetails:I=!1,loadingComponent:t,errorComponent:G,browserNotSupportedComponent:L}){const{t:h}=z("dndev"),{shouldShow:v,isLoaded:E,isLoading:x,error:y,containerRef:S,fedcmSupported:d,isHydrated:n,browserInfo:_}=C({clientId:s,autoSelect:m,cancelOnTapOutside:c,promptParentId:f,disabled:o,onSuccess:p,onError:l,allowedParentOrigins:r,cspNonce:u,clientOnly:a});return o||!v||a&&!n?null:x?t?e("div",{className:"dndev-fixed",style:{right:"var(--gap-md)",zIndex:50,top:"calc(1rem + var(--header-height, 0px))"},children:e(i,{style:{padding:"var(--gap-md)"},children:e(t,{})})}):e("div",{className:"dndev-fixed",style:{right:"var(--gap-md)",zIndex:50,top:"calc(1rem + var(--header-height, 0px))"},children:e(i,{style:{padding:"var(--gap-md)"},children:N(w,{direction:"row",align:"center",gap:"medium",children:[e(j,{}),e("span",{style:{fontSize:"var(--font-size-sm)",color:"var(--muted-foreground)"},children:h("auth.googleOneTapLoading","Loading Google One Tap...")})]})})}):!d||y?null:e("div",{className:"dndev-fixed",style:{right:"var(--gap-md)",zIndex:50,top:"calc(1rem + var(--header-height, 0px))"},children:e("div",{ref:S,className:`google-one-tap-container ${g}`.trim(),"data-testid":"google-one-tap","data-fedcm-supported":d,"data-hydrated":n,...r&&{"data-allowed-parent-origins":r.join(",")}})})}var O=T;export{O as default};
@@ -1 +1 @@
1
- "use client";import{jsx as o}from"react/jsx-runtime";import{Dialog as i}from"@donotdev/components";import{useTranslation as a}from"@donotdev/core";import{withAuthFallback as r}from"./AuthFallback";import s from"./MultipleAuthProviders";function p({open:t,onOpenChange:e}){const{t:n}=a("dndev");return o(i,{open:t,onOpenChange:e,title:n("signIn","Sign In"),description:n("choosePlatform","Choose a platform to sign in with"),children:o("div",{style:{padding:"var(--gap-md)"},children:o(s,{layout:"vertical",showLabels:!0,method:"popup"})})})}const l=r(p,{message:"Authentication is not configured",showLoginButton:!0});var m=l;export{m as default};
1
+ "use client";import{jsx as o}from"react/jsx-runtime";import{Dialog as e}from"@donotdev/components";import{useTranslation as r}from"@donotdev/core";import{withAuthFallback as a}from"./AuthFallback";import s from"./MultipleAuthProviders";function l({open:n,onOpenChange:i}){const{t}=r("dndev");return o(e,{open:n,onOpenChange:i,title:t("signIn","Sign In"),description:t("choosePlatform","Choose a platform to sign in with"),children:o("div",{style:{padding:"var(--gap-md)"},children:o(s,{layout:"vertical",showLabels:!0,method:"popup"})})})}const p=a(l,{message:"Authentication is not configured",showLoginButton:!0});var g=p;export{g as default};
@@ -1 +1 @@
1
- "use client";import{jsx as a,jsxs as z}from"react/jsx-runtime";import{Suspense as L,lazy as T}from"react";import{Alert as $,ALERT_VARIANT as k,Stack as I,Grid as M}from"@donotdev/components";import{useTranslation as S,getEnabledAuthPartners as E}from"@donotdev/core";import{useAuth as m}from"../useAuth";import{withAuthFallback as j}from"./AuthFallback";import G from"./AuthPartnerButton";import{getAuthMethod as O}from"../constants";import{useAccountLinking as P}from"../hooks/useAccountLinking";const q=({providers:c,containerClassName:i="",providerClassName:p="",method:u,size:_="md",layout:e="vertical",showLabels:h=!0,spacing:t="medium",ariaLabel:g,id:v,fullWidth:f=!0,emailMode:A="signin"})=>{const{t:s}=S("dndev"),n=v||`auth-providers-${Math.random().toString(36).slice(2,9)}`,{isRequired:b}=P(),N=T(()=>import("./AccountLinking")),w=O(u),r=c||E();if(!r||r.length===0)return a("div",{className:i,children:a("p",{children:"No authentication providers are configured"})});const l=m("error"),R=m("isAvailable"),x=()=>{const d=r.map((o,y)=>a(G,{partnerId:o,method:w,className:`${p} ${f?"dndev-w-full":""}`,tabIndex:y===0?0:void 0,id:`${n}-${o}-button`,emailMode:A,children:h?void 0:null},o));return e==="grid"?a(M,{cols:2,gap:t,className:i,children:d}):a(I,{direction:e==="horizontal"?"row":"column",wrap:e==="horizontal"?"wrap":void 0,gap:t,align:e==="horizontal"?"center":"stretch",className:i,children:d})};return z("div",{className:"dndev-mx-auto",id:n,role:"region","aria-label":g||s("aria.signInOptions","Sign in options"),children:[x(),l&&R&&a($,{variant:k.ERROR,style:{marginTop:"var(--gap-md)"},description:l.message||s("auth.errorGeneric","Authentication failed. Please try again.")}),b&&a("div",{style:{marginTop:"var(--gap-md)"},children:a(L,{fallback:null,children:a(N,{})})})]})},B=j(q,{message:"Authentication providers are not configured",showLoginButton:!0});var C=B;export{C as default};
1
+ "use client";import{jsx as e,jsxs as z}from"react/jsx-runtime";import{Suspense as L,lazy as M}from"react";import{Alert as N,ALERT_VARIANT as T,Stack as $,Grid as j}from"@donotdev/components";import{useTranslation as E,getEnabledAuthPartners as S}from"@donotdev/core";import{useAuth as c}from"../useAuth";import{withAuthFallback as I}from"./AuthFallback";import _ from"./AuthPartnerButton";import{getAuthMethod as q}from"../constants";import{useAccountLinking as y}from"../hooks/useAccountLinking";const B=({providers:u,containerClassName:t="",providerClassName:m="",method:h,size:O="md",layout:r="vertical",showLabels:p=!0,spacing:o="medium",ariaLabel:g,id:f,fullWidth:v=!0,emailMode:A="signin"})=>{const{t:a}=E("dndev"),s=f||`auth-providers-${Math.random().toString(36).slice(2,9)}`,{isRequired:b}=y(),x=M(()=>import("./AccountLinking")),P=q(h),i=u||S();if(!i||i.length===0)return e("div",{className:t,children:e("p",{children:"No authentication providers are configured"})});const d=c("error"),R=c("isAvailable"),k=()=>{const l=i.map((n,w)=>e(_,{partnerId:n,method:P,className:`${m} ${v?"dndev-w-full":""}`,tabIndex:w===0?0:void 0,id:`${s}-${n}-button`,emailMode:A,children:p?void 0:null},n));return r==="grid"?e(j,{cols:2,gap:o,className:t,children:l}):e($,{direction:r==="horizontal"?"row":"column",wrap:r==="horizontal"?"wrap":void 0,gap:o,align:r==="horizontal"?"center":"stretch",className:t,children:l})};return z("div",{className:"dndev-mx-auto",id:s,role:"region","aria-label":g||a("aria.signInOptions","Sign in options"),children:[k(),d&&R&&e(N,{variant:T.ERROR,style:{marginTop:"var(--gap-md)"},description:d.message||a("auth.errorGeneric","Authentication failed. Please try again.")}),b&&e("div",{style:{marginTop:"var(--gap-md)"},children:e(L,{fallback:null,children:e(x,{})})})]})},G=I(B,{message:"Authentication providers are not configured",showLoginButton:!0});var X=G;export{X as default};
@@ -1 +1 @@
1
- "use client";import{jsx as t,jsxs as r}from"react/jsx-runtime";import{Alert as s,Button as l,BUTTON_VARIANT as u,Stack as c}from"@donotdev/components";import{useTranslation as f}from"@donotdev/core";import{useNetworkStatus as d}from"../hooks/useNetworkStatus";function w({showWhenOnline:a=!1,className:i=""}){const{t:e}=f("auth"),{online:n,connectionType:o,isSlowConnection:m}=d();return n&&!a?null:t(s,{variant:n?void 0:"error",className:i,role:"status","aria-live":n?"polite":"assertive",title:n?e("networkStatus.online",{defaultValue:"You are online"}):e("networkStatus.offline",{defaultValue:"You are offline"}),description:n?t("span",{children:e("networkStatus.connectedVia",{connectionType:o||"unknown",defaultValue:`Connected via ${o||"unknown"}`})}):r(c,{gap:"medium",children:[t("p",{children:e("networkStatus.offlineMessage",{defaultValue:"Authentication requires an internet connection. Please check your network settings."})}),t(l,{variant:u.GHOST,onClick:()=>{typeof window<"u"&&window.location.reload()},style:{fontSize:"var(--font-size-sm)",textDecoration:"underline",fontWeight:500},children:e("networkStatus.checkAgain",{defaultValue:"Check again"})})]})})}var k=w;export{k as default};
1
+ "use client";import{jsx as t,jsxs as r}from"react/jsx-runtime";import{Alert as s,Button as l,BUTTON_VARIANT as u,Stack as c}from"@donotdev/components";import{useTranslation as f}from"@donotdev/core";import{useNetworkStatus as d}from"../hooks/useNetworkStatus";function k({showWhenOnline:i=!1,className:a=""}){const{t:e}=f("auth"),{online:n,connectionType:o,isSlowConnection:w}=d();return n&&!i?null:t(s,{variant:n?void 0:"error",className:a,role:"status","aria-live":n?"polite":"assertive",title:n?e("networkStatus.online",{defaultValue:"You are online"}):e("networkStatus.offline",{defaultValue:"You are offline"}),description:n?t("span",{children:e("networkStatus.connectedVia",{connectionType:o||"unknown",defaultValue:`Connected via ${o||"unknown"}`})}):r(c,{gap:"medium",children:[t("p",{children:e("networkStatus.offlineMessage",{defaultValue:"Authentication requires an internet connection. Please check your network settings."})}),t(l,{variant:u.GHOST,onClick:()=>{typeof window<"u"&&window.location.reload()},style:{fontSize:"var(--font-size-sm)",textDecoration:"underline",fontWeight:500},children:e("networkStatus.checkAgain",{defaultValue:"Check again"})})]})})}var T=k;export{T as default};
@@ -1 +1 @@
1
- "use client";import{jsx as a,jsxs as t,Fragment as T}from"react/jsx-runtime";import"lucide-react";import{useState as o}from"react";import{Button as p,BUTTON_VARIANT as f,Input as m,Label as P,Alert as A,ALERT_VARIANT as E,Dialog as N,Stack as c}from"@donotdev/components";import{useTranslation as I}from"@donotdev/core";function R({updatePassword:y}){const{t:r}=I("profile"),[C,d]=o(!1),[s,w]=o(""),[n,u]=o(""),[l,g]=o(!1),[h,i]=o(null),v=async()=>{if(s!==n){i("Passwords do not match");return}if(s.length<6){i("Password must be at least 6 characters long");return}g(!0),i(null);try{await y(s),d(!1),w(""),u("")}catch(e){i(e.message||"Failed to update password")}finally{g(!1)}};return a(N,{open:C,onOpenChange:d,trigger:a(p,{variant:f.OUTLINE,children:r("profile.security.password.change","Change Password")}),title:r("profile.security.password.dialog.title","Change Password"),description:r("profile.security.password.dialog.description","Enter your new password below"),footer:t(T,{children:[a(p,{variant:f.OUTLINE,onClick:()=>d(!1),disabled:l,children:r("profile.security.password.dialog.cancel","Cancel")}),a(p,{onClick:v,disabled:l||!s||!n,children:l?r("profile.security.password.dialog.updating","Updating..."):r("profile.security.password.dialog.update","Update Password")})]}),children:t(c,{gap:"medium",children:[t(c,{gap:"tight",children:[a(P,{htmlFor:"newPassword",children:r("profile.security.password.dialog.newPassword","New Password")}),a(m,{id:"newPassword",type:"password",value:s,onChange:e=>w(e.target.value),placeholder:"Enter new password"})]}),t(c,{gap:"tight",children:[a(P,{htmlFor:"confirmPassword",children:r("profile.security.password.dialog.confirmPassword","Confirm Password")}),a(m,{id:"confirmPassword",type:"password",value:n,onChange:e=>u(e.target.value),placeholder:"Confirm new password"})]}),h&&a(A,{variant:E.ERROR,description:h})]})})}var U=R;export{U as default};
1
+ "use client";import{jsx as r,jsxs as i,Fragment as U}from"react/jsx-runtime";import"lucide-react";import{useState as o}from"react";import{Button as p,BUTTON_VARIANT as h,Input as m,Label as P,Alert as v,ALERT_VARIANT as A,Dialog as E,Stack as c}from"@donotdev/components";import{useTranslation as N}from"@donotdev/core";function I({updatePassword:y}){const{t:s}=N("profile"),[C,n]=o(!1),[e,w]=o(""),[d,g]=o(""),[l,f]=o(!1),[u,t]=o(null),T=async()=>{if(e!==d){t("Passwords do not match");return}if(e.length<6){t("Password must be at least 6 characters long");return}f(!0),t(null);try{await y(e),n(!1),w(""),g("")}catch(a){t(a.message||"Failed to update password")}finally{f(!1)}};return r(E,{open:C,onOpenChange:n,trigger:r(p,{variant:h.OUTLINE,children:s("profile.security.password.change","Change Password")}),title:s("profile.security.password.dialog.title","Change Password"),description:s("profile.security.password.dialog.description","Enter your new password below"),footer:i(U,{children:[r(p,{variant:h.OUTLINE,onClick:()=>n(!1),disabled:l,children:s("profile.security.password.dialog.cancel","Cancel")}),r(p,{onClick:T,disabled:l||!e||!d,children:l?s("profile.security.password.dialog.updating","Updating..."):s("profile.security.password.dialog.update","Update Password")})]}),children:i(c,{gap:"medium",children:[i(c,{gap:"tight",children:[r(P,{htmlFor:"newPassword",children:s("profile.security.password.dialog.newPassword","New Password")}),r(m,{id:"newPassword",type:"password",value:e,onChange:a=>w(a.target.value),placeholder:"Enter new password"})]}),i(c,{gap:"tight",children:[r(P,{htmlFor:"confirmPassword",children:s("profile.security.password.dialog.confirmPassword","Confirm Password")}),r(m,{id:"confirmPassword",type:"password",value:d,onChange:a=>g(a.target.value),placeholder:"Confirm new password"})]}),u&&r(v,{variant:A.ERROR,description:u})]})})}var j=I;export{j as default};
@@ -1 +1 @@
1
- "use client";import"react";import{useTranslation as t}from"@donotdev/core";const e=({identifier:a,className:n=""})=>{const{t:s}=t("auth");return null};var r=e;export{r as default};
1
+ "use client";import"react";import{useTranslation as t}from"@donotdev/core";const e=({identifier:r,className:i=""})=>{const{t:n}=t("auth");return null};var l=e;export{l as default};
@@ -1 +1 @@
1
- export*from"./AuthFallback";import{default as o}from"./EmailPasswordForm";import{default as a}from"./AuthPartnerButton";import{default as r}from"./EmailVerification";export*from"./Feature";export*from"./FeatureGuard";export*from"./FeaturePlaceholder";import{default as t}from"./GoogleOneTap";import{default as m}from"./LoginModal";import{default as e}from"./MultipleAuthProviders";import{default as f}from"./NetworkStatusIndicator";import{default as s}from"./PasswordUpdateDialog";import{default as i}from"./RateLimitAlert";export*from"./DeleteAccountDialogs";export{a as AuthPartnerButton,o as EmailPasswordForm,r as EmailVerification,t as GoogleOneTap,m as LoginModal,e as MultipleAuthProviders,f as NetworkStatusIndicator,s as PasswordUpdateDialog,i as RateLimitAlert};
1
+ export*from"./AuthFallback";import{default as e}from"./EmailPasswordForm";import{default as f}from"./AuthPartnerButton";import{default as l}from"./EmailVerification";export*from"./Feature";export*from"./FeatureGuard";export*from"./FeaturePlaceholder";import{default as x}from"./GoogleOneTap";import{default as n}from"./LoginModal";import{default as g}from"./MultipleAuthProviders";import{default as A}from"./NetworkStatusIndicator";import{default as h}from"./PasswordUpdateDialog";import{default as L}from"./RateLimitAlert";export*from"./DeleteAccountDialogs";export{f as AuthPartnerButton,e as EmailPasswordForm,l as EmailVerification,x as GoogleOneTap,n as LoginModal,g as MultipleAuthProviders,A as NetworkStatusIndicator,h as PasswordUpdateDialog,L as RateLimitAlert};
package/dist/constants.js CHANGED
@@ -1 +1 @@
1
- import"@donotdev/components";import{isDev as r}from"@donotdev/core";function t(e){return!(r()||e==="modal")}function o(e){return e||(r()?"popup":"redirect")}import{AUTH_PARTNER_STATE as i}from"@donotdev/core";const n={VERIFIED:"verified",PENDING:"pending",ERROR:"error"};export{n as EMAIL_VERIFICATION_STATUS,i as PARTNER_STATE,o as getAuthMethod,t as getDefaultUseRedirect};
1
+ import"@donotdev/components";import{isDev as t}from"@donotdev/core";function n(e){return!(t()||e==="modal")}function u(e){return e||(t()?"popup":"redirect")}import{AUTH_PARTNER_STATE as s}from"@donotdev/core";const f={VERIFIED:"verified",PENDING:"pending",ERROR:"error"};export{f as EMAIL_VERIFICATION_STATUS,s as PARTNER_STATE,u as getAuthMethod,n as getDefaultUseRedirect};
@@ -1 +1 @@
1
- "use client";import{useState as I,useEffect as k,useCallback as s}from"react";import{safeSessionStorage as e,handleError as p,isClient as t}from"@donotdev/core";import{getAuthMethod as L}from"../constants";import{useAuth as a}from"../useAuth";function v(){const r=a("signInWithPartner"),c=a("user"),[i,o]=I(null);k(()=>{if(t()){try{const n=e.getItem("accountLinkingInfo");if(n){const h=JSON.parse(n);o(h)}}catch{}return()=>{if(!t())return;const n=e.getItem("accountLinkingInfo");if(n)try{JSON.parse(n).isRequired||e.removeItem("accountLinkingInfo")}catch{}}}},[c]);const u=s(async()=>{if(!(!i||!i.isRequired))try{const{existingProvider:n}=i;if(n==="password"||n==="emailLink")return;await r(n,L())}catch(n){p(n)}},[i,r]),l=s(()=>{t()&&(e.removeItem("accountLinkingInfo"),o(null))},[]),f=i?.isRequired||!1,g=i?.email||null,m=i?.existingProvider||null,d=i?.newProvider||null;return{accountLinking:i,isRequired:f,email:g,existingProvider:m,newProvider:d,handleSignInWithExistingProvider:u,clearAccountLinking:l}}export{v as useAccountLinking};
1
+ "use client";import{useState as p,useEffect as h,useCallback as u}from"react";import{safeSessionStorage as e,handleError as L,isClient as t}from"@donotdev/core";import{getAuthMethod as I}from"../constants";import{useAuth as a}from"../useAuth";function x(){const r=a("signInWithPartner"),o=a("user"),[i,s]=p(null);h(()=>{if(t()){try{const n=e.getItem("accountLinkingInfo");if(n){const c=JSON.parse(n);s(c)}}catch{}return()=>{if(!t())return;const n=e.getItem("accountLinkingInfo");if(n)try{JSON.parse(n).isRequired||e.removeItem("accountLinkingInfo")}catch{}}}},[o]);const l=u(async()=>{if(!(!i||!i.isRequired))try{const{existingProvider:n}=i;if(n==="password"||n==="emailLink")return;await r(n,I())}catch(n){L(n)}},[i,r]),g=u(()=>{t()&&(e.removeItem("accountLinkingInfo"),s(null))},[]),f=i?.isRequired||!1,d=i?.email||null,m=i?.existingProvider||null,k=i?.newProvider||null;return{accountLinking:i,isRequired:f,email:d,existingProvider:m,newProvider:k,handleSignInWithExistingProvider:l,clearAccountLinking:g}}export{x as useAccountLinking};
@@ -1 +1 @@
1
- "use client";import{useState as l,useCallback as t}from"react";function g({defaultValue:r="popup"}={}){const[o,e]=l(r),u=o==="redirect",d=o==="popup",i=t(()=>{e(p=>p==="redirect"?"popup":"redirect")},[]),s=t(()=>{e("redirect")},[]),a=t(()=>{e("popup")},[]),c=t(p=>{e(p?"redirect":"popup")},[]);return{isRedirectMode:u,isPopupMode:d,authMethod:o,toggleMode:i,setRedirectMode:s,setPopupMode:a,handleToggleChange:c}}export{g as useAuthMethodToggle};
1
+ "use client";import{useState as h,useCallback as t}from"react";function g({defaultValue:c="popup"}={}){const[o,e]=h(c),r=o==="redirect",d=o==="popup",s=t(()=>{e(p=>p==="redirect"?"popup":"redirect")},[]),u=t(()=>{e("redirect")},[]),n=t(()=>{e("popup")},[]),i=t(p=>{e(p?"redirect":"popup")},[]);return{isRedirectMode:r,isPopupMode:d,authMethod:o,toggleMode:s,setRedirectMode:u,setPopupMode:n,handleToggleChange:i}}export{g as useAuthMethodToggle};
@@ -1 +1 @@
1
- "use client";import{useCallback as t}from"react";import"../constants";import{useAuth as o}from"../useAuth";function I(r,g={}){const h=o("getPartnerState"),e=o("setPartnerState"),d=o("signInWithPartner"),i=o("partnerError"),{onSuccess:s,onError:l}=g,u=h(r),p=u==="authenticated",m=u==="loading",n=i?.partnerId===r,E=n&&i?.error?new Error(i.error):null,c=t(()=>{n&&e(r,"idle")},[n,r,e]),S=t(()=>{e(r,"loading")},[r,e]),f=t(()=>{e(r,"idle")},[r,e]),A=t(async P=>{n&&c();try{e(r,"loading");const a=await d(r,P);if(a===null){e(r,"idle");return}a&&s&&s(a)}catch(a){e(r,"error",a),l&&l(a)}},[r,n,c,e,d,s,l]);return{partnerState:u,isAuthenticated:p,isAuthenticating:m,hasError:n,error:E,handleSignIn:A,clearError:c,setLoading:S,setIdle:f}}export{I as useAuthPartner};
1
+ "use client";import{useCallback as e}from"react";import"../constants";import{useAuth as s}from"../useAuth";function x(t,h={}){const f=s("getPartnerState"),r=s("setPartnerState"),g=s("signInWithPartner"),i=s("partnerError"),{onSuccess:c,onError:a}=h,l=f(t),P=l==="authenticated",S=l==="loading",n=i?.partnerId===t,m=n&&i?.error?new Error(i.error):null,u=e(()=>{n&&r(t,"idle")},[n,t,r]),E=e(()=>{r(t,"loading")},[t,r]),A=e(()=>{r(t,"idle")},[t,r]),w=e(async y=>{n&&u();try{r(t,"loading");const o=await g(t,y);if(o===null){r(t,"idle");return}o&&c&&c(o)}catch(o){r(t,"error",o),a&&a(o)}},[t,n,u,r,g,c,a]);return{partnerState:l,isAuthenticated:P,isAuthenticating:S,hasError:n,error:m,handleSignIn:w,clearError:u,setLoading:E,setIdle:A}}export{x as useAuthPartner};
@@ -1 +1 @@
1
- "use client";import{useState as o}from"react";import{useAuth as f}from"../useAuth";function A(){const c=f("deleteAccount"),[r,e]=o(!1),[u,t]=o(!1),[i,n]=o(!1),[m,l]=o(null);return{showConfirmDialog:r,showPasswordDialog:u,isDeleting:i,error:m,startDeleteFlow:()=>{l(null),e(!0)},confirmDelete:async D=>{n(!0),l(null);try{await c(D),e(!1),t(!1)}catch(a){const s=a.message||a.message;s==="REQUIRES_PASSWORD"?(e(!1),t(!0)):s==="REAUTH_CANCELLED"?(e(!1),t(!1)):l(s||"Failed to delete account")}finally{n(!1)}},cancel:()=>{e(!1),t(!1),l(null)}}}export{A as useDeleteAccount};
1
+ "use client";import{useState as l}from"react";import{useAuth as m}from"../useAuth";function E(){const r=m("deleteAccount"),[c,e]=l(!1),[f,s]=l(!1),[i,a]=l(!1),[u,t]=l(null);return{showConfirmDialog:c,showPasswordDialog:f,isDeleting:i,error:u,startDeleteFlow:()=>{t(null),e(!0)},confirmDelete:async D=>{a(!0),t(null);try{await r(D),e(!1),s(!1)}catch(n){const o=n.message||n.message;o==="REQUIRES_PASSWORD"?(e(!1),s(!0)):o==="REAUTH_CANCELLED"?(e(!1),s(!1)):t(o||"Failed to delete account")}finally{a(!1)}},cancel:()=>{e(!1),s(!1),t(null)}}}export{E as useDeleteAccount};
@@ -1 +1 @@
1
- "use client";import{useEffect as g,useState as t,useCallback as E}from"react";import{handleError as k}from"@donotdev/core";import{useAuth as s}from"../useAuth";function l(){const o=s("isSignInWithEmailLink"),a=s("signInWithEmailLink"),[r,n]=t(!1),[m,e]=t(null),c=o();g(()=>{if(typeof window<"u"){const i=localStorage.getItem("emailForSignIn");i&&e(i)}},[]);const u=E(async i=>{if(i){n(!0);try{(await a(i))?.success&&(localStorage.removeItem("emailForSignIn"),e(null))}catch(f){k(f)}finally{n(!1)}}},[a]);return{isEmailLink:c,isProcessing:r,email:m,completeEmailLinkSignIn:u}}var I=l;export{I as default,l as useEmailLinkAuth};
1
+ "use client";import{useEffect as f,useState as l,useCallback as g}from"react";import{handleError as E}from"@donotdev/core";import{useAuth as o}from"../useAuth";function k(){const r=o("isSignInWithEmailLink"),n=o("signInWithEmailLink"),[a,e]=l(!1),[m,t]=l(null),c=r();f(()=>{if(typeof window<"u"){const i=localStorage.getItem("emailForSignIn");i&&t(i)}},[]);const u=g(async i=>{if(i){e(!0);try{(await n(i))?.success&&(localStorage.removeItem("emailForSignIn"),t(null))}catch(s){E(s)}finally{e(!1)}}},[n]);return{isEmailLink:c,isProcessing:a,email:m,completeEmailLinkSignIn:u}}var L=k;export{L as default,k as useEmailLinkAuth};
@@ -1 +1 @@
1
- "use client";import{useState as r,useCallback as l}from"react";import{handleError as A}from"@donotdev/core";import{useAuth as f}from"../useAuth";function S(g={}){const t=f("sendSignInLinkToEmail"),E=f("isAvailable"),{onSuccess:s,onError:o,actionCodeSettings:m}=g,[e,h]=r(""),[u,d]=r(!1),[p,c]=r(!1),[k,n]=r(null),a=e.trim().length>0&&e.includes("@"),y=a&&!u&&E,L=l(()=>{n(null)},[]),b=l(async w=>{if(w.preventDefault(),!a){n("Please enter a valid email address");return}d(!0),n(null);try{typeof window<"u"&&localStorage.setItem("emailForSignIn",e.trim()),await t(e.trim(),m),c(!0),s?.()}catch(i){const I=i instanceof Error?i.message:"Failed to send sign-in link";n(I),o?.(i),A(i)}finally{d(!1)}},[e,a,t,m,s,o]),v=l(()=>{c(!1),n(null)},[]);return{email:e,setEmail:h,isLoading:u,isSent:p,error:k,handleSendLink:b,handleResend:v,clearError:L,isValid:a,canSubmit:y}}var F=S;export{F as default,S as useEmailLinkForm};
1
+ "use client";import{useState as i,useCallback as r}from"react";import{handleError as w}from"@donotdev/core";import{useAuth as f}from"../useAuth";function A(g={}){const o=f("sendSignInLinkToEmail"),S=f("isAvailable"),{onSuccess:a,onError:l,actionCodeSettings:c}=g,[e,E]=i(""),[d,u]=i(!1),[p,m]=i(!1),[h,n]=i(null),t=e.trim().length>0&&e.includes("@"),k=t&&!d&&S,I=r(()=>{n(null)},[]),L=r(async v=>{if(v.preventDefault(),!t){n("Please enter a valid email address");return}u(!0),n(null);try{typeof window<"u"&&localStorage.setItem("emailForSignIn",e.trim()),await o(e.trim(),c),m(!0),a?.()}catch(s){const y=s instanceof Error?s.message:"Failed to send sign-in link";n(y),l?.(s),w(s)}finally{u(!1)}},[e,t,o,c,a,l]),b=r(()=>{m(!1),n(null)},[]);return{email:e,setEmail:E,isLoading:d,isSent:p,error:h,handleSendLink:L,handleResend:b,clearError:I,isValid:t,canSubmit:k}}var T=A;export{T as default,A as useEmailLinkForm};
@@ -1 +1 @@
1
- "use client";import{useState as s,useEffect as w,useMemo as h}from"react";import{handleError as C,isClient as c}from"@donotdev/core";function S({checkGoogleServices:a=!0,onError:i}={}){const[n,u]=s(!1),[l,d]=s(!1),[m,p]=s(null);w(()=>{c()&&(async()=>{try{const e="IdentityCredential"in window;let o=!0;if(a){const r=new Promise(t=>setTimeout(t,2e3));await Promise.race([new Promise(t=>{const g=setInterval(()=>{window.google?.accounts?.id&&(clearInterval(g),t(!0))},100)}),r]),o=!!window.google?.accounts?.id}u(e&&o),d(!0)}catch(e){const o=C(e,{userMessage:"Failed to detect FedCM support",context:{operation:"fedcm_detection"},severity:"warning"});p(o),d(!0),i?.(o)}})()},[a,i]);const f=h(()=>{if(!c())return{name:"Unknown",isSupported:!1,recommendation:"Loading..."};const e=navigator.userAgent;let o="Unknown",r="Please update your browser";if(e.includes("Chrome/")){const t=parseInt(e.match(/Chrome\/(\d+)/)?.[1]||"0");o=`Chrome ${t}`,r=t>=116?"Supported":"Please update to Chrome 116 or later"}else if(e.includes("Edg/")){const t=parseInt(e.match(/Edg\/(\d+)/)?.[1]||"0");o=`Edge ${t}`,r=t>=116?"Supported":"Please update to Edge 116 or later"}else e.includes("Safari/")&&!e.includes("Chrome")?(o="Safari",r="Not supported yet. Please use Chrome or Edge"):e.includes("Firefox/")&&(o="Firefox",r="Not supported yet. Please use Chrome or Edge");return{name:o,isSupported:n,recommendation:r}},[n]);return{isSupported:n,isReady:l,error:m,browserInfo:f}}export{S as useFedCM};
1
+ "use client";import{useState as i,useEffect as C,useMemo as y}from"react";import{handleError as S,isClient as c}from"@donotdev/core";function P({checkGoogleServices:a=!0,onError:d}={}){const[s,l]=i(!1),[p,u]=i(!1),[m,f]=i(null);C(()=>{if(!c())return;(async()=>{try{const t="IdentityCredential"in window;let e=!0;if(a){const w=new Promise(n=>setTimeout(n,2e3));await Promise.race([new Promise(n=>{const h=setInterval(()=>{window.google?.accounts?.id&&(clearInterval(h),n(!0))},100)}),w]),e=!!window.google?.accounts?.id}l(t&&e),u(!0)}catch(t){const e=S(t,{userMessage:"Failed to detect FedCM support",context:{operation:"fedcm_detection"},severity:"warning"});f(e),u(!0),d?.(e)}})()},[a,d]);const g=y(()=>{if(!c())return{name:"Unknown",isSupported:!1,recommendation:"Loading..."};const o=navigator.userAgent;let t="Unknown",e="Please update your browser";if(o.includes("Chrome/")){const r=parseInt(o.match(/Chrome\/(\d+)/)?.[1]||"0");t=`Chrome ${r}`,e=r>=116?"Supported":"Please update to Chrome 116 or later"}else if(o.includes("Edg/")){const r=parseInt(o.match(/Edg\/(\d+)/)?.[1]||"0");t=`Edge ${r}`,e=r>=116?"Supported":"Please update to Edge 116 or later"}else o.includes("Safari/")&&!o.includes("Chrome")?(t="Safari",e="Not supported yet. Please use Chrome or Edge"):o.includes("Firefox/")&&(t="Firefox",e="Not supported yet. Please use Chrome or Edge");return{name:t,isSupported:s,recommendation:e}},[s]);return{isSupported:s,isReady:p,error:m,browserInfo:g}}export{P as useFedCM};
@@ -1 +1 @@
1
- {"version":3,"file":"useGoogleOneTap.d.ts","sourceRoot":"","sources":["../../src/hooks/useGoogleOneTap.ts"],"names":[],"mappings":"AA+IA;;GAEG;AACH,UAAU,sBAAsB;IAC9B,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,6CAA6C;IAC7C,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,4CAA4C;IAC5C,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,+BAA+B;IAC/B,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,uBAAuB;IACvB,SAAS,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,IAAI,CAAC;IAEzC,qBAAqB;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC,sCAAsC;IACtC,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhC,yBAAyB;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,uDAAuD;IACvD,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED;;GAEG;AACH,UAAU,qBAAqB;IAC7B,0CAA0C;IAC1C,QAAQ,EAAE,OAAO,CAAC;IAElB,2CAA2C;IAC3C,SAAS,EAAE,OAAO,CAAC;IAEnB,sCAAsC;IACtC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEpB,iCAAiC;IACjC,IAAI,EAAE,GAAG,CAAC;IAEV,kCAAkC;IAClC,MAAM,EAAE,OAAO,CAAC;IAEhB,qCAAqC;IACrC,cAAc,EAAE,OAAO,CAAC;IAExB,kDAAkD;IAClD,UAAU,EAAE,OAAO,CAAC;IAEpB,8CAA8C;IAC9C,YAAY,EAAE,KAAK,CAAC,SAAS,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAErD,gCAAgC;IAChC,UAAU,EAAE,MAAM,IAAI,CAAC;IAEvB,oCAAoC;IACpC,gBAAgB,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAExD,iCAAiC;IACjC,UAAU,EAAE,OAAO,CAAC;IAEpB,6CAA6C;IAC7C,WAAW,EAAE;QACX,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,OAAO,CAAC;QACrB,cAAc,EAAE,MAAM,CAAC;KACxB,CAAC;IAEF,+DAA+D;IAC/D,WAAW,EAAE,MAAM,IAAI,CAAC;IAExB,6CAA6C;IAC7C,aAAa,EAAE,OAAO,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,eAAe,CAAC,EAC9B,QAAQ,EACR,UAAiB,EACjB,kBAAyB,EACzB,cAAc,EACd,QAAgB,EAChB,SAAS,EACT,OAAO,EACP,oBAAoB,EACpB,QAAQ,EACR,UAAkB,GACnB,GAAE,sBAA2B,GAAG,qBAAqB,CAiWrD"}
1
+ {"version":3,"file":"useGoogleOneTap.d.ts","sourceRoot":"","sources":["../../src/hooks/useGoogleOneTap.ts"],"names":[],"mappings":"AA8IA;;GAEG;AACH,UAAU,sBAAsB;IAC9B,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,6CAA6C;IAC7C,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,4CAA4C;IAC5C,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,+BAA+B;IAC/B,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,uBAAuB;IACvB,SAAS,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,IAAI,CAAC;IAEzC,qBAAqB;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC,sCAAsC;IACtC,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhC,yBAAyB;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,uDAAuD;IACvD,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED;;GAEG;AACH,UAAU,qBAAqB;IAC7B,0CAA0C;IAC1C,QAAQ,EAAE,OAAO,CAAC;IAElB,2CAA2C;IAC3C,SAAS,EAAE,OAAO,CAAC;IAEnB,sCAAsC;IACtC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEpB,iCAAiC;IACjC,IAAI,EAAE,GAAG,CAAC;IAEV,kCAAkC;IAClC,MAAM,EAAE,OAAO,CAAC;IAEhB,qCAAqC;IACrC,cAAc,EAAE,OAAO,CAAC;IAExB,kDAAkD;IAClD,UAAU,EAAE,OAAO,CAAC;IAEpB,8CAA8C;IAC9C,YAAY,EAAE,KAAK,CAAC,SAAS,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAErD,gCAAgC;IAChC,UAAU,EAAE,MAAM,IAAI,CAAC;IAEvB,oCAAoC;IACpC,gBAAgB,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAExD,iCAAiC;IACjC,UAAU,EAAE,OAAO,CAAC;IAEpB,6CAA6C;IAC7C,WAAW,EAAE;QACX,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,OAAO,CAAC;QACrB,cAAc,EAAE,MAAM,CAAC;KACxB,CAAC;IAEF,+DAA+D;IAC/D,WAAW,EAAE,MAAM,IAAI,CAAC;IAExB,6CAA6C;IAC7C,aAAa,EAAE,OAAO,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,eAAe,CAAC,EAC9B,QAAQ,EACR,UAAiB,EACjB,kBAAyB,EACzB,cAAc,EACd,QAAgB,EAChB,SAAS,EACT,OAAO,EACP,oBAAoB,EACpB,QAAQ,EACR,UAAkB,GACnB,GAAE,sBAA2B,GAAG,qBAAqB,CAmWrD"}
@@ -1 +1 @@
1
- "use client";import{useState as L,useEffect as k,useRef as _,useCallback as B,startTransition as y,useMemo as K}from"react";import{handleError as p,getOAuthClientId as te,getEnabledAuthPartners as re,isClient as ne,useTranslation as ie,useScriptLoader as ae}from"@donotdev/core";import{useIsDark as se}from"@donotdev/components";import{useAuth as Q}from"../useAuth";import{useFedCM as ce}from"./useFedCM";function le({clientId:U,autoSelect:x=!0,cancelOnTapOutside:C=!0,promptParentId:S,disabled:d=!1,onSuccess:R,onError:s,allowedParentOrigins:A,cspNonce:I,clientOnly:F=!1}={}){const{t:r}=ie("dndev"),T=Q("user"),P=Q("signInWithGoogleCredential"),b=se(),c=U||te("google"),D=re().includes("google"),{isSupported:t,isReady:g,error:q,browserInfo:V}=ce({checkGoogleServices:!0,onError:e=>{const a=p(e,{userMessage:r("auth.fedcmNotSupported","Your browser does not support Google One Tap"),context:{operation:"fedcm_detection"},severity:"warning"});s?.(a)}}),{isLoading:X,isLoaded:M,error:z,isReady:N,load:Z,loadTriggered:$}=ae("https://accounts.google.com/gsi/client",{enabled:D&&!!c&&!d&&g&&t,nonce:I,checkExisting:!0,isLoaded:()=>!!window.google?.accounts?.id,onError:e=>{const a=p(e,{userMessage:r("auth.googleScriptLoadError","Failed to load Google Identity Services"),context:{operation:"google_script_load"},severity:"error"});s?.(a)}}),[O,J]=L(!1),[Y,H]=L(null),ee=_(null),i=_(!1),l=_(null),E=_(0),[W,m]=L(!1),w="gsi_hide_until",de=600*1e3,v=K(()=>D&&!!c&&!d&&!T&&t&&(F?O:!0)&&!W,[D,c,d,T,t,F,O,W]),oe=K(()=>!t&&g?new Error(r("auth.fedcmRequired","Google One Tap requires a modern browser (Chrome 116+ or Edge 116+)")):z||q||Y,[z,q,Y,t,g,r]),f=B(async e=>{try{if(!e||typeof e!="string")throw new Error("Invalid credential format");await P(e),y(()=>{R?.(e)})}catch(a){const n=p(a,{userMessage:r("auth.googleOneTapError","Google One Tap authentication failed"),context:{operation:"google_one_tap_signin",credentialLength:e?.length||0},severity:"error"});throw y(()=>{H(n)}),s?.(n),n}},[P,R,s,r]),G=B(()=>{if(!ne()||!N||!c||!window.google?.accounts?.id||!t||i.current)return;const e=Date.now(),a=e-E.current,n=600*1e3;if(!(a<n&&E.current>0))try{i.current=!0,E.current=e;const h={client_id:c,callback:async o=>{try{await f(o.credential)}catch(j){p(j,{userMessage:"Google One Tap credential handling failed",context:{operation:"google_one_tap_callback"},severity:"error"})}},auto_select:x,cancel_on_tap_outside:C,context:"signin",ux_mode:"popup",itp_support:!0,state:b?"dark":"light",use_fedcm_for_prompt:!0,allowed_parent_origins:A,csp_nonce:I,moment_callback:o=>{const j=o.getMomentType();if(o.isDisplayMoment?.()){if(!o.isDisplayed?.()&&o.getNotDisplayedReason){i.current=!1;try{const u=Date.now()+n;localStorage.setItem(w,String(u)),m(!0)}catch{}}}else if(o.isSkippedMoment?.()){i.current=!1;try{const u=Date.now()+n;localStorage.setItem(w,String(u)),m(!0)}catch{}}else if(o.isDismissedMoment?.()){i.current=!1;try{const u=Date.now()+n;localStorage.setItem(w,String(u)),m(!0)}catch{}}}};S&&(h.prompt_parent_id=S),window.google.accounts.id.initialize(h),l.current&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>{window.google?.accounts?.id?.prompt(o=>{o?.credential&&f(o.credential)}),l.current=null},100)}catch(h){const o=p(h,{userMessage:r("auth.googleOneTapInitError","Failed to initialize Google One Tap"),context:{operation:"google_one_tap_initialize",fedcmSupported:t},severity:"error"});y(()=>{H(o)}),s?.(o),i.current=!1}},[N,c,t,x,C,S,b,f,s,A,I,r]);return k(()=>{if(typeof window<"u"){y(()=>{J(!0)});try{const e=Number(localStorage.getItem(w)||0);m(e>Date.now())}catch{}}},[]),k(()=>{M&&!d&&v&&g&&G()},[M,d,v,g,G]),k(()=>()=>{l.current&&window.clearTimeout(l.current),i.current=!1},[]),{isLoaded:M,isLoading:X,error:oe,user:T,isDark:b,fedcmSupported:t,isHydrated:O,containerRef:ee,initialize:G,handleCredential:f,shouldShow:v,browserInfo:V,triggerLoad:Z,loadTriggered:$}}export{le as useGoogleOneTap};
1
+ "use client";import{useState as R,useEffect as b,useRef as _,useCallback as K,startTransition as y,useMemo as j}from"react";import{handleError as p,getOAuthClientId as re,getEnabledAuthPartners as oe,isClient as ne,useTranslation as ie,useScriptLoader as se}from"@donotdev/core";import{useIsDark as ae}from"@donotdev/components";import{useAuth as B}from"../useAuth";import{useFedCM as ce}from"./useFedCM";function he({clientId:J,autoSelect:k=!0,cancelOnTapOutside:x=!0,promptParentId:T,disabled:u=!1,onSuccess:O,onError:a,allowedParentOrigins:N,cspNonce:E,clientOnly:z=!1}={}){const{t:o}=ie("dndev"),S=B("user"),A=B("signInWithGoogleCredential"),I=ae(),c=J||re("google"),L=oe().includes("google"),{isSupported:r,isReady:d,error:U,browserInfo:Q}=ce({checkGoogleServices:!0,onError:e=>{const s=p(e,{userMessage:o("auth.fedcmNotSupported","Your browser does not support Google One Tap"),context:{operation:"fedcm_detection"},severity:"warning"});a?.(s)}}),{isLoading:V,isLoaded:M,error:F,isReady:W,load:X,loadTriggered:Z}=se("https://accounts.google.com/gsi/client",{enabled:L&&!!c&&!u&&d&&r,nonce:E,checkExisting:!0,isLoaded:()=>!!window.google?.accounts?.id,onError:e=>{const s=p(e,{userMessage:o("auth.googleScriptLoadError","Failed to load Google Identity Services"),context:{operation:"google_script_load"},severity:"error"});a?.(s)}}),[D,$]=R(!1),[q,H]=R(null),ee=_(null),i=_(!1),l=_(null),v=_(0),[P,f]=R(!1),m="gsi_hide_until",ue=600*1e3,C=j(()=>L&&!!c&&!u&&!S&&r&&(z?D:!0)&&!P,[L,c,u,S,r,z,D,P]),te=j(()=>!r&&d?new Error(o("auth.fedcmRequired","Google One Tap requires a modern browser (Chrome 116+ or Edge 116+)")):F||U||q,[F,U,q,r,d,o]),h=K(async e=>{try{if(!e||typeof e!="string")throw new Error("Invalid credential format");await A(e),y(()=>{O?.(e)})}catch(s){const n=p(s,{userMessage:o("auth.googleOneTapError","Google One Tap authentication failed"),context:{operation:"google_one_tap_signin",credentialLength:e?.length||0},severity:"error"});throw y(()=>{H(n)}),a?.(n),n}},[A,O,a,o]),G=K(()=>{if(!ne()||!W||!c||!window.google?.accounts?.id||!r||i.current)return;const e=Date.now(),s=e-v.current,n=600*1e3;if(!(s<n&&v.current>0))try{i.current=!0,v.current=e;const w={client_id:c,callback:async t=>{try{await h(t.credential)}catch(Y){p(Y,{userMessage:"Google One Tap credential handling failed",context:{operation:"google_one_tap_callback"},severity:"error"})}},auto_select:k,cancel_on_tap_outside:x,context:"signin",ux_mode:"popup",itp_support:!0,state:I?"dark":"light",use_fedcm_for_prompt:!0,allowed_parent_origins:N,csp_nonce:E,moment_callback:t=>{const Y=t.getMomentType();if(t.isDisplayMoment?.()){if(!t.isDisplayed?.()){if(t.getNotDisplayedReason){i.current=!1;try{const g=Date.now()+n;localStorage.setItem(m,String(g)),f(!0)}catch{}}}}else if(t.isSkippedMoment?.()){i.current=!1;try{const g=Date.now()+n;localStorage.setItem(m,String(g)),f(!0)}catch{}}else if(t.isDismissedMoment?.()){i.current=!1;try{const g=Date.now()+n;localStorage.setItem(m,String(g)),f(!0)}catch{}}}};T&&(w.prompt_parent_id=T),window.google.accounts.id.initialize(w),l.current&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>{window.google?.accounts?.id?.prompt(t=>{t?.credential&&h(t.credential)}),l.current=null},100)}catch(w){const t=p(w,{userMessage:o("auth.googleOneTapInitError","Failed to initialize Google One Tap"),context:{operation:"google_one_tap_initialize",fedcmSupported:r},severity:"error"});y(()=>{H(t)}),a?.(t),i.current=!1}},[W,c,r,k,x,T,I,h,a,N,E,o]);return b(()=>{if(typeof window<"u"){y(()=>{$(!0)});try{const e=Number(localStorage.getItem(m)||0);f(e>Date.now())}catch{}}},[]),b(()=>{M&&!u&&C&&d&&G()},[M,u,C,d,G]),b(()=>()=>{l.current&&window.clearTimeout(l.current),i.current=!1},[]),{isLoaded:M,isLoading:V,error:te,user:S,isDark:I,fedcmSupported:r,isHydrated:D,containerRef:ee,initialize:G,handleCredential:h,shouldShow:C,browserInfo:Q,triggerLoad:X,loadTriggered:Z}}export{he as useGoogleOneTap};