@donotdev/firebase 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.
@@ -1 +1 @@
1
- import{getFirestore as n,connectFirestoreEmulator as p}from"firebase/firestore";import{getPlatformEnvVar as r}from"@donotdev/core";import{getFirebaseSDK as c}from"./sdk";let a=null,s=!1;async function f(){if(a)return a;const e=await c().getApp();a=n(e);const t=r("NODE_ENV")==="development",o=r("USE_FIREBASE_EMULATOR")==="true";if(t&&o&&!s){const i=r("FIREBASE_EMULATOR_HOST")||"localhost",m=parseInt(r("FIREBASE_FIRESTORE_EMULATOR_PORT")||"8080");p(a,i,m),s=!0}return a}import{getFirestore as l}from"firebase/firestore";import{doc as F,getDoc as S,getDocs as d,setDoc as T,updateDoc as D,deleteDoc as E,addDoc as g}from"firebase/firestore";import{collection as u,collectionGroup as A}from"firebase/firestore";import{query as y,where as I,orderBy as O,limit as R,limitToLast as h,startAt as v,startAfter as B,endAt as U,endBefore as _}from"firebase/firestore";import{onSnapshot as P,onSnapshotsInSync as w}from"firebase/firestore";import{writeBatch as L,runTransaction as V}from"firebase/firestore";import{serverTimestamp as G,increment as M,arrayUnion as b,arrayRemove as q}from"firebase/firestore";import{FieldValue as N,GeoPoint as C}from"firebase/firestore";import{Timestamp as K}from"firebase/firestore";import{transformFirestoreData as j}from"../shared/transform";import{convertISOStringsToDates as k}from"../shared/transform";import{prepareForFirestore as x}from"../shared/transform";import{toTimestamp as H}from"../shared/transform";import{firestoreToISOString as J}from"../shared/transform";import{createFirestorePartialUpdate as Q}from"../shared/transform";export{N as FieldValue,K as FirestoreTimestampClass,C as GeoPoint,g as addDoc,q as arrayRemove,b as arrayUnion,u as collection,A as collectionGroup,k as convertISOStringsToDates,Q as createFirestorePartialUpdate,E as deleteDoc,F as doc,U as endAt,_ as endBefore,J as firestoreToISOString,S as getDoc,d as getDocs,f as getFirebaseFirestore,l as getFirestore,M as increment,R as limit,h as limitToLast,P as onSnapshot,w as onSnapshotsInSync,O as orderBy,x as prepareForFirestore,y as query,V as runTransaction,G as serverTimestamp,T as setDoc,B as startAfter,v as startAt,H as toTimestamp,j as transformFirestoreData,D as updateDoc,I as where,L as writeBatch};
1
+ import{getFirestore as m,connectFirestoreEmulator as p}from"firebase/firestore";import{getPlatformEnvVar as r}from"@donotdev/core";import{getFirebaseSDK as c}from"./sdk";let e=null,t=!1;async function F(){if(e)return e;const o=await c().getApp();e=m(o);const s=r("NODE_ENV")==="development",a=r("USE_FIREBASE_EMULATOR")==="true";if(s&&a&&!t){const n=r("FIREBASE_EMULATOR_HOST")||"localhost",i=parseInt(r("FIREBASE_FIRESTORE_EMULATOR_PORT")||"8080");p(e,n,i),t=!0}return e}import{getFirestore as S}from"firebase/firestore";import{doc as D,getDoc as g,getDocs as A,setDoc as R,updateDoc as I,deleteDoc as O,addDoc as _}from"firebase/firestore";import{collection as v,collectionGroup as y}from"firebase/firestore";import{query as U,where as L,orderBy as P,limit as w,limitToLast as M,startAt as V,startAfter as b,endAt as k,endBefore as C}from"firebase/firestore";import{onSnapshot as N,onSnapshotsInSync as q}from"firebase/firestore";import{writeBatch as K,runTransaction as j}from"firebase/firestore";import{serverTimestamp as J,increment as Q,arrayUnion as W,arrayRemove as X}from"firebase/firestore";import{FieldValue as Z,GeoPoint as $}from"firebase/firestore";import{Timestamp as re}from"firebase/firestore";import{transformFirestoreData as oe}from"../shared/transform";import{convertISOStringsToDates as ae}from"../shared/transform";import{prepareForFirestore as ie}from"../shared/transform";import{toTimestamp as pe}from"../shared/transform";import{firestoreToISOString as fe}from"../shared/transform";import{createFirestorePartialUpdate as Ee}from"../shared/transform";export{Z as FieldValue,re as FirestoreTimestampClass,$ as GeoPoint,_ as addDoc,X as arrayRemove,W as arrayUnion,v as collection,y as collectionGroup,ae as convertISOStringsToDates,Ee as createFirestorePartialUpdate,O as deleteDoc,D as doc,k as endAt,C as endBefore,fe as firestoreToISOString,g as getDoc,A as getDocs,F as getFirebaseFirestore,S as getFirestore,Q as increment,w as limit,M as limitToLast,N as onSnapshot,q as onSnapshotsInSync,P as orderBy,ie as prepareForFirestore,U as query,j as runTransaction,J as serverTimestamp,R as setDoc,b as startAfter,V as startAt,pe as toTimestamp,oe as transformFirestoreData,I as updateDoc,L as where,K as writeBatch};
@@ -1 +1 @@
1
- import{getFunctions as m,connectFunctionsEmulator as u}from"firebase/functions";import{getPlatformEnvVar as t}from"@donotdev/core";import{getFirebaseSDK as f}from"./sdk";const a=new Set;async function F(i){const n=await f().getApp(),s=i||t("FIREBASE_FUNCTIONS_REGION")||"europe-west1",r=m(n,s),E=t("NODE_ENV")==="development",c=t("USE_FIREBASE_EMULATOR")==="true";if(E&&c){const e=`${n.name}_${s}`;if(!a.has(e)){const p=t("FIREBASE_EMULATOR_HOST")||"localhost",l=t("FIREBASE_FUNCTIONS_EMULATOR_PORT")||"5001";try{u(r,p,parseInt(l)),a.add(e),typeof window<"u"}catch(o){(o instanceof Error?o.message:String(o)).includes("already")&&typeof window<"u",a.add(e)}}}return r}import{httpsCallable as S}from"firebase/functions";export{F as getFirebaseFunctions,S as httpsCallable};
1
+ import{getFunctions as d,connectFunctionsEmulator as m}from"firebase/functions";import{getPlatformEnvVar as e}from"@donotdev/core";import{getFirebaseSDK as p}from"./sdk";const n=new Set;async function O(a){const r=await p().getApp(),s=a||e("FIREBASE_FUNCTIONS_REGION")||"europe-west1",c=d(r,s),i=e("NODE_ENV")==="development",l=e("USE_FIREBASE_EMULATOR")==="true";if(i&&l){const o=`${r.name}_${s}`;if(!n.has(o)){const u=e("FIREBASE_EMULATOR_HOST")||"localhost",E=e("FIREBASE_FUNCTIONS_EMULATOR_PORT")||"5001";try{m(c,u,parseInt(E)),n.add(o),typeof window<"u"}catch(t){(t instanceof Error?t.message:String(t)).includes("already")&&typeof window<"u",n.add(o)}}}return c}import{httpsCallable as A}from"firebase/functions";export{O as getFirebaseFunctions,A as httpsCallable};
@@ -18,4 +18,4 @@
18
18
  * @license Commercial
19
19
  *
20
20
  * @module @donotdev/firebase/sdk
21
- */import{initializeApp as E,getApps as l}from"firebase/app";import{initializeAppCheck as w,ReCaptchaEnterpriseProvider as y}from"firebase/app-check";import*as i from"firebase/auth";import{GoogleAuthProvider as m}from"firebase/auth";import{createSingleton as W,getPlatformEnvVar as r,getAuthDomain as k,handleError as d}from"@donotdev/core";import{GoogleAuthProvider as v,GithubAuthProvider as C,FacebookAuthProvider as R,TwitterAuthProvider as f,OAuthProvider as z,EmailAuthProvider as b}from"firebase/auth";let a=null,h,p=!1,I=0;class S{initialized=!1;app=null;auth=null;appCheck=null;authEmulatorConnected=!1;async initialize(){if(!this.initialized)try{const t=r("FIREBASE_API_KEY"),e=r("FIREBASE_PROJECT_ID");if(!t||!e){this.initialized=!0;return}const n=k(),s={apiKey:t,authDomain:n,projectId:e,storageBucket:r("FIREBASE_STORAGE_BUCKET"),messagingSenderId:r("FIREBASE_MESSAGING_SENDER_ID"),appId:r("FIREBASE_APP_ID"),measurementId:r("FIREBASE_MEASUREMENT_ID")};if(l().length===0?this.app=E(s):this.app=l()[0]||null,this.auth=this.app?i.getAuth(this.app):null,this.auth)try{await i.setPersistence(this.auth,i.browserLocalPersistence)}catch{}const P=r("NODE_ENV")==="development",g=r("USE_FIREBASE_EMULATOR")==="true";if(P&&g&&this.auth&&!this.authEmulatorConnected){const c=r("FIREBASE_EMULATOR_HOST"),A=r("FIREBASE_EMULATOR_PORT")||"9099";if(c)try{await i.connectAuthEmulator(this.auth,`http://${c}:${A}`,{disableWarnings:!0}),this.authEmulatorConnected=!0}catch(o){const u=o instanceof Error?o.message:String(o);(u.includes("already")||u.includes("emulator-config-failed"))&&(this.authEmulatorConnected=!0)}}this.initialized=!0}catch(t){throw d(t,{showNotification:!1,severity:"warning",context:{operation:"FirebaseSDK.initialize"}}),t}}ensureInitialized(){if(!this.auth)throw new Error("Firebase Auth not initialized. Call initialize() first.");return this.auth}async initializeAppCheck(t){if(!this.app||this.appCheck)return;const e=r("RECAPTCHA_SITE_KEY");if(e)try{if(t&&typeof window<"u"){const n=r("APPCHECK_DEBUG_TOKEN");window.FIREBASE_APPCHECK_DEBUG_TOKEN=n||!0}this.appCheck=w(this.app,{provider:new y(e),isTokenAutoRefreshEnabled:!0})}catch{}}appCheckInitPromise=null;async ensureAppCheckInitialized(){if(this.appCheck||!this.initialized)return;if(this.appCheckInitPromise)return this.appCheckInitPromise;const t=r("NODE_ENV")==="development";return this.appCheckInitPromise=this.initializeAppCheck(t).then(()=>{this.appCheckInitPromise=null}).catch(e=>{throw this.appCheckInitPromise=null,e}),this.appCheckInitPromise}isAppCheckEnabled(){return this.appCheck!==null}async getApp(){if(await this.initialize(),!this.app)throw new Error("Firebase app not initialized. This should never happen after initialize().");return this.app}onAuthStateChanged(t){const e=this.ensureInitialized();return i.onAuthStateChanged(e,t)}beforeAuthStateChanged(t){const e=this.ensureInitialized();return i.beforeAuthStateChanged(e,t)}getCurrentUser(){return this.ensureInitialized().currentUser}async getRedirectResult(){const t=this.ensureInitialized(),e=Date.now(),n=e-I;return h!==void 0?h:a||(p=!0,I=e,a=i.getRedirectResult(t).then(s=>(h=s,a=null,s)).catch(s=>{throw d(s,{showNotification:!1,severity:"warning",context:{operation:"getRedirectResult"}}),a=null,p=!1,s}),a)}async signInWithRedirect(t){const e=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithRedirect(e,t)}async signInWithPopup(t){const e=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithPopup(e,t)}async signInWithEmailAndPassword(t,e){const n=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithEmailAndPassword(n,t,e)}async createUserWithEmailAndPassword(t,e){const n=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.createUserWithEmailAndPassword(n,t,e)}async sendPasswordResetEmail(t,e){const n=this.ensureInitialized();return i.sendPasswordResetEmail(n,t,e)}async confirmPasswordReset(t,e){const n=this.ensureInitialized();return i.confirmPasswordReset(n,t,e)}async verifyPasswordResetCode(t){const e=this.ensureInitialized();return i.verifyPasswordResetCode(e,t)}async signInWithEmailLink(t,e){const n=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithEmailLink(n,t,e)}async sendSignInLinkToEmail(t,e){const n=this.ensureInitialized();return i.sendSignInLinkToEmail(n,t,e)}isSignInWithEmailLink(t){const e=this.ensureInitialized();return i.isSignInWithEmailLink(e,t)}async signInWithCustomToken(t){const e=this.ensureInitialized();return i.signInWithCustomToken(e,t)}async signInAnonymously(){const t=this.ensureInitialized();return i.signInAnonymously(t)}async signInWithCredential(t){const e=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithCredential(e,t)}async signInWithPhoneNumber(t,e){const n=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithPhoneNumber(n,t,e)}async signOut(){const t=this.ensureInitialized();return i.signOut(t)}async sendEmailVerification(t,e){return i.sendEmailVerification(t,e)}async updatePassword(t,e){return i.updatePassword(t,e)}async updateEmail(t,e){return i.updateEmail(t,e)}async updateProfile(t,e){return i.updateProfile(t,e)}async reload(t){return i.reload(t)}async deleteUser(t){return i.deleteUser(t)}async getIdToken(t,e){return i.getIdToken(t,e)}async getIdTokenResult(t,e){return i.getIdTokenResult(t,e)}async linkWithCredential(t,e){return i.linkWithCredential(t,e)}async linkWithPopup(t,e){return i.linkWithPopup(t,e)}async linkWithRedirect(t,e){return i.linkWithRedirect(t,e)}async linkWithPhoneNumber(t,e,n){return i.linkWithPhoneNumber(t,e,n)}async unlink(t,e){return i.unlink(t,e)}async fetchSignInMethodsForEmail(t){const e=this.ensureInitialized();return i.fetchSignInMethodsForEmail(e,t)}async reauthenticateWithCredential(t,e){return i.reauthenticateWithCredential(t,e)}async reauthenticateWithPopup(t,e){return i.reauthenticateWithPopup(t,e)}async reauthenticateWithRedirect(t,e){return i.reauthenticateWithRedirect(t,e)}createGoogleProvider(){return new i.GoogleAuthProvider}createGithubProvider(){return new i.GithubAuthProvider}createFacebookProvider(){return new i.FacebookAuthProvider}createTwitterProvider(){return new i.TwitterAuthProvider}createMicrosoftProvider(){return new i.OAuthProvider("microsoft.com")}createAppleProvider(){return new i.OAuthProvider("apple.com")}createOAuthProvider(t){return new i.OAuthProvider(t)}createPhoneAuthProvider(){const t=this.ensureInitialized();return new i.PhoneAuthProvider(t)}createEmailAuthProvider(){return i.EmailAuthProvider}createRecaptchaVerifier(t,e){const n=this.ensureInitialized();return new i.RecaptchaVerifier(n,t,e)}multiFactor(t){return i.multiFactor(t)}getMultiFactorResolver(t){const e=this.ensureInitialized();return i.getMultiFactorResolver(e,t)}getAdditionalUserInfo(t){return i.getAdditionalUserInfo(t)}async setPersistence(t){const e=this.ensureInitialized();return i.setPersistence(e,t)}useDeviceLanguage(){const t=this.ensureInitialized();return i.useDeviceLanguage(t)}async checkActionCode(t){const e=this.ensureInitialized();return i.checkActionCode(e,t)}async applyActionCode(t){const e=this.ensureInitialized();return i.applyActionCode(e,t)}async signInWithGoogle(){const t=this.createGoogleProvider();return await this.signInWithPopup(t)}async signInWithGoogleRedirect(){const t=this.createGoogleProvider();return await this.signInWithRedirect(t)}async signInWithGitHub(){const t=this.createGithubProvider();return await this.signInWithPopup(t)}async signInWithGitHubRedirect(){const t=this.createGithubProvider();return await this.signInWithRedirect(t)}async signInWithFacebook(){const t=this.createFacebookProvider();return await this.signInWithPopup(t)}async signInWithFacebookRedirect(){const t=this.createFacebookProvider();return await this.signInWithRedirect(t)}async signInWithTwitter(){const t=this.createTwitterProvider();return await this.signInWithPopup(t)}async signInWithTwitterRedirect(){const t=this.createTwitterProvider();return await this.signInWithRedirect(t)}async signInWithMicrosoft(){const t=this.createMicrosoftProvider();return await this.signInWithPopup(t)}async signInWithMicrosoftRedirect(){const t=this.createMicrosoftProvider();return await this.signInWithRedirect(t)}async signInWithApple(){const t=this.createAppleProvider();return await this.signInWithPopup(t)}async signInWithAppleRedirect(){const t=this.createAppleProvider();return await this.signInWithRedirect(t)}async signInWithGoogleCredential(t){const e=this.createGoogleProvider(),n=m.credential(t);return await this.signInWithCredential(n)}async signInWithEmail(t,e){return await this.signInWithEmailAndPassword(t,e)}async createUserWithEmail(t,e){return await this.createUserWithEmailAndPassword(t,e)}async linkWithGoogle(t){const e=this.createGoogleProvider();return await this.linkWithPopup(t,e)}async linkWithGitHub(t){const e=this.createGithubProvider();return await this.linkWithPopup(t,e)}async linkWithFacebook(t){const e=this.createFacebookProvider();return await this.linkWithPopup(t,e)}async linkWithTwitter(t){const e=this.createTwitterProvider();return await this.linkWithPopup(t,e)}async linkWithMicrosoft(t){const e=this.createMicrosoftProvider();return await this.linkWithPopup(t,e)}async linkWithApple(t){const e=this.createAppleProvider();return await this.linkWithPopup(t,e)}reset(){this.initialized=!1,this.auth=null,this.app=null,this.appCheck=null}}const T=W(()=>new S);export{b as EmailAuthProvider,R as FacebookAuthProvider,C as GithubAuthProvider,v as GoogleAuthProvider,z as OAuthProvider,f as TwitterAuthProvider,T as getFirebaseSDK};
21
+ */import{initializeApp as A,getApps as d}from"firebase/app";import{initializeAppCheck as w,ReCaptchaEnterpriseProvider as m}from"firebase/app-check";import*as i from"firebase/auth";import{GoogleAuthProvider as v}from"firebase/auth";import{createSingleton as y,getPlatformEnvVar as n,getAuthDomain as k,handleError as l}from"@donotdev/core";import{GoogleAuthProvider as O,GithubAuthProvider as K,FacebookAuthProvider as M,TwitterAuthProvider as N,OAuthProvider as L,EmailAuthProvider as H}from"firebase/auth";let a=null,u,p=!1,I=0;class f{initialized=!1;app=null;auth=null;appCheck=null;authEmulatorConnected=!1;async initialize(){if(!this.initialized)try{const e=n("FIREBASE_API_KEY"),t=n("FIREBASE_PROJECT_ID");if(!e||!t){this.initialized=!0;return}const r=k(),s={apiKey:e,authDomain:r,projectId:t,storageBucket:n("FIREBASE_STORAGE_BUCKET"),messagingSenderId:n("FIREBASE_MESSAGING_SENDER_ID"),appId:n("FIREBASE_APP_ID"),measurementId:n("FIREBASE_MEASUREMENT_ID")};if(d().length===0?this.app=A(s):this.app=d()[0]||null,this.auth=this.app?i.getAuth(this.app):null,this.auth)try{await i.setPersistence(this.auth,i.browserLocalPersistence)}catch{}const P=n("NODE_ENV")==="development",E=n("USE_FIREBASE_EMULATOR")==="true";if(P&&E&&this.auth&&!this.authEmulatorConnected){const o=n("FIREBASE_EMULATOR_HOST"),g=n("FIREBASE_EMULATOR_PORT")||"9099";if(o)try{await i.connectAuthEmulator(this.auth,`http://${o}:${g}`,{disableWarnings:!0}),this.authEmulatorConnected=!0}catch(h){const c=h instanceof Error?h.message:String(h);(c.includes("already")||c.includes("emulator-config-failed"))&&(this.authEmulatorConnected=!0)}}this.initialized=!0}catch(e){throw l(e,{showNotification:!1,severity:"warning",context:{operation:"FirebaseSDK.initialize"}}),e}}ensureInitialized(){if(!this.auth)throw new Error("Firebase Auth not initialized. Call initialize() first.");return this.auth}async initializeAppCheck(e){if(!this.app||this.appCheck)return;const t=n("RECAPTCHA_SITE_KEY");if(t)try{if(e&&typeof window<"u"){const r=n("APPCHECK_DEBUG_TOKEN");window.FIREBASE_APPCHECK_DEBUG_TOKEN=r||!0}this.appCheck=w(this.app,{provider:new m(t),isTokenAutoRefreshEnabled:!0})}catch{}}appCheckInitPromise=null;async ensureAppCheckInitialized(){if(this.appCheck||!this.initialized)return;if(this.appCheckInitPromise)return this.appCheckInitPromise;const e=n("NODE_ENV")==="development";return this.appCheckInitPromise=this.initializeAppCheck(e).then(()=>{this.appCheckInitPromise=null}).catch(t=>{throw this.appCheckInitPromise=null,t}),this.appCheckInitPromise}isAppCheckEnabled(){return this.appCheck!==null}async getApp(){if(await this.initialize(),!this.app)throw new Error("Firebase app not initialized. This should never happen after initialize().");return this.app}onAuthStateChanged(e){const t=this.ensureInitialized();return i.onAuthStateChanged(t,e)}beforeAuthStateChanged(e){const t=this.ensureInitialized();return i.beforeAuthStateChanged(t,e)}getCurrentUser(){return this.ensureInitialized().currentUser}async getRedirectResult(){const e=this.ensureInitialized(),t=Date.now(),r=t-I;return u!==void 0?u:a||(p=!0,I=t,a=i.getRedirectResult(e).then(s=>(u=s,a=null,s)).catch(s=>{throw l(s,{showNotification:!1,severity:"warning",context:{operation:"getRedirectResult"}}),a=null,p=!1,s}),a)}async signInWithRedirect(e){const t=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithRedirect(t,e)}async signInWithPopup(e){const t=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithPopup(t,e)}async signInWithEmailAndPassword(e,t){const r=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithEmailAndPassword(r,e,t)}async createUserWithEmailAndPassword(e,t){const r=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.createUserWithEmailAndPassword(r,e,t)}async sendPasswordResetEmail(e,t){const r=this.ensureInitialized();return i.sendPasswordResetEmail(r,e,t)}async confirmPasswordReset(e,t){const r=this.ensureInitialized();return i.confirmPasswordReset(r,e,t)}async verifyPasswordResetCode(e){const t=this.ensureInitialized();return i.verifyPasswordResetCode(t,e)}async signInWithEmailLink(e,t){const r=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithEmailLink(r,e,t)}async sendSignInLinkToEmail(e,t){const r=this.ensureInitialized();return i.sendSignInLinkToEmail(r,e,t)}isSignInWithEmailLink(e){const t=this.ensureInitialized();return i.isSignInWithEmailLink(t,e)}async signInWithCustomToken(e){const t=this.ensureInitialized();return i.signInWithCustomToken(t,e)}async signInAnonymously(){const e=this.ensureInitialized();return i.signInAnonymously(e)}async signInWithCredential(e){const t=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithCredential(t,e)}async signInWithPhoneNumber(e,t){const r=this.ensureInitialized();return await this.ensureAppCheckInitialized(),i.signInWithPhoneNumber(r,e,t)}async signOut(){const e=this.ensureInitialized();return i.signOut(e)}async sendEmailVerification(e,t){return i.sendEmailVerification(e,t)}async updatePassword(e,t){return i.updatePassword(e,t)}async updateEmail(e,t){return i.updateEmail(e,t)}async updateProfile(e,t){return i.updateProfile(e,t)}async reload(e){return i.reload(e)}async deleteUser(e){return i.deleteUser(e)}async getIdToken(e,t){return i.getIdToken(e,t)}async getIdTokenResult(e,t){return i.getIdTokenResult(e,t)}async linkWithCredential(e,t){return i.linkWithCredential(e,t)}async linkWithPopup(e,t){return i.linkWithPopup(e,t)}async linkWithRedirect(e,t){return i.linkWithRedirect(e,t)}async linkWithPhoneNumber(e,t,r){return i.linkWithPhoneNumber(e,t,r)}async unlink(e,t){return i.unlink(e,t)}async fetchSignInMethodsForEmail(e){const t=this.ensureInitialized();return i.fetchSignInMethodsForEmail(t,e)}async reauthenticateWithCredential(e,t){return i.reauthenticateWithCredential(e,t)}async reauthenticateWithPopup(e,t){return i.reauthenticateWithPopup(e,t)}async reauthenticateWithRedirect(e,t){return i.reauthenticateWithRedirect(e,t)}createGoogleProvider(){return new i.GoogleAuthProvider}createGithubProvider(){return new i.GithubAuthProvider}createFacebookProvider(){return new i.FacebookAuthProvider}createTwitterProvider(){return new i.TwitterAuthProvider}createMicrosoftProvider(){return new i.OAuthProvider("microsoft.com")}createAppleProvider(){return new i.OAuthProvider("apple.com")}createOAuthProvider(e){return new i.OAuthProvider(e)}createPhoneAuthProvider(){const e=this.ensureInitialized();return new i.PhoneAuthProvider(e)}createEmailAuthProvider(){return i.EmailAuthProvider}createRecaptchaVerifier(e,t){const r=this.ensureInitialized();return new i.RecaptchaVerifier(r,e,t)}multiFactor(e){return i.multiFactor(e)}getMultiFactorResolver(e){const t=this.ensureInitialized();return i.getMultiFactorResolver(t,e)}getAdditionalUserInfo(e){return i.getAdditionalUserInfo(e)}async setPersistence(e){const t=this.ensureInitialized();return i.setPersistence(t,e)}useDeviceLanguage(){const e=this.ensureInitialized();return i.useDeviceLanguage(e)}async checkActionCode(e){const t=this.ensureInitialized();return i.checkActionCode(t,e)}async applyActionCode(e){const t=this.ensureInitialized();return i.applyActionCode(t,e)}async signInWithGoogle(){const e=this.createGoogleProvider();return await this.signInWithPopup(e)}async signInWithGoogleRedirect(){const e=this.createGoogleProvider();return await this.signInWithRedirect(e)}async signInWithGitHub(){const e=this.createGithubProvider();return await this.signInWithPopup(e)}async signInWithGitHubRedirect(){const e=this.createGithubProvider();return await this.signInWithRedirect(e)}async signInWithFacebook(){const e=this.createFacebookProvider();return await this.signInWithPopup(e)}async signInWithFacebookRedirect(){const e=this.createFacebookProvider();return await this.signInWithRedirect(e)}async signInWithTwitter(){const e=this.createTwitterProvider();return await this.signInWithPopup(e)}async signInWithTwitterRedirect(){const e=this.createTwitterProvider();return await this.signInWithRedirect(e)}async signInWithMicrosoft(){const e=this.createMicrosoftProvider();return await this.signInWithPopup(e)}async signInWithMicrosoftRedirect(){const e=this.createMicrosoftProvider();return await this.signInWithRedirect(e)}async signInWithApple(){const e=this.createAppleProvider();return await this.signInWithPopup(e)}async signInWithAppleRedirect(){const e=this.createAppleProvider();return await this.signInWithRedirect(e)}async signInWithGoogleCredential(e){const t=this.createGoogleProvider(),r=v.credential(e);return await this.signInWithCredential(r)}async signInWithEmail(e,t){return await this.signInWithEmailAndPassword(e,t)}async createUserWithEmail(e,t){return await this.createUserWithEmailAndPassword(e,t)}async linkWithGoogle(e){const t=this.createGoogleProvider();return await this.linkWithPopup(e,t)}async linkWithGitHub(e){const t=this.createGithubProvider();return await this.linkWithPopup(e,t)}async linkWithFacebook(e){const t=this.createFacebookProvider();return await this.linkWithPopup(e,t)}async linkWithTwitter(e){const t=this.createTwitterProvider();return await this.linkWithPopup(e,t)}async linkWithMicrosoft(e){const t=this.createMicrosoftProvider();return await this.linkWithPopup(e,t)}async linkWithApple(e){const t=this.createAppleProvider();return await this.linkWithPopup(e,t)}reset(){this.initialized=!1,this.auth=null,this.app=null,this.appCheck=null}}const D=y(()=>new f);export{H as EmailAuthProvider,M as FacebookAuthProvider,K as GithubAuthProvider,O as GoogleAuthProvider,L as OAuthProvider,N as TwitterAuthProvider,D as getFirebaseSDK};
@@ -1 +1 @@
1
- import*as E from"valibot";import{handleServerError as f}from"@donotdev/core/server";import{getServerFirestore as x}from"./utils";import{prepareForFirestore as W,transformFirestoreData as $}from"../shared/transform";const p=typeof window<"u",c={async batchWrite(e,t,r,o,b={}){if(!t||!t.length)return{successes:0,failures:0};const{idField:a="id",generateIds:v=!0,maxBatchSize:l=450,removeFields:F=[],validate:w=!!o}=b,i={successes:0,failures:0,failedItems:[]};try{const n=[],g=await x();let h=g.batch(),y=0;for(let d=0;d<t.length;d++){let u=t[d];if(!u){i.failures++,i.failedItems?.push({index:d,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!u[a])throw f(new Error(`Missing ID for delete operation (${a})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:a,operation:r}});const s=g.collection(e).doc(u[a]);h.delete(s)}else{if(w&&o)try{E.parse(o,u)}catch(M){throw f(M,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:a,itemId:u[a]}})}let s=u[a];if(!s&&r==="create"&&v)s=g.collection(e).doc().id,u={...u,[a]:s};else if(!s)throw f(new Error(`Missing ID for ${r} operation (${a})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:a,operation:r}});const D=[a,...F],I=W(u,D),C=g.collection(e).doc(s);r==="create"?h.create(C,I):r==="update"&&h.update(C,I)}i.successes++,y++,y>=l&&(n.push(h),h=g.batch(),y=0)}catch(s){i.failures++,i.failedItems?.push({index:d,error:s instanceof Error?s:new Error(String(s))})}}return y>0&&n.push(h),n.length>0&&await Promise.all(n.map(d=>d.commit())),i}catch(n){throw f(n,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:i.successes+i.failures,successCount:i.successes,failureCount:i.failures}})}},async batchCreate(e,t,r,o={}){return c.batchWrite(e,t,"create",r,o)},async batchUpdate(e,t,r,o={}){return c.batchWrite(e,t,"update",r,o)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){const o=r.idField||"id",b=t.map(a=>({[o]:a}));return c.batchWrite(e,b,"delete",void 0,r)}return c.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await x()).runTransaction(e)}catch(t){throw f(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];const{maxBatchSize:o=450,transform:b=!0}=r;try{const a=[];for(let l=0;l<t.length;l+=o)a.push(t.slice(l,l+o));const v=a.map(async l=>{const F=await(await x()).collection(e).where("__name__","in",l).get(),w=new Map;return F.forEach(i=>{w.set(i.id,i.data())}),l.map(i=>{const n=w.get(i);return n?b?$({id:i,...n}):{id:i,...n}:null})});return(await Promise.all(v)).flat()}catch(a){throw f(a,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},m=e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},U=p?m("batchWrite"):c.batchWrite,k=p?m("batchCreate"):c.batchCreate,T=p?m("batchUpdate"):c.batchUpdate,G=p?m("batchDelete"):c.batchDelete,S=p?m("runTransaction"):c.runTransaction,_=p?m("bulkGet"):c.bulkGet;export{k as batchCreate,G as batchDelete,T as batchUpdate,U as batchWrite,_ as bulkGet,S as runTransaction};
1
+ import*as E from"valibot";import{handleServerError as m}from"@donotdev/core/server";import{getServerFirestore as x}from"./utils";import{prepareForFirestore as W,transformFirestoreData as $}from"../shared/transform";const p=typeof window<"u",i={async batchWrite(e,t,r,n,w={}){if(!t||!t.length)return{successes:0,failures:0};const{idField:s="id",generateIds:y=!0,maxBatchSize:v=450,removeFields:l=[],validate:I=!!n}=w,c={successes:0,failures:0,failedItems:[]};try{const f=[],d=await x();let a=d.batch(),h=0;for(let b=0;b<t.length;b++){let u=t[b];if(!u){c.failures++,c.failedItems?.push({index:b,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!u[s])throw m(new Error(`Missing ID for delete operation (${s})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:s,operation:r}});const o=d.collection(e).doc(u[s]);a.delete(o)}else{if(I&&n)try{E.parse(n,u)}catch(F){throw m(F,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:s,itemId:u[s]}})}let o=u[s];if(!o&&r==="create"&&y)o=d.collection(e).doc().id,u={...u,[s]:o};else if(!o)throw m(new Error(`Missing ID for ${r} operation (${s})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:s,operation:r}});const M=[s,...l],C=W(u,M),D=d.collection(e).doc(o);r==="create"?a.create(D,C):r==="update"&&a.update(D,C)}c.successes++,h++,h>=v&&(f.push(a),a=d.batch(),h=0)}catch(o){c.failures++,c.failedItems?.push({index:b,error:o instanceof Error?o:new Error(String(o))})}}return h>0&&f.push(a),f.length>0&&await Promise.all(f.map(b=>b.commit())),c}catch(f){throw m(f,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:c.successes+c.failures,successCount:c.successes,failureCount:c.failures}})}},async batchCreate(e,t,r,n={}){return i.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return i.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){const n=r.idField||"id",w=t.map(s=>({[n]:s}));return i.batchWrite(e,w,"delete",void 0,r)}return i.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await x()).runTransaction(e)}catch(t){throw m(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];const{maxBatchSize:n=450,transform:w=!0}=r;try{const s=[];for(let l=0;l<t.length;l+=n)s.push(t.slice(l,l+n));const y=s.map(async l=>{const f=await(await x()).collection(e).where("__name__","in",l).get(),d=new Map;return f.forEach(a=>{d.set(a.id,a.data())}),l.map(a=>{const h=d.get(a);return h?w?$({id:a,...h}):{id:a,...h}:null})});return(await Promise.all(y)).flat()}catch(s){throw m(s,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},g=e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},U=p?g("batchWrite"):i.batchWrite,k=p?g("batchCreate"):i.batchCreate,R=p?g("batchUpdate"):i.batchUpdate,G=p?g("batchDelete"):i.batchDelete,_=p?g("runTransaction"):i.runTransaction,z=p?g("bulkGet"):i.bulkGet;export{k as batchCreate,G as batchDelete,R as batchUpdate,U as batchWrite,z as bulkGet,_ as runTransaction};
@@ -1 +1 @@
1
- export*from"./init";export*from"./utils";export*from"./batch";export*from"./subscription";export*from"./validation";export*from"./uniqueness";import{FieldValue as r,Query as e,Timestamp as o}from"firebase-admin/firestore";export{r as FieldValue,e as Query,o as Timestamp};
1
+ export*from"./init";export*from"./utils";export*from"./batch";export*from"./subscription";export*from"./validation";export*from"./uniqueness";import{FieldValue as a,Query as i,Timestamp as l}from"firebase-admin/firestore";export{a as FieldValue,i as Query,l as Timestamp};
@@ -1,2 +1,2 @@
1
- import{initializeApp as n,getApps as t,cert as o}from"firebase-admin/app";import{getAuth as s}from"firebase-admin/auth";import{getFirestore as a}from"firebase-admin/firestore";import{getFunctions as c}from"firebase-admin/functions";import{handleServerError as p,createSingleton as E}from"@donotdev/core/server";function A(){const e=t();let r=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?r=n({credential:o({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
2
- `)}),projectId:process.env.FIREBASE_PROJECT_ID}):r=n():r=e[0]||null,!r)throw new Error("Failed to initialize Firebase Admin app");return{app:r,auth:s(r),firestore:a(r),functions:c(r)}}const i=E(A);async function u(){try{return i()}catch(e){throw p(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}async function F(){const e=i();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function d(){const e=i();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function f(){const e=i();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}function m(){const e=i();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}export{F as getFirebaseAdminApp,d as getFirebaseAdminAuth,f as getFirebaseAdminFirestore,m as getFirebaseAdminFunctions,u as initFirebaseAdmin};
1
+ import{initializeApp as n,getApps as t,cert as o}from"firebase-admin/app";import{getAuth as s}from"firebase-admin/auth";import{getFirestore as c}from"firebase-admin/firestore";import{getFunctions as a}from"firebase-admin/functions";import{handleServerError as p,createSingleton as A}from"@donotdev/core/server";function E(){const e=t();let i=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?i=n({credential:o({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
2
+ `)}),projectId:process.env.FIREBASE_PROJECT_ID}):i=n():i=e[0]||null,!i)throw new Error("Failed to initialize Firebase Admin app");return{app:i,auth:s(i),firestore:c(i),functions:a(i)}}const r=A(E);async function I(){try{return r()}catch(e){throw p(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}async function v(){const e=r();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function _(){const e=r();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function b(){const e=r();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}function h(){const e=r();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}export{v as getFirebaseAdminApp,_ as getFirebaseAdminAuth,b as getFirebaseAdminFirestore,h as getFirebaseAdminFunctions,I as initFirebaseAdmin};
@@ -1 +1 @@
1
- import{handleServerError as u}from"@donotdev/core/server";import{getServerFirestore as s}from"./utils";import{prepareForFirestore as h,transformFirestoreData as l}from"../shared/transform";import{handleFirebaseError as i}from"../shared/utils";async function p(t,a={}){const{collection:r="subscriptions",userIdField:e="customerId"}=a;try{const c=await(await s()).collection(r).where(e,"==",t).where("status","==","active").limit(1).get();if(c.empty)return null;const o=c.docs[0];if(!o)return null;const n=o.data();return l({id:o.id,...n})}catch(c){throw i(c,"getActiveSubscription")}}async function b(t,a={}){const{collection:r="subscriptions",userIdField:e="customerId"}=a;try{return(await(await s()).collection(r).where(e,"==",t).orderBy("createdAt","desc").get()).docs.map(c=>l({id:c.id,...c.data()}))}catch(c){throw i(c,"getUserSubscriptions")}}async function w(t,a={}){const{collection:r="subscriptions"}=a;try{const e=await s(),c=new Date().toISOString();t.createdAt||(t.createdAt=c),t.updatedAt=c;const o=h(t),{id:n,...m}=o,d=n?e.collection(r).doc(n):e.collection(r).doc();return await d.set(m,{merge:!0}),{...t,id:d.id}}catch(e){throw i(e,"saveSubscription")}}async function S(t,a,r={}){const{collection:e="subscriptions"}=r;try{await(await s()).collection(e).doc(t).update({status:a,updatedAt:new Date().toISOString()})}catch(c){throw i(c,"updateSubscriptionStatus")}}async function y(t,a,r={}){try{const e=await p(t,r);return e?e.features&&Array.isArray(e.features)?e.features.includes(a):e.metadata&&e.metadata[a]?e.metadata[a]==="true":!1:!1}catch(e){return u(e,{context:{function:"hasFeatureAccess"}}),!1}}async function f(t,a={}){const r=t.type,e=t.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await g(e,a);break;case"customer.subscription.deleted":await S(e.id,"canceled",a);break;default:}}catch(c){throw u(c,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:t.id}})}}async function g(t,a={}){const r={id:t.id,customerId:t.customer,status:t.status,planId:t.items.data[0]?.plan.id||"",currentPeriodStart:new Date(t.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(t.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:t.cancel_at_period_end,metadata:t.metadata||{},createdAt:new Date(t.created*1e3).toISOString(),updatedAt:new Date().toISOString()};t.canceled_at&&(r.canceledAt=new Date(t.canceled_at*1e3).toISOString()),await w(r,a)}export{p as getActiveSubscription,b as getUserSubscriptions,f as handleStripeWebhookEvent,y as hasFeatureAccess,w as saveSubscription,S as updateSubscriptionStatus};
1
+ import{handleServerError as l}from"@donotdev/core/server";import{getServerFirestore as i}from"./utils";import{prepareForFirestore as f,transformFirestoreData as w}from"../shared/transform";import{handleFirebaseError as u}from"../shared/utils";async function m(t,a={}){const{collection:r="subscriptions",userIdField:e="customerId"}=a;try{const n=await(await i()).collection(r).where(e,"==",t).where("status","==","active").limit(1).get();if(n.empty)return null;const c=n.docs[0];if(!c)return null;const d=c.data();return w({id:c.id,...d})}catch(o){throw u(o,"getActiveSubscription")}}async function I(t,a={}){const{collection:r="subscriptions",userIdField:e="customerId"}=a;try{return(await(await i()).collection(r).where(e,"==",t).orderBy("createdAt","desc").get()).docs.map(c=>w({id:c.id,...c.data()}))}catch(o){throw u(o,"getUserSubscriptions")}}async function p(t,a={}){const{collection:r="subscriptions"}=a;try{const e=await i(),o=new Date().toISOString();t.createdAt||(t.createdAt=o),t.updatedAt=o;const s=f(t),{id:n,...c}=s,d=n?e.collection(r).doc(n):e.collection(r).doc();return await d.set(c,{merge:!0}),{...t,id:d.id}}catch(e){throw u(e,"saveSubscription")}}async function h(t,a,r={}){const{collection:e="subscriptions"}=r;try{await(await i()).collection(e).doc(t).update({status:a,updatedAt:new Date().toISOString()})}catch(o){throw u(o,"updateSubscriptionStatus")}}async function v(t,a,r={}){try{const e=await m(t,r);return e?e.features&&Array.isArray(e.features)?e.features.includes(a):e.metadata&&e.metadata[a]?e.metadata[a]==="true":!1:!1}catch(e){return l(e,{context:{function:"hasFeatureAccess"}}),!1}}async function F(t,a={}){const r=t.type,e=t.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await y(e,a);break;case"customer.subscription.deleted":await h(e.id,"canceled",a);break;default:}}catch(o){throw l(o,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:t.id}})}}async function y(t,a={}){const r={id:t.id,customerId:t.customer,status:t.status,planId:t.items.data[0]?.plan.id||"",currentPeriodStart:new Date(t.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(t.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:t.cancel_at_period_end,metadata:t.metadata||{},createdAt:new Date(t.created*1e3).toISOString(),updatedAt:new Date().toISOString()};t.canceled_at&&(r.canceledAt=new Date(t.canceled_at*1e3).toISOString()),await p(r,a)}export{m as getActiveSubscription,I as getUserSubscriptions,F as handleStripeWebhookEvent,v as hasFeatureAccess,p as saveSubscription,h as updateSubscriptionStatus};
@@ -1 +1 @@
1
- import{handleServerError as s}from"@donotdev/core/server";import{getServerFirestore as d}from"./utils";const c={};function u(a){c.uniqueConstraintValidator=a}function f(){return c.uniqueConstraintValidator}function g(){return!!c.uniqueConstraintValidator}async function h(){try{const a=await d(),i={checkDuplicate:async(n,r,e,o)=>{if(e==null)return!1;try{return(await a.collection(n).where(r,"==",e).get()).docs.some(t=>t.id!==o&&t.data()[r]===e)}catch(t){throw s(t,{userMessage:`Failed to check uniqueness for field "${r}"`,severity:"error",context:{collection:n,field:r,value:e}})}}};return u(i),i}catch{return{checkDuplicate:async()=>!1}}}async function y(){try{const a=await d(),i={checkDuplicate:async(n,r,e,o)=>{if(e==null)return!1;try{return(await a.collection(n).where(r,"==",e).get()).docs.some(t=>t.id!==o&&t.data()[r]===e)}catch(t){throw s(t,{userMessage:`Failed to check uniqueness for field "${r}"`,severity:"error",context:{collection:n,field:r,value:e}})}}};return u(i),i}catch{return{checkDuplicate:async()=>!1}}}async function p(a,i,n,r){if(!i.length)return;let e=f();if(e||(typeof window<"u"?e=await y():e=await h()),!e)return;const o=[];if(await Promise.all(i.map(async({field:t,errorMessage:w})=>{const l=n[t];l!=null&&await e.checkDuplicate(a,t,l,r)&&o.push({field:t,message:w||`The ${t} must be unique`})})),o.length>0)throw s(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:o,collection:a}})}export{y as createFirestoreClientValidator,h as createFirestoreValidator,f as getUniqueConstraintValidator,g as hasUniqueConstraintValidator,u as registerUniqueConstraintValidator,p as validateUniqueness};
1
+ import{handleServerError as l}from"@donotdev/core/server";import{getServerFirestore as d}from"./utils";const u={};function f(t){u.uniqueConstraintValidator=t}function h(){return u.uniqueConstraintValidator}function k(){return!!u.uniqueConstraintValidator}async function p(){try{const t=await d(),i={checkDuplicate:async(a,r,e,s)=>{if(e==null)return!1;try{return(await t.collection(a).where(r,"==",e).get()).docs.some(o=>o.id!==s&&o.data()[r]===e)}catch(n){throw l(n,{userMessage:`Failed to check uniqueness for field "${r}"`,severity:"error",context:{collection:a,field:r,value:e}})}}};return f(i),i}catch{return{checkDuplicate:async()=>!1}}}async function y(){try{const t=await d(),i={checkDuplicate:async(a,r,e,s)=>{if(e==null)return!1;try{return(await t.collection(a).where(r,"==",e).get()).docs.some(o=>o.id!==s&&o.data()[r]===e)}catch(n){throw l(n,{userMessage:`Failed to check uniqueness for field "${r}"`,severity:"error",context:{collection:a,field:r,value:e}})}}};return f(i),i}catch{return{checkDuplicate:async()=>!1}}}async function m(t,i,a,r){if(!i.length)return;let e=h();if(e||(typeof window<"u"?e=await y():e=await p()),!e)return;const s=[];if(await Promise.all(i.map(async({field:n,errorMessage:c})=>{const o=a[n];if(o==null)return;await e.checkDuplicate(t,n,o,r)&&s.push({field:n,message:c||`The ${n} must be unique`})})),s.length>0)throw l(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:s,collection:t}})}export{y as createFirestoreClientValidator,p as createFirestoreValidator,h as getUniqueConstraintValidator,k as hasUniqueConstraintValidator,f as registerUniqueConstraintValidator,m as validateUniqueness};
@@ -1 +1 @@
1
- import{handleServerError as t}from"@donotdev/core/server";const r={async getServerAdmin(){try{const e=await import("firebase-admin");return e.default||e}catch(e){throw t(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return(await import("firebase-admin/firestore")).getFirestore()}catch(e){throw t(e,"Error getting Admin Firestore")}},async generateServerId(){return(await r.getServerFirestore()).collection("_").doc().id}},i=r.getServerAdmin,a=r.getServerFirestore,n=r.generateServerId;export{n as generateServerId,i as getServerAdmin,a as getServerFirestore};
1
+ import{handleServerError as t}from"@donotdev/core/server";const r={async getServerAdmin(){try{const e=await import("firebase-admin");return e.default||e}catch(e){throw t(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return(await import("firebase-admin/firestore")).getFirestore()}catch(e){throw t(e,"Error getting Admin Firestore")}},async generateServerId(){return(await r.getServerFirestore()).collection("_").doc().id}},i=r.getServerAdmin,n=r.getServerFirestore,s=r.generateServerId;export{s as generateServerId,i as getServerAdmin,n as getServerFirestore};
@@ -1 +1 @@
1
- import*as n from"valibot";import{handleServerError as r}from"@donotdev/core/server";import{validateUniqueness as o}from"./uniqueness";import{validateUniqueness as l,registerUniqueConstraintValidator as d,getUniqueConstraintValidator as u,hasUniqueConstraintValidator as c,createFirestoreValidator as m,createFirestoreClientValidator as V}from"./uniqueness";async function q(a,t,i,s){try{n.parse(a,t),a.metadata?.uniqueFields?.length&&await o(a.metadata.collection,a.metadata.uniqueFields,t,s),a.metadata?.customValidate&&await a.metadata.customValidate(t,i)}catch(e){throw e.name==="ValibotError"||e.issues?r(e,{userMessage:"Document validation failed",context:{validationErrors:e.issues||[],data:t},severity:"warning"}):r(e,{userMessage:"Document validation failed",context:{collection:a.metadata?.collection||"unknown"},severity:"error"})}}function v(a,t){const i=a;return i.metadata=t,i}export{V as createFirestoreClientValidator,m as createFirestoreValidator,v as enhanceSchema,u as getUniqueConstraintValidator,c as hasUniqueConstraintValidator,d as registerUniqueConstraintValidator,q as validateFirestoreDocument,l as validateUniqueness};
1
+ import*as n from"valibot";import{handleServerError as i}from"@donotdev/core/server";import{validateUniqueness as s}from"./uniqueness";import{validateUniqueness as v,registerUniqueConstraintValidator as V,getUniqueConstraintValidator as p,hasUniqueConstraintValidator as q,createFirestoreValidator as g,createFirestoreClientValidator as w}from"./uniqueness";async function u(e,t,r,o){try{n.parse(e,t),e.metadata?.uniqueFields?.length&&await s(e.metadata.collection,e.metadata.uniqueFields,t,o),e.metadata?.customValidate&&await e.metadata.customValidate(t,r)}catch(a){throw a.name==="ValibotError"||a.issues?i(a,{userMessage:"Document validation failed",context:{validationErrors:a.issues||[],data:t},severity:"warning"}):i(a,{userMessage:"Document validation failed",context:{collection:e.metadata?.collection||"unknown"},severity:"error"})}}function c(e,t){const r=e;return r.metadata=t,r}export{w as createFirestoreClientValidator,g as createFirestoreValidator,c as enhanceSchema,p as getUniqueConstraintValidator,q as hasUniqueConstraintValidator,V as registerUniqueConstraintValidator,u as validateFirestoreDocument,v as validateUniqueness};
@@ -1 +1 @@
1
- import{handleError as i}from"@donotdev/core";function s(t){return{seconds:Math.floor(t.getTime()/1e3),nanoseconds:t.getTime()%1e3*1e6,toDate:()=>new Date(t),toMillis:()=>t.getTime(),isEqual:n=>n.seconds===Math.floor(t.getTime()/1e3)&&n.nanoseconds===t.getTime()%1e3*1e6,valueOf:()=>`Timestamp(seconds=${Math.floor(t.getTime()/1e3)}, nanoseconds=${t.getTime()%1e3*1e6})`}}function f(t){try{if(typeof t=="string"){const n=new Date(t);if(isNaN(n.getTime()))throw i("Invalid date string format",{context:{value:t}});return s(n)}if(t instanceof Date){if(isNaN(t.getTime()))throw i("Invalid Date object",{context:{value:t}});return s(t)}throw i("Invalid date value type",{context:{valueType:typeof t}})}catch(n){throw i(n,"Failed to convert to Timestamp")}}function d(t){try{if(t instanceof Date){if(isNaN(t.getTime()))throw i("Invalid Date object",{context:{value:t}});return t.toISOString()}if(typeof t=="object"&&t!==null&&"toDate"in t&&typeof t.toDate=="function")return t.toDate().toISOString();if(typeof t=="string"){const n=new Date(t);if(isNaN(n.getTime()))throw i("Invalid date string format",{context:{value:t}});return n.toISOString()}throw i("Invalid date value type",{context:{valueType:typeof t}})}catch(n){throw i(n,"Failed to convert to ISO string")}}function l(t){return typeof t=="object"&&t!==null&&"toDate"in t&&typeof t.toDate=="function"&&"seconds"in t&&"nanoseconds"in t}function p(t){if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(t))return!1;const n=new Date(t);return!isNaN(n.getTime())}function c(t){if(!t)return t;if(Array.isArray(t))return t.map(n=>c(n));if(typeof t=="string"&&p(t))return new Date(t);if(typeof t=="object"&&t!==null){const n={};for(const[r,o]of Object.entries(t))n[r]=c(o);return n}return t}function a(t,n=!1){if(!t)return t;if(n&&typeof t=="object"&&t!==null&&"id"in t&&"ref"in t&&"data"in t&&typeof t.data=="function"){const r=t,o=r.data();return{id:r.id,...a(o)}}if(Array.isArray(t))return t.map(r=>a(r));if(l(t))return d(t);if(typeof t=="object"&&t!==null){const r={};for(const[o,e]of Object.entries(t))r[o]=a(e);return r}return t}function u(t,n=[]){if(!t)return t;if(Array.isArray(t))return t.map(r=>u(r,n));if(typeof t=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(t))try{return f(t)}catch{return t}if(t instanceof Date)try{return f(t)}catch{return t}if(typeof t=="object"&&t!==null){const r={};for(const[o,e]of Object.entries(t))n.includes(o)||(r[o]=u(e,n));return r}return t}function y(t,n){const r={};for(const[o,e]of Object.entries(n)){if(!(o in t)){r[o]=e;continue}JSON.stringify(t[o])!==JSON.stringify(e)&&(r[o]=e)}return{...r,updatedAt:new Date().toISOString()}}export{c as convertISOStringsToDates,y as createFirestorePartialUpdate,s as createTimestamp,d as firestoreToISOString,l as isTimestamp,u as prepareForFirestore,f as toTimestamp,a as transformFirestoreData};
1
+ import{handleError as o}from"@donotdev/core";function s(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:()=>new Date(e),toMillis:()=>e.getTime(),isEqual:t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,valueOf:()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`}}function c(e){try{if(typeof e=="string"){const t=new Date(e);if(isNaN(t.getTime()))throw o("Invalid date string format",{context:{value:e}});return s(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw o("Invalid Date object",{context:{value:e}});return s(e)}throw o("Invalid date value type",{context:{valueType:typeof e}})}catch(t){throw o(t,"Failed to convert to Timestamp")}}function l(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw o("Invalid Date object",{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){const t=new Date(e);if(isNaN(t.getTime()))throw o("Invalid date string format",{context:{value:e}});return t.toISOString()}throw o("Invalid date value type",{context:{valueType:typeof e}})}catch(t){throw o(t,"Failed to convert to ISO string")}}function y(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function m(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return!1;const r=new Date(e);return!isNaN(r.getTime())}function u(e){if(!e)return e;if(Array.isArray(e))return e.map(t=>u(t));if(typeof e=="string"&&m(e))return new Date(e);if(typeof e=="object"&&e!==null){const t={};for(const[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function f(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){const r=e,n=r.data();return{id:r.id,...f(n)}}if(Array.isArray(e))return e.map(r=>f(r));if(y(e))return l(e);if(typeof e=="object"&&e!==null){const r={};for(const[n,i]of Object.entries(e))r[n]=f(i);return r}return e}function p(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>p(r,t));if(typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))try{return c(e)}catch{return e}if(e instanceof Date)try{return c(e)}catch{return e}if(typeof e=="object"&&e!==null){const r={};for(const[n,i]of Object.entries(e))t.includes(n)||(r[n]=p(i,t));return r}return e}function D(e,t){const r={};for(const[n,i]of Object.entries(t)){if(!(n in e)){r[n]=i;continue}JSON.stringify(e[n])!==JSON.stringify(i)&&(r[n]=i)}return{...r,updatedAt:new Date().toISOString()}}export{u as convertISOStringsToDates,D as createFirestorePartialUpdate,s as createTimestamp,l as firestoreToISOString,y as isTimestamp,p as prepareForFirestore,c as toTimestamp,f as transformFirestoreData};
@@ -1 +1 @@
1
- import{handleError as o}from"@donotdev/core";const m=typeof window<"u",i=e=>()=>{throw o(new Error(`Firebase Admin function '${e}' is not available in browser environments`),{userMessage:"This operation requires server-side Firebase access and cannot be used in the browser",severity:"error"})},b=m?null:i("admin"),w=i("getAdminFirestore"),g=i("generateId");function x(e){const r=new AbortController;let t;return e?.timeout&&(t=setTimeout(()=>{const a=new Error("Request timeout exceeded");r.abort(o(a,{userMessage:"The operation timed out",context:{timeoutMs:e.timeout,abortKey:e.abortKey},severity:"warning"}))},e.timeout)),e?.externalSignal&&e.externalSignal.addEventListener("abort",()=>{r.abort(e.externalSignal?.reason||"External abort")}),r.signal.addEventListener("abort",()=>{t!==void 0&&clearTimeout(t)}),r}function p(e,r){return o(e,{userMessage:r?`Error during ${r}: ${e.message||"An error occurred"}`:void 0,context:{operation:r}})}async function v(e,r,t={}){const{retry:a=!1,maxRetries:s=3,retryDelay:d=300}=t;let n=0;for(;;)try{return await r()}catch(u){if(n++,h(u)&&a&&n<=s){const c=d*Math.pow(2,n-1);await new Promise(l=>setTimeout(l,c));continue}throw o(u,{userMessage:`Firebase operation "${e}" failed`,context:{operation:e,attempt:n,maxRetries:s,options:t}})}}function h(e){const r=["permission-denied","invalid-argument","already-exists","not-found","unauthenticated"];return e&&e.name==="DoNotDevError"&&r.includes(e.code)?!1:e&&e.code?["unavailable","deadline","cancel","network","timeout","internal","resource","exhausted"].some(t=>e.code.toLowerCase().includes(t)):!0}export{b as admin,x as createAbortController,v as executeFirebaseOperation,g as generateId,w as getAdminFirestore,p as handleFirebaseError};
1
+ import{handleError as i}from"@donotdev/core";const s=typeof window<"u",a=e=>()=>{throw i(new Error(`Firebase Admin function '${e}' is not available in browser environments`),{userMessage:"This operation requires server-side Firebase access and cannot be used in the browser",severity:"error"})},w=s?null:a("admin"),y=a("getAdminFirestore"),x=a("generateId");function h(e){const t=new AbortController;let r;return e?.timeout&&(r=setTimeout(()=>{const n=new Error("Request timeout exceeded");t.abort(i(n,{userMessage:"The operation timed out",context:{timeoutMs:e.timeout,abortKey:e.abortKey},severity:"warning"}))},e.timeout)),e?.externalSignal&&e.externalSignal.addEventListener("abort",()=>{t.abort(e.externalSignal?.reason||"External abort")}),t.signal.addEventListener("abort",()=>{r!==void 0&&clearTimeout(r)}),t}function v(e,t){return i(e,{userMessage:t?`Error during ${t}: ${e.message||"An error occurred"}`:void 0,context:{operation:t}})}async function E(e,t,r={}){const{retry:n=!1,maxRetries:d=3,retryDelay:l=300}=r;let o=0;for(;;)try{return await t()}catch(u){if(o++,b(u)&&n&&o<=d){const c=l*Math.pow(2,o-1);await new Promise(m=>setTimeout(m,c));continue}throw i(u,{userMessage:`Firebase operation "${e}" failed`,context:{operation:e,attempt:o,maxRetries:d,options:r}})}}function b(e){const t=["permission-denied","invalid-argument","already-exists","not-found","unauthenticated"];return e&&e.name==="DoNotDevError"&&t.includes(e.code)?!1:e&&e.code?["unavailable","deadline","cancel","network","timeout","internal","resource","exhausted"].some(n=>e.code.toLowerCase().includes(n)):!0}export{w as admin,h as createAbortController,E as executeFirebaseOperation,x as generateId,y as getAdminFirestore,v as handleFirebaseError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/firebase",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -28,7 +28,7 @@
28
28
  "valibot": "^1.2.0"
29
29
  },
30
30
  "peerDependencies": {
31
- "@donotdev/core": "0.0.3",
31
+ "@donotdev/core": "0.0.4",
32
32
  "firebase": "^12.5.0",
33
33
  "firebase-admin": "^13.6.0"
34
34
  },