@donotdev/firebase 0.0.8 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/firestore.js +1 -1
- package/dist/client/functions.js +1 -1
- package/dist/client/imageProcessing.js +1 -1
- package/dist/client/sdk.js +1 -1
- package/dist/client/storage.js +1 -1
- package/dist/server/batch.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/init.js +2 -2
- package/dist/server/subscription.js +1 -1
- package/dist/server/uniqueness.js +1 -1
- package/dist/server/utils.js +1 -1
- package/dist/server/validation.js +1 -1
- package/dist/shared/transform.js +1 -1
- package/dist/shared/utils.js +1 -1
- package/package.json +2 -2
package/dist/client/firestore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getFirestore as
|
|
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};
|
package/dist/client/functions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getFunctions as
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import v from"browser-image-compression";const f={full:{width:1600,height:1200},thumbnail:{width:320,height:240},medium:{width:800,height:600}};async function p(a,t){const{dimensions:e,quality:i=.9,maxSizeMB:o=2,backgroundColor:d,maintainAspectRatio:y=!0}=t;return new Promise(async(x,l)=>{try{const b=await v(a,{maxSizeMB:o,useWebWorker:!0}),n=new Image;n.onload=()=>{try{const r=document.createElement("canvas");r.width=e.width,r.height=e.height;const s=r.getContext("2d");if(!s){l(new Error("Could not get canvas context"));return}d?(s.fillStyle=d,s.fillRect(0,0,r.width,r.height)):s.clearRect(0,0,r.width,r.height);let g=0,w=0,h=e.width,c=e.height;if(y){const m=Math.min(e.width/n.width,e.height/n.height);h=n.width*m,c=n.height*m,g=(e.width-h)/2,w=(e.height-c)/2}s.drawImage(n,g,w,h,c),r.toBlob(m=>{m?x({blob:m,mimeType:"image/webp",dimensions:e}):l(new Error("Failed to convert canvas to blob"))},"image/webp",i)}catch(r){l(r)}},n.onerror=()=>{l(new Error("Failed to load image"))},n.src=URL.createObjectURL(b)}catch(u){l(u)}})}async function M(a,t){const e=t?.fullDimensions??f.full,i=t?.thumbnailDimensions??f.thumbnail,[o,d]=await Promise.all([p(a,{dimensions:e,quality:t?.quality,maxSizeMB:t?.maxSizeMB}),p(a,{dimensions:i,quality:t?.quality??.8,maxSizeMB:1})]);return{full:o,thumbnail:d}}function B(a,t){const{maxSizeMB:e=10,allowedTypes:i=["image/jpeg","image/png","image/webp","image/gif"]}=t??{};if(!i.includes(a.type))return{valid:!1,error:`Invalid file type. Allowed: ${i.join(", ")}`};const o=a.size/(1024*1024);return o>e?{valid:!1,error:`File too large (${o.toFixed(2)}MB). Maximum: ${e}MB`}:{valid:!0}}function I(a){return new Promise((t,e)=>{const i=new FileReader;i.onload=()=>{typeof i.result=="string"?t(i.result):e(new Error("Failed to read file"))},i.onerror=()=>e(new Error("Failed to read file")),i.readAsDataURL(a)})}export{f as DEFAULT_DIMENSIONS,I as createImagePreview,p as processImage,M as processImageWithThumbnail,B as validateImageFile};
|
package/dist/client/sdk.js
CHANGED
|
@@ -18,4 +18,4 @@
|
|
|
18
18
|
* @license Commercial
|
|
19
19
|
*
|
|
20
20
|
* @module @donotdev/firebase/sdk
|
|
21
|
-
*/import{initializeApp as
|
|
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};
|
package/dist/client/storage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getStorage as i,ref as
|
|
1
|
+
import{getStorage as i,ref as r,uploadBytes as g,uploadBytesResumable as B,getDownloadURL as f,deleteObject as w,listAll as S}from"firebase/storage";const h=10*1024*1024;function U(t){return t.replace(/[^a-zA-Z0-9.-]/g,"_")}function P(t,e){const a=Date.now(),o=U(e||t);return`${a}_${o}`}function F(t,e){const a=[e.basePath];return e.subfolder&&a.push(e.subfolder),a.push(t),a.join("/")}function D(t,e){const a=e.maxSize??h,o=t instanceof File?t.name:"blob";if(t.size>a)throw new Error(`File size (${(t.size/1024/1024).toFixed(2)}MB) exceeds maximum allowed (${(a/1024/1024).toFixed(2)}MB)`);const s=i(),n=P(o,e.filename),l=F(n,e),d=r(s,l),u=e.metadata||{},m=B(d,t,u);e.onProgress&&m.on("state_changed",c=>{const b=c.bytesTransferred/c.totalBytes*100;e.onProgress({bytesTransferred:c.bytesTransferred,totalBytes:c.totalBytes,progress:b})});const p=m.then(async()=>({url:await f(d),path:l,filename:o}));return{task:m,promise:p}}async function y(t,e){const a=e.maxSize??h;if(t.size>a)throw new Error(`File size (${(t.size/1024/1024).toFixed(2)}MB) exceeds maximum allowed (${(a/1024/1024).toFixed(2)}MB)`);const o=i(),s=P(t.name,e.filename),n=F(s,e),l=r(o,n);return await g(l,t),{url:await f(l),path:n,filename:t.name}}async function _(t,e){const a=t.map(o=>y(o,e));return Promise.all(a)}async function M(t){try{const e=i(),o=new URL(t).pathname.match(/\/o\/(.+)\?/);if(o&&o[1]){const s=decodeURIComponent(o[1]),n=r(e,s);await w(n)}}catch{}}async function E(t){try{const e=i(),a=r(e,t);await w(a)}catch{}}async function I(t){const e=t.map(a=>M(a));await Promise.all(e)}async function $(t){const e=i(),a=r(e,t);return(await S(a)).items}async function L(t){const a=(await $(t)).map(o=>f(o));return Promise.all(a)}async function N(t){const e=i(),a=r(e,t);return f(a)}function O(t){const e=i();return r(e,t)}async function T(t){const a=(await $(t)).map(o=>w(o));await Promise.all(a)}async function C(t,e,a){return y(t,{basePath:e,subfolder:a,maxSize:5*1024*1024})}async function Z(t,e,a){return _(t,{basePath:e,subfolder:a,maxSize:5*1024*1024})}async function A(t,e,a){const{processImageWithThumbnail:o}=await import("./imageProcessing"),{full:s,thumbnail:n}=await o(t),l=i(),u=`${Date.now()}_${t.name.replace(/\.[^/.]+$/,"")}`,m=a?`${e}/${a}/${u}_full.webp`:`${e}/${u}_full.webp`,p=a?`${e}/${a}/${u}_thumb.webp`:`${e}/${u}_thumb.webp`,c={contentType:"image/webp",cacheControl:"public, max-age=2592000"},b=r(l,m),x=r(l,p);await Promise.all([g(b,s.blob,c),g(x,n.blob,c)]);const[z,R]=await Promise.all([f(b),f(x)]);return{fullUrl:z,thumbUrl:R,fullPath:m,thumbPath:p}}async function k(t,e,a){const o=t.map(s=>A(s,e,a));return Promise.all(o)}export{O as createStorageRef,T as deleteAllFiles,E as deleteFileByPath,M as deleteFileByUrl,I as deleteFilesByUrl,N as getFileUrl,L as getFileUrls,$ as listFiles,y as uploadFile,D as uploadFileResumable,_ as uploadFiles,C as uploadImage,Z as uploadImages,A as uploadProcessedImage,k as uploadProcessedImages};
|
package/dist/server/batch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as E from"valibot";import{handleError as
|
|
1
|
+
import*as E from"valibot";import{handleError 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:I=450,removeFields:l=[],validate:v=!!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(v&&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>=I&&(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`)},k=p?g("batchWrite"):i.batchWrite,R=p?g("batchCreate"):i.batchCreate,S=p?g("batchUpdate"):i.batchUpdate,G=p?g("batchDelete"):i.batchDelete,_=p?g("runTransaction"):i.runTransaction,z=p?g("bulkGet"):i.bulkGet;export{R as batchCreate,G as batchDelete,S as batchUpdate,k as batchWrite,z as bulkGet,_ as runTransaction};
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./init";export*from"./utils";export*from"./batch";export*from"./subscription";export*from"./validation";export*from"./uniqueness";export*from"../shared/transform";import{FieldValue as
|
|
1
|
+
export*from"./init";export*from"./utils";export*from"./batch";export*from"./subscription";export*from"./validation";export*from"./uniqueness";export*from"../shared/transform";import{FieldValue as i,Query as l,Timestamp as u}from"firebase-admin/firestore";export{i as FieldValue,l as Query,u as Timestamp};
|
package/dist/server/init.js
CHANGED
|
@@ -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
|
|
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:
|
|
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{handleError 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{handleError as
|
|
1
|
+
import{handleError 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{handleError as
|
|
1
|
+
import{handleError 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};
|
package/dist/server/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{handleError 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,
|
|
1
|
+
import{handleError 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{handleError as r}from"@donotdev/core/server";import{validateUniqueness as
|
|
1
|
+
import*as n from"valibot";import{handleError as r}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(t,e,i,o){try{n.parse(t,e),t.metadata?.uniqueFields?.length&&await s(t.metadata.collection,t.metadata.uniqueFields,e,o),t.metadata?.customValidate&&await t.metadata.customValidate(e,i)}catch(a){throw a.name==="ValibotError"||a.issues?r(a,{userMessage:"Document validation failed",context:{validationErrors:a.issues||[],data:e},severity:"warning"}):r(a,{userMessage:"Document validation failed",context:{collection:t.metadata?.collection||"unknown"},severity:"error"})}}function c(t,e){const i=t;return i.metadata=e,i}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};
|
package/dist/shared/transform.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{handleError as i}from"@donotdev/core";function s(
|
|
1
|
+
import{handleError as i}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 g(e){try{if(typeof e=="string"){const t=new Date(e);if(isNaN(t.getTime()))throw i(new Error("Invalid date string format"),{context:{value:e}});return s(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw i(new Error("Invalid Date object"),{context:{value:e}});return s(e)}throw i(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw i(t,"Failed to convert to Timestamp")}}function p(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw i(new Error("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 i(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw i(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw i(t,"Failed to convert to ISO string")}}function l(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function y(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 c(e){if(!e)return e;if(Array.isArray(e))return e.map(t=>c(t));if(typeof e=="string"&&y(e))return new Date(e);if(typeof e=="object"&&e!==null){const t={};for(const[r,n]of Object.entries(e))t[r]=c(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(l(e))return p(e);if(typeof e=="object"&&e!==null){const r={};for(const[n,o]of Object.entries(e))r[n]=f(o);return r}return e}function u(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>u(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){const r={};for(const[n,o]of Object.entries(e))t.includes(n)||o!==void 0&&(r[n]=u(o,t));return r}return e}function D(e,t){const r={};for(const[n,o]of Object.entries(t)){if(!(n in e)){r[n]=o;continue}JSON.stringify(e[n])!==JSON.stringify(o)&&(r[n]=o)}return{...r,updatedAt:new Date().toISOString()}}export{c as convertISOStringsToDates,D as createFirestorePartialUpdate,s as createTimestamp,p as firestoreToISOString,l as isTimestamp,u as prepareForFirestore,g as toTimestamp,f as transformFirestoreData};
|
package/dist/shared/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{handleError as
|
|
1
|
+
import{handleError as o}from"@donotdev/core";const s=typeof window<"u",n=e=>()=>{throw o(new Error(`Firebase Admin function '${e}' is not available in browser environments`),{userMessage:"This operation requires server-side Firebase access",context:{function:e}})},g=s?null:n("admin"),w=n("getAdminFirestore"),y=n("generateId");function h(e){const t=new AbortController;let r;return e?.timeout&&(r=setTimeout(()=>{t.abort(o(new Error("Request timeout exceeded"),{userMessage:"The operation timed out",context:{timeoutMs:e.timeout,abortKey:e.abortKey}}))},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 E(e,t){return o(e,{userMessage:t?`Error during ${t}`:void 0,context:{operation:t}})}async function v(e,t,r={}){const{retry:i=!1,maxRetries:l=3,retryDelay:d=300}=r;let a=0;for(;;)try{return await t()}catch(u){if(a++,b(u)&&i&&a<=l){const c=d*Math.pow(2,a-1);await new Promise(m=>setTimeout(m,c));continue}throw o(u,{userMessage:`Firebase operation "${e}" failed`,context:{operation:e,attempt:a,maxRetries:l,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(i=>e.code.toLowerCase().includes(i)):!0}export{g as admin,h as createAbortController,v as executeFirebaseOperation,y as generateId,w as getAdminFirestore,E as handleFirebaseError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/firebase",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.10",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"valibot": "^1.2.0"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@donotdev/core": "^0.0.
|
|
32
|
+
"@donotdev/core": "^0.0.20",
|
|
33
33
|
"firebase": "^12.8.0",
|
|
34
34
|
"firebase-admin": "^13.6.0"
|
|
35
35
|
},
|