@donotdev/functions 0.2.0 → 0.2.1
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/lib/chunks/{chunk-IFOYVSPU.js → chunk-3F4BWKQD.js} +2 -2
- package/lib/chunks/{chunk-JTAGPPPL.js → chunk-5IPULSUX.js} +2 -2
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.js.map +7 -0
- package/lib/chunks/{chunk-RM7DV6IQ.js → chunk-CXBSROEW.js} +2 -2
- package/lib/chunks/{chunk-5DTPEM64.js → chunk-GYTCWMXV.js} +1 -1
- package/lib/chunks/{chunk-5DTPEM64.js.map → chunk-GYTCWMXV.js.map} +1 -1
- package/lib/chunks/chunk-LCDLG4VG.js +151 -0
- package/lib/chunks/{chunk-UH4L3EF3.js.map → chunk-LCDLG4VG.js.map} +4 -4
- package/lib/chunks/{chunk-4U7QQWYG.js → chunk-MQANUSY3.js} +2 -2
- package/lib/chunks/chunk-OFQVO3FD.js +22 -0
- package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/{chunk-QJAU2MWV.js → chunk-US2VOP4S.js} +2 -2
- package/lib/chunks/{chunk-QJAU2MWV.js.map → chunk-US2VOP4S.js.map} +3 -3
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/{monitoring-AGCSU3FI.js → monitoring-E7JBYBHQ.js} +2 -2
- package/lib/chunks/{rateLimiter-6KO7AIZP.js → rateLimiter-SQISLOP5.js} +2 -2
- package/lib/chunks/{server-32A5RH4C.js → server-IQ5JNJOM.js} +2 -2
- package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
- package/lib/firebase/baseFunction.d.ts +0 -0
- package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +0 -0
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/firebase/billing/webhookHandler.d.ts +0 -0
- package/lib/firebase/config/constants.d.ts +0 -0
- package/lib/firebase/config/index.d.ts +0 -0
- package/lib/firebase/config/secrets.d.ts +0 -0
- package/lib/firebase/crud/aggregate.d.ts +0 -0
- package/lib/firebase/crud/create.d.ts +0 -0
- package/lib/firebase/crud/delete.d.ts +0 -0
- package/lib/firebase/crud/get.d.ts +0 -0
- package/lib/firebase/crud/index.d.ts +0 -0
- package/lib/firebase/crud/list.d.ts +0 -0
- package/lib/firebase/crud/update.d.ts +0 -0
- package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/index.d.ts +0 -0
- package/lib/firebase/index.d.ts +0 -0
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +2 -2
- package/lib/firebase/oauth/disconnect.d.ts +0 -0
- package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
- package/lib/firebase/oauth/getConnections.d.ts +0 -0
- package/lib/firebase/oauth/githubAccess.d.ts +0 -0
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +0 -0
- package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
- package/lib/firebase/scheduled/index.d.ts +0 -0
- package/lib/shared/ai/classifyAIError.d.ts +0 -0
- package/lib/shared/ai/costTracker.d.ts +0 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- package/lib/shared/billing/createCheckout.d.ts +0 -0
- package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
- package/lib/shared/billing/helpers/index.d.ts +0 -0
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
- package/lib/shared/billing/idempotency.d.ts +1 -12
- package/lib/shared/billing/index.d.ts +0 -0
- package/lib/shared/billing/stripeClient.d.ts +45 -0
- package/lib/shared/billing/webhookHandler.d.ts +5 -4
- package/lib/shared/email/createEmailRoute.d.ts +0 -0
- package/lib/shared/email/index.d.ts +0 -0
- package/lib/shared/email/provider.d.ts +0 -0
- package/lib/shared/email/resendProvider.d.ts +0 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +0 -0
- package/lib/shared/index.d.ts +0 -0
- package/lib/shared/index.js +1 -1
- package/lib/shared/index.js.map +0 -0
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +0 -0
- package/lib/shared/oauth/exchangeToken.d.ts +0 -0
- package/lib/shared/oauth/grantAccess.d.ts +0 -0
- package/lib/shared/oauth/index.d.ts +0 -0
- package/lib/shared/schema.d.ts +0 -0
- package/lib/shared/utils/detectFirestore.d.ts +0 -0
- package/lib/shared/utils/external/date.d.ts +0 -0
- package/lib/shared/utils/external/index.d.ts +0 -0
- package/lib/shared/utils/external/references.d.ts +0 -0
- package/lib/shared/utils/external/subscription.d.ts +0 -0
- package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
- package/lib/shared/utils/functionWrapper.d.ts +0 -0
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +0 -0
- package/lib/shared/utils/internal/firebase.d.ts +0 -0
- package/lib/shared/utils/internal/idempotency.d.ts +0 -0
- package/lib/shared/utils/internal/index.d.ts +0 -0
- package/lib/shared/utils/internal/monitoring.d.ts +0 -0
- package/lib/shared/utils/internal/rateLimiter.d.ts +0 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -8
- package/lib/shared/utils/schemaValidation.d.ts +0 -0
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +0 -0
- package/lib/shared/utils.d.ts +0 -43
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +0 -0
- package/lib/supabase/auth/deleteAccount.d.ts +0 -0
- package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
- package/lib/supabase/baseFunction.d.ts +0 -0
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +0 -0
- package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/supabase/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +0 -0
- package/lib/supabase/crud/list.d.ts +0 -8
- package/lib/supabase/crud/update.d.ts +0 -0
- package/lib/supabase/edgeFunction.d.ts +0 -0
- package/lib/supabase/email/createEmailFunction.d.ts +0 -0
- package/lib/supabase/helpers/authProvider.d.ts +0 -0
- package/lib/supabase/index.d.ts +3 -2
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +3 -3
- package/lib/supabase/oauth/disconnect.d.ts +0 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
- package/lib/supabase/oauth/getConnections.d.ts +0 -0
- package/lib/supabase/oauth/index.d.ts +0 -0
- package/lib/supabase/oauth/refreshToken.d.ts +0 -0
- package/lib/supabase/registerCrudFunctions.d.ts +0 -0
- package/lib/supabase/utils/idempotency.d.ts +0 -0
- package/lib/supabase/utils/monitoring.d.ts +0 -0
- package/lib/supabase/utils/rateLimiter.d.ts +0 -0
- package/lib/vercel/api/ai/chat.d.ts +0 -0
- package/lib/vercel/api/ai/index.d.ts +0 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
- package/lib/vercel/api/billing/cancel.d.ts +0 -0
- package/lib/vercel/api/billing/change-plan.d.ts +0 -0
- package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
- package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
- package/lib/vercel/api/billing/index.d.ts +0 -0
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
- package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/create.d.ts +0 -0
- package/lib/vercel/api/crud/delete.d.ts +0 -0
- package/lib/vercel/api/crud/get.d.ts +0 -0
- package/lib/vercel/api/crud/index.d.ts +0 -0
- package/lib/vercel/api/crud/list.d.ts +0 -0
- package/lib/vercel/api/crud/update.d.ts +0 -0
- package/lib/vercel/api/index.d.ts +0 -0
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +2 -2
- package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +0 -0
- package/package.json +2 -2
- package/src/firebase/billing/cancelSubscription.ts +1 -1
- package/src/firebase/billing/changePlan.ts +1 -5
- package/src/firebase/billing/createCheckoutSession.ts +1 -5
- package/src/firebase/billing/createCustomerPortal.ts +1 -1
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
- package/src/firebase/billing/webhookHandler.ts +2 -2
- package/src/shared/__tests__/internalValidation.test.ts +1 -40
- package/src/shared/__tests__/logger.test.ts +31 -0
- package/src/shared/__tests__/utils.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -38
- package/src/shared/billing/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +1 -1
- package/src/shared/billing/idempotency.ts +5 -172
- package/src/shared/billing/stripeClient.ts +91 -0
- package/src/shared/billing/webhookHandler.ts +5 -5
- package/src/shared/logger.ts +4 -6
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils.ts +0 -77
- package/src/supabase/billing/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +1 -5
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -5
- package/src/supabase/billing/stripeWebhook.ts +2 -2
- package/src/supabase/crud/list.ts +2 -0
- package/src/supabase/index.ts +3 -3
- package/src/vercel/api/billing/change-plan.ts +1 -1
- package/src/vercel/api/billing/create-checkout-session.ts +1 -5
- package/src/vercel/api/billing/customer-portal.ts +1 -1
- package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
- package/src/vercel/api/billing/webhook-handler.ts +1 -1
- package/lib/chunks/chunk-2JL3GDTO.js +0 -151
- package/lib/chunks/chunk-2JL3GDTO.js.map +0 -7
- package/lib/chunks/chunk-4TVLH2W2.js +0 -22
- package/lib/chunks/chunk-6CQXHNVL.js +0 -22
- package/lib/chunks/chunk-6CQXHNVL.js.map +0 -7
- package/lib/chunks/chunk-6DSCPZC6.js +0 -22
- package/lib/chunks/chunk-6DSCPZC6.js.map +0 -7
- package/lib/chunks/chunk-7E6TGWHU.js +0 -22
- package/lib/chunks/chunk-7E6TGWHU.js.map +0 -7
- package/lib/chunks/chunk-7LT32OWE.js +0 -22
- package/lib/chunks/chunk-7VH2GJXT.js +0 -151
- package/lib/chunks/chunk-7VH2GJXT.js.map +0 -7
- package/lib/chunks/chunk-API5A4BV.js +0 -22
- package/lib/chunks/chunk-API5A4BV.js.map +0 -7
- package/lib/chunks/chunk-BUP7SXPV.js +0 -23
- package/lib/chunks/chunk-BXKRI3JJ.js +0 -22
- package/lib/chunks/chunk-BXKRI3JJ.js.map +0 -7
- package/lib/chunks/chunk-FSLGZD7A.js +0 -21
- package/lib/chunks/chunk-GVLSPWDD.js +0 -151
- package/lib/chunks/chunk-GVLSPWDD.js.map +0 -7
- package/lib/chunks/chunk-GXQVWEFT.js +0 -22
- package/lib/chunks/chunk-GXQVWEFT.js.map +0 -7
- package/lib/chunks/chunk-HB7EGXVI.js +0 -22
- package/lib/chunks/chunk-HB7EGXVI.js.map +0 -7
- package/lib/chunks/chunk-HM7XCMWW.js +0 -22
- package/lib/chunks/chunk-HM7XCMWW.js.map +0 -7
- package/lib/chunks/chunk-I7IOIL6U.js +0 -151
- package/lib/chunks/chunk-I7IOIL6U.js.map +0 -7
- package/lib/chunks/chunk-IFOYVSPU.js.map +0 -7
- package/lib/chunks/chunk-JTAGPPPL.js.map +0 -7
- package/lib/chunks/chunk-MZ232FUE.js +0 -22
- package/lib/chunks/chunk-MZ232FUE.js.map +0 -7
- package/lib/chunks/chunk-NE5ZTUUZ.js +0 -22
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +0 -7
- package/lib/chunks/chunk-NP2AN2TV.js +0 -22
- package/lib/chunks/chunk-NP2AN2TV.js.map +0 -7
- package/lib/chunks/chunk-RM7DV6IQ.js.map +0 -7
- package/lib/chunks/chunk-RQZGIZHD.js +0 -151
- package/lib/chunks/chunk-RQZGIZHD.js.map +0 -7
- package/lib/chunks/chunk-TBEDQLOB.js +0 -23
- package/lib/chunks/chunk-TBEDQLOB.js.map +0 -7
- package/lib/chunks/chunk-TMHBP3HB.js +0 -22
- package/lib/chunks/chunk-TMHBP3HB.js.map +0 -7
- package/lib/chunks/chunk-UH4L3EF3.js +0 -151
- package/lib/chunks/chunk-UJBIU6TL.js +0 -22
- package/lib/chunks/chunk-UJBIU6TL.js.map +0 -7
- package/lib/chunks/chunk-VKEYW3NT.js +0 -22
- package/lib/chunks/chunk-VKEYW3NT.js.map +0 -7
- package/lib/chunks/chunk-XGXBMXJ6.js +0 -22
- package/lib/chunks/chunk-XGXBMXJ6.js.map +0 -7
- package/lib/chunks/chunk-Y44NEQQG.js +0 -22
- package/lib/chunks/chunk-Y44NEQQG.js.map +0 -7
- package/lib/chunks/chunk-ZVU3KPXI.js +0 -22
- package/lib/chunks/chunk-ZVU3KPXI.js.map +0 -7
- package/lib/chunks/monitoring-PVQMFL34.js +0 -22
- package/lib/chunks/monitoring-V7FZXTTW.js +0 -22
- package/lib/chunks/monitoring-V7FZXTTW.js.map +0 -7
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +0 -7
- package/lib/chunks/rateLimiter-OXVBFW5C.js +0 -22
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +0 -7
- package/lib/chunks/rateLimiter-U45OMTWR.js +0 -22
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +0 -7
- package/lib/chunks/server-32A5RH4C.js.map +0 -7
- package/lib/chunks/server-7HDAP5DL.js +0 -22
- package/lib/chunks/server-7HDAP5DL.js.map +0 -7
- package/lib/chunks/server-S2IMFOY7.js +0 -22
- package/lib/chunks/server-S2IMFOY7.js.map +0 -7
- package/lib/shared/ai/createAIHandler.d.ts +0 -39
- package/lib/shared/ai/providers/anthropic.d.ts +0 -12
- package/lib/shared/ai/providers/google.d.ts +0 -10
- package/lib/shared/ai/providers/index.d.ts +0 -23
- package/lib/shared/ai/providers/openai.d.ts +0 -10
- package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
- /package/lib/chunks/{chunk-7LT32OWE.js.map → chunk-3F4BWKQD.js.map} +0 -0
- /package/lib/chunks/{chunk-4TVLH2W2.js.map → chunk-5IPULSUX.js.map} +0 -0
- /package/lib/chunks/{chunk-BUP7SXPV.js.map → chunk-CXBSROEW.js.map} +0 -0
- /package/lib/chunks/{chunk-4U7QQWYG.js.map → chunk-MQANUSY3.js.map} +0 -0
- /package/lib/chunks/{chunk-FSLGZD7A.js.map → monitoring-E7JBYBHQ.js.map} +0 -0
- /package/lib/chunks/{monitoring-AGCSU3FI.js.map → rateLimiter-SQISLOP5.js.map} +0 -0
- /package/lib/chunks/{monitoring-PVQMFL34.js.map → server-IQ5JNJOM.js.map} +0 -0
|
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{$ as S,B as v,I as T,K as q,L as d,T as E,ca as C,da as D,ea as M}from"./chunk-
|
|
22
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
import{$ as S,B as v,I as T,K as q,L as d,T as E,ca as C,da as D,ea as M}from"./chunk-GYTCWMXV.js";import{a as i}from"./chunk-AYY7UXNI.js";function K(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}i(K,"createMetadata");function Y(e){return{updatedAt:new Date().toISOString(),updatedById:e}}i(Y,"updateMetadata");var F=Object.freeze({insertedIds:[],updatedIds:[],deletedIds:[]});async function X(e){let{collection:t,ops:p,createSchema:o,draftCreateSchema:n,updateSchema:a,access:s,uid:u,userRole:c,transact:f,mintInsertId:$,stampInsertMetadata:I,stampUpdateMetadata:A,audit:x}=e,g=v(C,p);if(!g.success){let r=g.issues.map(m=>`${m.path?.map(l=>l.key).join(".")||"root"}: ${m.message}`).join("; ");throw new d(`Bulk payload validation failed: ${r}`,"invalid-argument",{details:{validationErrors:g.issues}})}let R=g.output,w=R.inserts??[],h=R.updates??[],k=R.deletes??[],P=M(R);if(P.where!==null)throw new T(P.collisions,P.where);if(w.length===0&&h.length===0&&k.length===0)return F;if(w.length>0){if(!s.create)throw new d(`Bulk insert requested on ${t} but no create role is configured`,"permission-denied");if(!E(c,s.create))throw new d(`Access denied for bulk insert on ${t}. Required: ${s.create}, your role: ${c}`,"permission-denied")}if(h.length>0){if(!s.update)throw new d(`Bulk update requested on ${t} but no update role is configured`,"permission-denied");if(!E(c,s.update))throw new d(`Access denied for bulk update on ${t}. Required: ${s.update}, your role: ${c}`,"permission-denied")}if(k.length>0){if(!s.delete)throw new d(`Bulk delete requested on ${t} but no delete role is configured`,"permission-denied");if(!E(c,s.delete))throw new d(`Access denied for bulk delete on ${t}. Required: ${s.delete}, your role: ${c}`,"permission-denied")}for(let r=0;r<w.length;r++){let l=w[r],y=l.status??S,B=y==="draft",L=B&&n?n:o,N=B&&n?{...l,status:y}:l;O(N,L,`inserts[${r}]`)}for(let r=0;r<h.length;r++)O(h[r].patch,a,`updates[${r}]`);let b=w.map(r=>{let m=r,l=m.status??S,y=$?$():"",B=I?I({...m,status:l},u):{...m,status:l};return{id:y,row:B}}),U=h.map(r=>({id:r.id,patch:A?A(r.patch,u):r.patch})),_=await f({inserts:b,updates:U,deletes:[...k]}),j=v(D,_);if(!j.success)throw new d(`Bulk transact() returned an unexpected shape for ${t}`,"internal");return x&&x(`crud.bulk.${t}`,{counts:{inserts:b.length,updates:U.length,deletes:k.length}}),j.output}i(X,"executeBulk");function O(e,t,p){let o=v(t,e);if(o.success)return;let n=o.issues.map(a=>`${a.path?.map(s=>s.key).join(".")||"root"}: ${a.message}`).join("; ");throw new d(`Validation failed on ${p}: ${n}`,"invalid-argument",{details:{validationErrors:o.issues}})}i(O,"validateRow");async function V(e,t,p){let o=q(e);if(!o.success)return{success:!1,error:`Invalid email request: ${o.issues?.map(f=>f.message).join(", ")}`};let n=t.templates[e.templateId];if(!n)return{success:!1,error:`Template not found: ${e.templateId}`};let a=e.locale||"fr",s=n.subject(e.data,a),u=n.html(e.data,a);return{success:!0,messageId:(await p.send({from:e.from||t.defaultFrom,to:e.to,subject:s,html:u,replyTo:e.replyTo||t.replyTo})).messageId}}i(V,"handleEmailRequest");var z="https://api.resend.com/emails";function J(e){if(!e)throw new Error("Resend API key is required");return{async send({from:t,to:p,subject:o,html:n,replyTo:a}){let s={from:t,to:p,subject:o,html:n};a&&(s.reply_to=a);let u=await fetch(z,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok){let f=await u.text().catch(()=>"Unknown error");throw new Error(`Resend API error (${u.status}): ${f}`)}return{messageId:(await u.json()).id}}}}i(J,"createResendProvider");export{K as a,Y as b,X as c,V as d,J as e};
|
|
22
|
+
//# sourceMappingURL=chunk-MQANUSY3.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{a,o as g,w as E}from"./chunk-LCDLG4VG.js";import{a as e}from"./chunk-AYY7UXNI.js";import w from"stripe";var l=null;function I(t){if(!t)throw new Error("Stripe API key is required");let r=process.env.STRIPE_API_VERSION||g;return l=new w(t,{apiVersion:r}),l}e(I,"initStripe");function v(){if(!l){let t=process.env.STRIPE_SECRET_KEY;if(t)I(t);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return l}e(v,"getStripe");var p=new Proxy({},{get(t,r){return v()[r]}});function S(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}e(S,"validateStripeEnvironment");async function O(t,r){S();let o=((await r.getUser(t)).customClaims||{}).subscription,i=o?.subscriptionId;if(!i)throw a(new Error("No active subscription found"));let s=await p.subscriptions.update(i,{cancel_at_period_end:!0}),d=["active","canceled","past_due","trialing","incomplete"].includes(s.status)?s.status:"incomplete";return await E(t,{tier:o?.tier||"free",status:d,subscriptionEnd:new Date(s.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:s.id,customerId:s.customer},r),{success:!0,endsAt:new Date(s.current_period_end*1e3).toISOString()}}e(O,"cancelUserSubscription");async function Y(t,r,n,m,o){S();let i=m[n];if(!i||i.type!=="StripeSubscription")throw a(new Error("Invalid plan"));if(i.priceId!==r)throw a(new Error("Price ID mismatch with configuration"));let u=((await o.getUser(t)).customClaims||{}).subscription?.subscriptionId;if(!u)throw a(new Error("No active subscription found"));let _=await p.subscriptions.retrieve(u),c=await p.subscriptions.update(u,{items:[{id:_.items.data[0]?.id,price:r}],proration_behavior:"create_prorations"}),f=["active","canceled","past_due","trialing","incomplete"].includes(c.status)?c.status:"incomplete";return await E(t,{tier:i.tier,status:f,subscriptionEnd:new Date(c.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:c.cancel_at_period_end,subscriptionId:c.id,customerId:c.customer},o),{success:!0,newTier:i.tier,newPrice:i.price}}e(Y,"changeUserPlan");async function D(t,r,n){S();let s=((await r.getUser(t)).customClaims||{}).subscription?.customerId;if(!s)throw a(new Error("No customer found"));if(n){let d=new URL(n),u=new URL(process.env.FRONTEND_URL||"");if(d.origin!==u.origin)throw new Error("Invalid return URL: must match frontend domain")}return{url:(await p.billingPortal.sessions.create({customer:s,return_url:n||`${process.env.FRONTEND_URL}/billing`})).url}}e(D,"createCustomerPortalSession");export{I as a,p as b,S as c,O as d,Y as e,D as f};
|
|
22
|
+
//# sourceMappingURL=chunk-OFQVO3FD.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/billing/stripeClient.ts", "../../src/shared/billing/helpers/subscriptionManagement.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/billing/stripeClient.ts\n\n/**\n * @fileoverview Stripe client for billing functions\n * @description Lazily initialized Stripe SDK instance shared by the Firebase,\n * Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so\n * code that does not bill (CRUD, auth) never loads the Stripe SDK.\n *\n * @version 0.2.1\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport Stripe from 'stripe';\n\nimport { STRIPE_API_VERSION_PIN } from './apiVersion.js';\n\n// Lazy initialization of Stripe\nlet _stripe: Stripe | null = null;\n\n/**\n * Initialize Stripe explicitly (e.g. with a secret from defineSecret).\n * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.\n * @param apiKey - Stripe secret key\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function initStripe(apiKey: string) {\n if (!apiKey) throw new Error('Stripe API key is required');\n\n // Unset: the framework pin (pre-basil fields are still read by subscription handlers)\n const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;\n\n _stripe = new Stripe(apiKey, {\n apiVersion: apiVersion as any,\n });\n return _stripe;\n}\n\n/**\n * Get Stripe instance with lazy initialization\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getStripe(): Stripe {\n if (!_stripe) {\n // Legacy/Vercel fallback: Try process.env\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (STRIPE_SECRET_KEY) {\n initStripe(STRIPE_SECRET_KEY);\n } else {\n throw new Error(\n 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'\n );\n }\n }\n // We know _stripe is set here or we threw\n return _stripe!;\n}\n\n/**\n * Lazy-initialized Stripe instance proxy\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport const stripe = new Proxy({} as Stripe, {\n get(target, prop) {\n return getStripe()[prop as keyof Stripe];\n },\n});\n\n/**\n * Validates that required Stripe environment variables are set\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripeEnvironment(): void {\n // Functions v2 automatically injects secrets as process.env when declared in config\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (!STRIPE_SECRET_KEY) {\n throw new Error('Missing STRIPE_SECRET_KEY environment variable');\n }\n}\n", "// packages/functions/src/shared/billing/helpers/subscriptionManagement.ts\n\n/**\n * @fileoverview Shared Subscription Management Logic\n * @description Platform-agnostic subscription management functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport { SUBSCRIPTION_STATUS } from '@donotdev/core/server';\nimport type { BillingAuthProvider } from '@donotdev/core/server';\n\nimport { updateUserSubscription } from './updateUserSubscription.js';\nimport { handleError } from '../../errorHandling.js';\nimport { stripe, validateStripeEnvironment } from '../stripeClient.js';\n\n/**\n * Cancel user subscription at period end\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n userId: string,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; endsAt: string }> {\n validateStripeEnvironment();\n\n // Get user's current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string; tier?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Cancel at period end (don't delete immediately)\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n cancel_at_period_end: true,\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = validStatuses.includes(updatedSubscription.status as any)\n ? (updatedSubscription.status as (typeof validStatuses)[number])\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: subscription?.tier || 'free',\n status,\n subscriptionEnd: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: true,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n endsAt: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n };\n}\n\n/**\n * Change user subscription plan\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function changeUserPlan(\n userId: string,\n newPriceId: string,\n billingConfigKey: string,\n billingConfig: Record<string, any>,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; newTier: string; newPrice: number }> {\n validateStripeEnvironment();\n\n // Validate new plan exists in config\n const billingItem = billingConfig[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') {\n throw handleError(new Error('Invalid plan'));\n }\n\n // Validate price ID matches config\n if (billingItem.priceId !== newPriceId) {\n throw handleError(new Error('Price ID mismatch with configuration'));\n }\n\n // Get current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Get current subscription from Stripe\n const currentSubscription = (await stripe.subscriptions.retrieve(\n subscriptionId\n )) as Stripe.Subscription;\n\n // Update subscription in Stripe\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n items: [\n {\n id: currentSubscription.items.data[0]?.id,\n price: newPriceId,\n },\n ],\n proration_behavior: 'create_prorations', // Pro-rate the change\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = validStatuses.includes(updatedSubscription.status as any)\n ? (updatedSubscription.status as (typeof validStatuses)[number])\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: billingItem.tier,\n status,\n subscriptionEnd: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: (updatedSubscription as any).cancel_at_period_end,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n newTier: billingItem.tier,\n newPrice: billingItem.price,\n };\n}\n\n/**\n * Create Stripe Customer Portal session\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function createCustomerPortalSession(\n userId: string,\n authProvider: BillingAuthProvider,\n returnUrl?: string\n): Promise<{ url: string }> {\n validateStripeEnvironment();\n\n // Get customer ID from user claims\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { customerId?: string }\n | undefined;\n const customerId = subscription?.customerId;\n\n if (!customerId) {\n throw handleError(new Error('No customer found'));\n }\n\n // Validate returnUrl domain\n if (returnUrl) {\n const parsed = new URL(returnUrl);\n const frontendUrl = new URL(process.env.FRONTEND_URL || '');\n if (parsed.origin !== frontendUrl.origin) {\n throw new Error('Invalid return URL: must match frontend domain');\n }\n }\n\n // Create portal session\n const session = await stripe.billingPortal.sessions.create({\n customer: customerId,\n return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,\n });\n\n return {\n url: session.url,\n };\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["Stripe", "_stripe", "initStripe", "apiKey", "apiVersion", "STRIPE_API_VERSION_PIN", "Stripe", "__name", "getStripe", "STRIPE_SECRET_KEY", "stripe", "target", "prop", "validateStripeEnvironment", "cancelUserSubscription", "userId", "authProvider", "validateStripeEnvironment", "subscription", "subscriptionId", "handleError", "updatedSubscription", "stripe", "status", "updateUserSubscription", "__name", "changeUserPlan", "newPriceId", "billingConfigKey", "billingConfig", "billingItem", "currentSubscription", "createCustomerPortalSession", "returnUrl", "customerId", "parsed", "frontendUrl"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{a as g}from"./chunk-AYY7UXNI.js";var y=typeof process<"u"&&!!process.versions?.node,a=!1,i=null,c=!1;async function l(){if(!c)try{let e=process.env.SENTRY_DSN;if(e){let{init:r,captureException:n,captureMessage:t}=await import("@sentry/node");r({dsn:e,environment:"production"}),i={captureException:n,captureMessage:t},a=!0}}catch{a=!1}finally{c=!0}}g(l,"initializeSentry");var d=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.FATAL=4]="FATAL",o))(d||{}),f={debug(e,r){this.log(0,e,r)},info(e,r){this.log(1,e,r)},warn(e,r){this.log(2,e,r)},async error(e,r){if(this.log(3,e,r),c||await l(),a&&i)try{r?.error instanceof Error?i.captureException(r.error):i.captureMessage(e,"error")}catch(n){console.error("Sentry error:",n)}},async fatal(e,r){if(this.log(4,e,r),c||await l(),a&&i)try{r?.error instanceof Error?i.captureException(r.error):i.captureMessage(e,"fatal")}catch(n){console.error("Sentry error:",n)}},log(e,r,n){let t=new Date().toISOString(),R={level:e,message:r,timestamp:t,context:n,error:n?.error,metadata:{...y?{pid:process.pid,nodeVersion:process.version,platform:process.platform}:{},...n?.metadata}},o=d[e],s=n?` ${JSON.stringify(n)}`:"";switch(e){case 0:console.debug(`[${t}] [DEBUG] ${r}${s}`);break;case 1:console.info(`[${t}] [INFO] ${r}${s}`);break;case 2:console.warn(`[${t}] [WARN] ${r}${s}`);break;case 3:console.error(`[${t}] [ERROR] ${r}${s}`);break;case 4:console.error(`[${t}] [FATAL] ${r}${s}`);break}},isSentryEnabled(){return a},getLevel(){return 0}};export{f as a};
|
|
22
|
+
//# sourceMappingURL=chunk-PWAGW4R6.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/logger.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/logger.ts\n\n/**\n * @fileoverview Server-side logging utility with Sentry integration\n * @description Structured logging for server environments with Sentry integration\n *\n * Sentry Integration:\n * - Uses @sentry/node for backend error tracking\n * - Automatically detects if Sentry is installed\n * - Works with or without Sentry (graceful degradation)\n * - Consumer must install @sentry/node and set SENTRY_DSN env var\n *\n * Usage:\n * ```typescript\n * import { logger } from '../shared/logger.js';\n *\n * logger.info('Server started', { port: 3000 });\n * logger.error('Database connection failed', { error: err });\n * ```\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n// Node-only metadata (pid, version) is added when running on Node; Deno runtimes\n// (Supabase Edge) log without it. Server-only by package: @donotdev/functions is\n// never imported by client code, so no runtime browser check (Supabase Edge\n// defines `window`, which made such a check throw on every edge function).\nconst _isNodeEnv = typeof process !== 'undefined' && !!process.versions?.node;\n\nlet sentryEnabled = false;\nlet sentryClient: any = null;\n\n// Initialize Sentry lazily to avoid Firebase Functions issues\nlet sentryInitialized = false;\n\n/**\n * Initialize Sentry if not already done\n * Called lazily to avoid Firebase Functions issues\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nasync function initializeSentry(): Promise<void> {\n if (sentryInitialized) return;\n\n try {\n // Check if Sentry is available (consumer must install @sentry/node)\n const sentryDsn = process.env.SENTRY_DSN;\n if (sentryDsn) {\n // Dynamic import to avoid build errors if @sentry/node is not installed\n const { init, captureException, captureMessage } =\n await import('@sentry/node');\n\n init({\n dsn: sentryDsn,\n environment: process.env.NODE_ENV || 'development',\n });\n\n sentryClient = { captureException, captureMessage };\n sentryEnabled = true;\n }\n } catch (error) {\n // Sentry not available, continue without it\n sentryEnabled = false;\n } finally {\n sentryInitialized = true;\n }\n}\n\n/**\n * Log levels for structured logging\n */\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n FATAL = 4,\n}\n\n/**\n * Log entry interface for structured logging\n */\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: string;\n context?: Record<string, any>;\n error?: Error;\n metadata?: Record<string, any>;\n}\n\n/**\n * Server-side logger with Sentry integration\n *\n * Features:\n * - Structured logging with context\n * - Automatic Sentry error reporting\n * - Performance monitoring\n * - Request correlation\n *\n * @example\n * ```typescript\n * import { logger } from '../shared/logger.js';\n *\n * // Basic logging\n * logger.info('Server started', { port: 3000 });\n *\n * // Error logging with Sentry\n * logger.error('Database error', { error: err, query: 'SELECT * FROM users' });\n *\n * // Performance logging\n * logger.info('Request completed', {\n * duration: 150,\n * status: 200,\n * path: '/api/users'\n * });\n * ```\n */\nexport const logger = {\n /**\n * Log debug information\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n debug(message: string, context?: Record<string, any>): void {\n this.log(LogLevel.DEBUG, message, context);\n },\n\n /**\n * Log informational messages\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n info(message: string, context?: Record<string, any>): void {\n this.log(LogLevel.INFO, message, context);\n },\n\n /**\n * Log warning messages\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n warn(message: string, context?: Record<string, any>): void {\n this.log(LogLevel.WARN, message, context);\n },\n\n /**\n * Log error messages with Sentry integration\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async error(message: string, context?: Record<string, any>): Promise<void> {\n this.log(LogLevel.ERROR, message, context);\n\n // Initialize Sentry lazily if needed\n if (!sentryInitialized) {\n await initializeSentry();\n }\n\n // Send to Sentry if available\n if (sentryEnabled && sentryClient) {\n try {\n if (context?.error instanceof Error) {\n sentryClient.captureException(context.error);\n } else {\n sentryClient.captureMessage(message, 'error');\n }\n } catch (sentryError) {\n // Don't let Sentry errors break logging\n console.error('Sentry error:', sentryError);\n }\n }\n },\n\n /**\n * Log fatal errors with Sentry integration\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async fatal(message: string, context?: Record<string, any>): Promise<void> {\n this.log(LogLevel.FATAL, message, context);\n\n // Initialize Sentry lazily if needed\n if (!sentryInitialized) {\n await initializeSentry();\n }\n\n // Send to Sentry if available\n if (sentryEnabled && sentryClient) {\n try {\n if (context?.error instanceof Error) {\n sentryClient.captureException(context.error);\n } else {\n sentryClient.captureMessage(message, 'fatal');\n }\n } catch (sentryError) {\n // Don't let Sentry errors break logging\n console.error('Sentry error:', sentryError);\n }\n }\n },\n\n /**\n * Core logging method\n * @param level - Log level\n * @param message - Log message\n * @param context - Additional context data\n *\n * @security Callers MUST NOT pass secrets (tokens, passwords, API keys) in context. Context is logged in plaintext.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n log(level: LogLevel, message: string, context?: Record<string, any>): void {\n const timestamp = new Date().toISOString();\n const logEntry: LogEntry = {\n level,\n message,\n timestamp,\n context,\n error: context?.error,\n metadata: {\n ...(_isNodeEnv\n ? {\n pid: process.pid,\n nodeVersion: process.version,\n platform: process.platform,\n }\n : {}),\n ...context?.metadata,\n },\n };\n\n // Format log entry for console output\n const levelName = LogLevel[level];\n const contextStr = context ? ` ${JSON.stringify(context)}` : '';\n\n // Use appropriate console method based on level\n switch (level) {\n case LogLevel.DEBUG:\n console.debug(`[${timestamp}] [DEBUG] ${message}${contextStr}`);\n break;\n case LogLevel.INFO:\n console.info(`[${timestamp}] [INFO] ${message}${contextStr}`);\n break;\n case LogLevel.WARN:\n console.warn(`[${timestamp}] [WARN] ${message}${contextStr}`);\n break;\n case LogLevel.ERROR:\n console.error(`[${timestamp}] [ERROR] ${message}${contextStr}`);\n break;\n case LogLevel.FATAL:\n console.error(`[${timestamp}] [FATAL] ${message}${contextStr}`);\n break;\n }\n },\n\n /**\n * Check if Sentry is enabled\n * @returns True if Sentry is available and configured\n */\n isSentryEnabled(): boolean {\n return sentryEnabled;\n },\n\n /**\n * Get current log level (always DEBUG for server)\n * @returns Current log level\n */\n getLevel(): LogLevel {\n return LogLevel.DEBUG;\n },\n};\n\n/**\n * Create a child logger with additional context\n * @param context - Additional context to include in all logs\n * @returns Child logger instance\n */\nexport function createChildLogger(context: Record<string, any>) {\n return {\n debug: (message: string, additionalContext?: Record<string, any>) => {\n logger.debug(message, { ...context, ...additionalContext });\n },\n info: (message: string, additionalContext?: Record<string, any>) => {\n logger.info(message, { ...context, ...additionalContext });\n },\n warn: (message: string, additionalContext?: Record<string, any>) => {\n logger.warn(message, { ...context, ...additionalContext });\n },\n error: async (message: string, additionalContext?: Record<string, any>) => {\n await logger.error(message, { ...context, ...additionalContext });\n },\n fatal: async (message: string, additionalContext?: Record<string, any>) => {\n await logger.fatal(message, { ...context, ...additionalContext });\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["_isNodeEnv", "sentryEnabled", "sentryClient", "sentryInitialized", "initializeSentry", "sentryDsn", "init", "captureException", "captureMessage", "__name", "LogLevel", "logger", "message", "context", "sentryError", "level", "timestamp", "logEntry", "levelName", "contextStr"]
|
|
7
|
+
}
|
|
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{b as $,c as x,d as m}from"./chunk-TBEDQLOB.js";import{A as c,B as g,L as h,f as A,h as p,i as T,j as F,m as P,q as R,r as d,s as f,v as l,z as S}from"./chunk-TMHBP3HB.js";import{a as o}from"./chunk-AYY7UXNI.js";var N=/^[a-zA-Z0-9_.-]+$/;function a(e,t){if(!N.test(e))throw new Error(`Invalid ${t}: must contain only alphanumeric, hyphens, underscores, and dots`)}o(a,"validateGitHubName");var q=class{static{o(this,"GitHubApiService")}config;constructor(t){this.config={baseUrl:"https://api.github.com",...t}}async getCurrentUser(){return await this.request("/user")}async getUserRepositories(t){t&&a(t,"username");let r=t?`/users/${t}/repos`:"/user/repos";return await this.request(r)}async addCollaborator(t){a(t.owner,"owner"),a(t.repo,"repo"),a(t.username,"username");try{return await this.request(`/repos/${t.owner}/${t.repo}/collaborators/${t.username}`,{method:"PUT",body:JSON.stringify({permission:t.permission||"push"})}),!0}catch(r){return console.error("Failed to add collaborator:",r),!1}}async isCollaborator(t,r,n){a(t,"owner"),a(r,"repo"),a(n,"username");try{return await this.request(`/repos/${t}/${r}/collaborators/${n}`,{method:"GET"}),!0}catch(s){return s.message?.includes("404")||console.error("Failed to check collaborator status:",s),!1}}async removeCollaborator(t,r,n){a(t,"owner"),a(r,"repo"),a(n,"username");try{return await this.request(`/repos/${t}/${r}/collaborators/${n}`,{method:"DELETE"}),!0}catch(s){return console.error("Failed to remove collaborator:",s),!1}}async addTeamMember(t,r,n,s="member"){a(t,"org"),a(r,"teamSlug"),a(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"PUT",body:JSON.stringify({role:s})}),!0}catch(i){return console.error("Failed to add team member:",i),!1}}async removeTeamMember(t,r,n){a(t,"org"),a(r,"teamSlug"),a(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"DELETE"}),!0}catch(s){return console.error("Failed to remove team member:",s),!1}}async isTeamMember(t,r,n){a(t,"org"),a(r,"teamSlug"),a(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"GET"}),!0}catch(s){return s.message?.includes("404")||console.error("Failed to check team membership:",s),!1}}async request(t,r={}){let n=`${this.config.baseUrl}${t}`,s=await fetch(n,{...r,headers:{Authorization:`Bearer ${this.config.accessToken}`,Accept:"application/vnd.github.v3+json","User-Agent":"DoNotDev-Functions","Content-Type":"application/json",...r.headers}});if(!s.ok){let i=await s.json().catch(()=>({})),u={message:i.message||`HTTP ${s.status}: ${s.statusText}`,documentation_url:i.documentation_url,status:s.status};throw new Error(`GitHub API Error: ${u.message}`)}return s.json()}};function Y(e){return new q({accessToken:e})}o(Y,"createGitHubApiService");function U(e){if(e&&typeof e=="object"&&"visibility"in e)return e.visibility}o(U,"getFieldVisibility");function _(e,t,r,n=!0){return t==="hidden"?!1:t==="guest"?!0:t==="admin"||t==="technical"?r:t==="owner"?!1:t==="user"||t===void 0?n:!1}o(_,"isFieldVisible");function H(e,t){if(!e||typeof e!="object"||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let r=e.entries,n=[];for(let[s,i]of Object.entries(r)){let u=U(i);_(s,u,t)&&n.push(s)}return n}o(H,"getVisibleFields");function X(e,t,r){if(!e)return{};let n=H(t,r),s={};for(let i of n)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i]);return s}o(X,"filterVisibleFields");import{logger as V}from"firebase-functions/v2";var B={webhookEvent:d({id:c(l(),p(1,"Event ID is required")),type:c(l(),p(1,"Event type is required")),data:d({object:P()}),created:c(R(),T(0,"Valid timestamp required"))}),purchaseRequest:d({userId:c(l(),p(1,"User ID is required")),productType:c(l(),p(1,"Product type is required")),githubUsername:f(c(l(),F(/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,"Invalid GitHub username"))),sessionId:c(l(),p(1,"Session ID is required")),amount:f(c(R(),T(0,"Amount must be positive"))),currency:f(c(l(),A(3,"Currency must be 3 characters")))})};function ne(e){try{return{isValid:!0,data:S(B.webhookEvent,e),errors:[]}}catch(t){if(t&&typeof t=="object"&&"issues"in t&&(t instanceof Error&&t.name==="ValiError"||t.name==="ValiError")){let n=t.issues.map(s=>`${s.path?.map(i=>i.key).join(".")||""}: ${s.message}`);return V.warn("Webhook event validation failed",{errors:n,data:e}),{isValid:!1,errors:n}}return{isValid:!1,errors:["Unknown validation error"]}}}o(ne,"validateWebhookEvent");function se(e){try{return{isValid:!0,data:S(B.purchaseRequest,e),errors:[]}}catch(t){if(t&&typeof t=="object"&&"issues"in t&&(t instanceof Error&&t.name==="ValiError"||t.name==="ValiError")){let n=t.issues.map(s=>`${s.path?.map(i=>i.key).join(".")||""}: ${s.message}`);return V.warn("Purchase request validation failed",{errors:n,data:e}),{isValid:!1,errors:n}}return{isValid:!1,errors:["Unknown validation error"]}}}o(se,"validatePurchaseRequest");function oe(e){return/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/.test(e)}o(oe,"validateGitHubUsername");function ie(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}o(ie,"validateEmail");function ae(e){return e.startsWith("price_")&&e.length>6}o(ae,"validateStripePriceId");function ce(e){return e.startsWith("cs_")&&e.length>3}o(ce,"validateStripeSessionId");function ue(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}o(ue,"validateUrl");function le(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let s=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(s.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=s}return t}o(le,"validateMetadata");function y(e,t,r){let s=g(r||t,e);return s.success?{success:!0,data:s.output}:{success:!1,error:`Validation failed: ${s.issues.map(i=>i.message).join(", ")}`}}o(y,"validateRequestData");function k(e,t){return async(r,n)=>{let s=y(r.data,e,n);if(!s.success)throw new Error(s.error);return await t(r,s.data)}}o(k,"withSchemaValidation");function I(e,t){return async(r,n,s)=>{let i=y(r.body,e,s);return i.success?await t(r,n,i.data):n.status(400).json({error:i.error})}}o(I,"withVercelSchemaValidation");function de(e,t){let r=k(e,t);return{standard:o(n=>r(n),"standard"),withSchema:o((n,s)=>r(n,s),"withSchema")}}o(de,"createFirebaseFunction");function fe(e,t){return I(e,t)}o(fe,"createVercelFunction");import{onCall as M}from"firebase-functions/v2/https";function G(e,t,r){let n=k(t,r);return{onCall:M(e,async s=>await n(s)),withSchema:o(async(s,i)=>await n(s,i),"withSchema")}}o(G,"createFirebaseCallable");function be(e,t,r){let{onCall:n,withSchema:s}=G(e,t,r);return{[r.name||"mainFunction"]:n,[`${r.name||"mainFunction"}WithSchema`]:s}}o(be,"createFirebaseFunctionExports");function Se(e,t){return I(e,t)}o(Se,"createVercelHandler");function xe(e,t,r){return async(n,s,i)=>{if(n.method!==e)return s.status(405).json({error:"Method not allowed"});let u=y(n.body,t,i);return u.success?await r(n,s,u.data):s.status(400).json({error:u.error})}}o(xe,"createVercelApiHandler");function De(e){if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null&&"toDate"in e){let r=e;if(typeof r.toDate=="function")return r.toDate().toISOString()}if(typeof e=="string"){let r=new Date(e);if(isNaN(r.getTime()))throw new Error("Invalid date format");return r.toISOString()}let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Invalid date format");return t.toISOString()}o(De,"toISOString");function v(e,t){let r=new Date(e),n=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==n&&r.setDate(0),r}o(v,"addMonths");function O(e,t){let r=new Date(e),n=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==n&&r.setDate(0),r}o(O,"addYears");function Ae(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=v(t,1):e==="3months"?r=v(t,3):e==="6months"?r=v(t,6):e==="1year"?r=O(t,1):e==="2years"?r=O(t,2):r=v(t,1),r.toISOString()}o(Ae,"calculateSubscriptionEndDate");async function Ve(e,t){return[]}o(Ve,"findReferences");function z(e){return{price_pro_monthly:"pro",price_ai_monthly:"ai",price_pro_yearly:"pro",price_ai_yearly:"ai"}[e]||"free"}o(z,"getTierFromPriceId");async function L(e,t){if(!e)throw new Error("Firebase UID is required to cancel subscription");let r={tier:"free",subscriptionId:null,customerId:t.customer,status:"canceled",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{let n=x(),s=m(),u=(await n.getUser(e)).customClaims||{};await n.setCustomUserClaims(e,{...u,subscription:r}),await s.collection("subscriptions").doc(e).update({...r,updatedAt:new Date().toISOString()}),console.log(`Subscription canceled for user ${e}:`,{subscriptionId:t.id})}catch(n){throw console.error("Failed to cancel user subscription:",n),new Error("Failed to cancel user subscription")}}o(L,"cancelUserSubscription");async function W(e){try{return(await x().getUser(e)).customClaims?.subscription||null}catch(t){return console.error("Failed to get user subscription:",t),null}}o(W,"getUserSubscription");async function Ze(){return await $()}o(Ze,"initializeFirebaseAdmin");import{logger as b}from"firebase-functions/v2";async function Xe(e,t){let r=m();try{let s=await r.collection("idempotency").doc(`${t}_${e}`).get();if(s.exists){let i=s.data();return b.info("Operation already processed (idempotency)",{key:e,operation:t,processedAt:i.processedAt,processedBy:i.processedBy}),i.result}return null}catch(n){throw b.error("Idempotency check failed",{key:e,operation:t,error:n instanceof Error?n.message:String(n)}),new Error(`Idempotency check failed for ${t}/${e}: ${n instanceof Error?n.message:String(n)}`)}}o(Xe,"checkIdempotency");async function et(e,t,r,n){try{await m().collection("idempotency").doc(`${t}_${e}`).set({result:r,processedAt:new Date().toISOString(),processedBy:n}),b.info("Idempotency result stored",{key:e,operation:t,processedBy:n})}catch(s){b.error("Failed to store idempotency result",{key:e,operation:t,processedBy:n,error:s instanceof Error?s.message:String(s)})}}o(et,"storeIdempotencyResult");function st(){let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`)}o(st,"validateStripeEnvironment");function ot(e){try{return JSON.parse(e)}catch{return null}}o(ot,"safeJsonParse");function it(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}o(it,"validateCollectionName");function at(e,t){if(!e||typeof e!="object")throw new h("Invalid document data","invalid-argument");if(Array.isArray(e))throw new h("Document data cannot be an array","invalid-argument");if(t){let r=g(t,e);if(!r.success){let n=r.issues.map(s=>`${s.path?.map(i=>i.key).join(".")||"root"}: ${s.message}`).join("; ");throw new h(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:r.issues}})}}}o(at,"validateDocument");async function dt(e,t){let{code:r,redirectUri:n,codeVerifier:s}=e;return await t.exchangeCodeForToken({code:r,redirectUri:n,codeVerifier:s})}o(dt,"exchangeTokenAlgorithm");async function ht(e,t,r,n,s){return await s.grantAccess({userId:e,provider:t,accessToken:r,refreshToken:n})}o(ht,"grantAccessAlgorithm");function E(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:o(()=>new Date(e),"toDate"),toMillis:o(()=>e.getTime(),"toMillis"),isEqual:o(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:o(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}o(E,"createTimestamp");function Z(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string format: ${e}`);return E(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return E(e)}throw new Error("Date must be a string or Date object")}catch(t){throw new Error(`Failed to convert to timestamp: ${t instanceof Error?t.message:"Unknown error"}`)}}o(Z,"toTimestamp");function J(e){return e.toDate().toISOString()}o(J,"toISOString");function j(e){return e&&typeof e=="object"&&typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toDate=="function"&&typeof e.toMillis=="function"}o(j,"isTimestamp");function w(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"){let r=e,n=r.data();return{id:r.id,...w(n)}}if(Array.isArray(e))return e.map(r=>w(r));if(j(e))return J(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,s]of Object.entries(e))r[n]=w(s);return r}return e}o(w,"transformFirestoreData");function D(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>D(r,t));if(typeof e=="object"&&e!==null){let r={};for(let[n,s]of Object.entries(e))t.includes(n)||(s instanceof Date?r[n]=s.toISOString():r[n]=D(s,t));return r}return e instanceof Date?e.toISOString():e}o(D,"prepareForFirestore");export{q as a,Y as b,_ as c,H as d,X as e,B as f,ne as g,se as h,oe as i,ie as j,ae as k,ce as l,ue as m,le as n,y as o,k as p,I as q,de as r,fe as s,G as t,be as u,Se as v,xe as w,De as x,Ae as y,Ve as z,z as A,L as B,W as C,Ze as D,Xe as E,et as F,st as G,ot as H,it as I,at as J,dt as K,ht as L,E as M,Z as N,j as O,w as P,D as Q};
|
|
22
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
import{b as P,c as S,d as m}from"./chunk-CXBSROEW.js";import{A as c,B as g,L as y,f as E,h as p,i as T,j as F,m as $,q as R,r as d,s as f,v as l,z as x}from"./chunk-GYTCWMXV.js";import{a as o}from"./chunk-AYY7UXNI.js";var N=/^[a-zA-Z0-9_.-]+$/;function a(e,t){if(!N.test(e))throw new Error(`Invalid ${t}: must contain only alphanumeric, hyphens, underscores, and dots`)}o(a,"validateGitHubName");var q=class{static{o(this,"GitHubApiService")}config;constructor(t){this.config={baseUrl:"https://api.github.com",...t}}async getCurrentUser(){return await this.request("/user")}async getUserRepositories(t){t&&a(t,"username");let r=t?`/users/${t}/repos`:"/user/repos";return await this.request(r)}async addCollaborator(t){a(t.owner,"owner"),a(t.repo,"repo"),a(t.username,"username");try{return await this.request(`/repos/${t.owner}/${t.repo}/collaborators/${t.username}`,{method:"PUT",body:JSON.stringify({permission:t.permission||"push"})}),!0}catch(r){return console.error("Failed to add collaborator:",r),!1}}async isCollaborator(t,r,n){a(t,"owner"),a(r,"repo"),a(n,"username");try{return await this.request(`/repos/${t}/${r}/collaborators/${n}`,{method:"GET"}),!0}catch(s){return s.message?.includes("404")||console.error("Failed to check collaborator status:",s),!1}}async removeCollaborator(t,r,n){a(t,"owner"),a(r,"repo"),a(n,"username");try{return await this.request(`/repos/${t}/${r}/collaborators/${n}`,{method:"DELETE"}),!0}catch(s){return console.error("Failed to remove collaborator:",s),!1}}async addTeamMember(t,r,n,s="member"){a(t,"org"),a(r,"teamSlug"),a(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"PUT",body:JSON.stringify({role:s})}),!0}catch(i){return console.error("Failed to add team member:",i),!1}}async removeTeamMember(t,r,n){a(t,"org"),a(r,"teamSlug"),a(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"DELETE"}),!0}catch(s){return console.error("Failed to remove team member:",s),!1}}async isTeamMember(t,r,n){a(t,"org"),a(r,"teamSlug"),a(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"GET"}),!0}catch(s){return s.message?.includes("404")||console.error("Failed to check team membership:",s),!1}}async request(t,r={}){let n=`${this.config.baseUrl}${t}`,s=await fetch(n,{...r,headers:{Authorization:`Bearer ${this.config.accessToken}`,Accept:"application/vnd.github.v3+json","User-Agent":"DoNotDev-Functions","Content-Type":"application/json",...r.headers}});if(!s.ok){let i=await s.json().catch(()=>({})),u={message:i.message||`HTTP ${s.status}: ${s.statusText}`,documentation_url:i.documentation_url,status:s.status};throw new Error(`GitHub API Error: ${u.message}`)}return s.json()}};function Y(e){return new q({accessToken:e})}o(Y,"createGitHubApiService");function U(e){if(e&&typeof e=="object"&&"visibility"in e)return e.visibility}o(U,"getFieldVisibility");function _(e,t,r,n=!0){return t==="hidden"?!1:t==="guest"?!0:t==="admin"||t==="technical"?r:t==="owner"?!1:t==="user"||t===void 0?n:!1}o(_,"isFieldVisible");function H(e,t){if(!e||typeof e!="object"||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let r=e.entries,n=[];for(let[s,i]of Object.entries(r)){let u=U(i);_(s,u,t)&&n.push(s)}return n}o(H,"getVisibleFields");function X(e,t,r){if(!e)return{};let n=H(t,r),s={};for(let i of n)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i]);return s}o(X,"filterVisibleFields");import{logger as C}from"firebase-functions/v2";var B={webhookEvent:d({id:c(l(),p(1,"Event ID is required")),type:c(l(),p(1,"Event type is required")),data:d({object:$()}),created:c(R(),T(0,"Valid timestamp required"))}),purchaseRequest:d({userId:c(l(),p(1,"User ID is required")),productType:c(l(),p(1,"Product type is required")),githubUsername:f(c(l(),F(/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,"Invalid GitHub username"))),sessionId:c(l(),p(1,"Session ID is required")),amount:f(c(R(),T(0,"Amount must be positive"))),currency:f(c(l(),E(3,"Currency must be 3 characters")))})};function ne(e){try{return{isValid:!0,data:x(B.webhookEvent,e),errors:[]}}catch(t){if(t&&typeof t=="object"&&"issues"in t&&(t instanceof Error&&t.name==="ValiError"||t.name==="ValiError")){let n=t.issues.map(s=>`${s.path?.map(i=>i.key).join(".")||""}: ${s.message}`);return C.warn("Webhook event validation failed",{errors:n,data:e}),{isValid:!1,errors:n}}return{isValid:!1,errors:["Unknown validation error"]}}}o(ne,"validateWebhookEvent");function se(e){try{return{isValid:!0,data:x(B.purchaseRequest,e),errors:[]}}catch(t){if(t&&typeof t=="object"&&"issues"in t&&(t instanceof Error&&t.name==="ValiError"||t.name==="ValiError")){let n=t.issues.map(s=>`${s.path?.map(i=>i.key).join(".")||""}: ${s.message}`);return C.warn("Purchase request validation failed",{errors:n,data:e}),{isValid:!1,errors:n}}return{isValid:!1,errors:["Unknown validation error"]}}}o(se,"validatePurchaseRequest");function oe(e){return/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/.test(e)}o(oe,"validateGitHubUsername");function ie(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}o(ie,"validateEmail");function ae(e){return e.startsWith("price_")&&e.length>6}o(ae,"validateStripePriceId");function ce(e){return e.startsWith("cs_")&&e.length>3}o(ce,"validateStripeSessionId");function ue(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}o(ue,"validateUrl");function le(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let s=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(s.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=s}return t}o(le,"validateMetadata");function h(e,t,r){let s=g(r||t,e);return s.success?{success:!0,data:s.output}:{success:!1,error:`Validation failed: ${s.issues.map(i=>i.message).join(", ")}`}}o(h,"validateRequestData");function k(e,t){return async(r,n)=>{let s=h(r.data,e,n);if(!s.success)throw new Error(s.error);return await t(r,s.data)}}o(k,"withSchemaValidation");function I(e,t){return async(r,n,s)=>{let i=h(r.body,e,s);return i.success?await t(r,n,i.data):n.status(400).json({error:i.error})}}o(I,"withVercelSchemaValidation");function de(e,t){let r=k(e,t);return{standard:o(n=>r(n),"standard"),withSchema:o((n,s)=>r(n,s),"withSchema")}}o(de,"createFirebaseFunction");function fe(e,t){return I(e,t)}o(fe,"createVercelFunction");import{onCall as G}from"firebase-functions/v2/https";function M(e,t,r){let n=k(t,r);return{onCall:G(e,async s=>await n(s)),withSchema:o(async(s,i)=>await n(s,i),"withSchema")}}o(M,"createFirebaseCallable");function ve(e,t,r){let{onCall:n,withSchema:s}=M(e,t,r);return{[r.name||"mainFunction"]:n,[`${r.name||"mainFunction"}WithSchema`]:s}}o(ve,"createFirebaseFunctionExports");function xe(e,t){return I(e,t)}o(xe,"createVercelHandler");function Se(e,t,r){return async(n,s,i)=>{if(n.method!==e)return s.status(405).json({error:"Method not allowed"});let u=h(n.body,t,i);return u.success?await r(n,s,u.data):s.status(400).json({error:u.error})}}o(Se,"createVercelApiHandler");function Ae(e){if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null&&"toDate"in e){let r=e;if(typeof r.toDate=="function")return r.toDate().toISOString()}if(typeof e=="string"){let r=new Date(e);if(isNaN(r.getTime()))throw new Error("Invalid date format");return r.toISOString()}let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Invalid date format");return t.toISOString()}o(Ae,"toISOString");function b(e,t){let r=new Date(e),n=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==n&&r.setDate(0),r}o(b,"addMonths");function j(e,t){let r=new Date(e),n=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==n&&r.setDate(0),r}o(j,"addYears");function Ee(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=b(t,1):e==="3months"?r=b(t,3):e==="6months"?r=b(t,6):e==="1year"?r=j(t,1):e==="2years"?r=j(t,2):r=b(t,1),r.toISOString()}o(Ee,"calculateSubscriptionEndDate");async function Ce(e,t){return[]}o(Ce,"findReferences");function z(e){return{price_pro_monthly:"pro",price_ai_monthly:"ai",price_pro_yearly:"pro",price_ai_yearly:"ai"}[e]||"free"}o(z,"getTierFromPriceId");async function L(e,t){if(!e)throw new Error("Firebase UID is required to cancel subscription");let r={tier:"free",subscriptionId:null,customerId:t.customer,status:"canceled",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{let n=S(),s=m(),u=(await n.getUser(e)).customClaims||{};await n.setCustomUserClaims(e,{...u,subscription:r}),await s.collection("subscriptions").doc(e).update({...r,updatedAt:new Date().toISOString()}),console.log(`Subscription canceled for user ${e}:`,{subscriptionId:t.id})}catch(n){throw console.error("Failed to cancel user subscription:",n),new Error("Failed to cancel user subscription")}}o(L,"cancelUserSubscription");async function W(e){try{return(await S().getUser(e)).customClaims?.subscription||null}catch(t){return console.error("Failed to get user subscription:",t),null}}o(W,"getUserSubscription");async function Ze(){return await P()}o(Ze,"initializeFirebaseAdmin");import{logger as v}from"firebase-functions/v2";async function Xe(e,t){let r=m();try{let s=await r.collection("idempotency").doc(`${t}_${e}`).get();if(s.exists){let i=s.data();return v.info("Operation already processed (idempotency)",{key:e,operation:t,processedAt:i.processedAt,processedBy:i.processedBy}),i.result}return null}catch(n){throw v.error("Idempotency check failed",{key:e,operation:t,error:n instanceof Error?n.message:String(n)}),new Error(`Idempotency check failed for ${t}/${e}: ${n instanceof Error?n.message:String(n)}`)}}o(Xe,"checkIdempotency");async function et(e,t,r,n){try{await m().collection("idempotency").doc(`${t}_${e}`).set({result:r,processedAt:new Date().toISOString(),processedBy:n}),v.info("Idempotency result stored",{key:e,operation:t,processedBy:n})}catch(s){v.error("Failed to store idempotency result",{key:e,operation:t,processedBy:n,error:s instanceof Error?s.message:String(s)})}}o(et,"storeIdempotencyResult");function st(e){try{return JSON.parse(e)}catch{return null}}o(st,"safeJsonParse");function ot(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}o(ot,"validateCollectionName");function it(e,t){if(!e||typeof e!="object")throw new y("Invalid document data","invalid-argument");if(Array.isArray(e))throw new y("Document data cannot be an array","invalid-argument");if(t){let r=g(t,e);if(!r.success){let n=r.issues.map(s=>`${s.path?.map(i=>i.key).join(".")||"root"}: ${s.message}`).join("; ");throw new y(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:r.issues}})}}}o(it,"validateDocument");async function mt(e,t){let{code:r,redirectUri:n,codeVerifier:s}=e;return await t.exchangeCodeForToken({code:r,redirectUri:n,codeVerifier:s})}o(mt,"exchangeTokenAlgorithm");async function gt(e,t,r,n,s){return await s.grantAccess({userId:e,provider:t,accessToken:r,refreshToken:n})}o(gt,"grantAccessAlgorithm");function D(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:o(()=>new Date(e),"toDate"),toMillis:o(()=>e.getTime(),"toMillis"),isEqual:o(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:o(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}o(D,"createTimestamp");function Z(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string format: ${e}`);return D(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return D(e)}throw new Error("Date must be a string or Date object")}catch(t){throw new Error(`Failed to convert to timestamp: ${t instanceof Error?t.message:"Unknown error"}`)}}o(Z,"toTimestamp");function J(e){return e.toDate().toISOString()}o(J,"toISOString");function O(e){return e&&typeof e=="object"&&typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toDate=="function"&&typeof e.toMillis=="function"}o(O,"isTimestamp");function w(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"){let r=e,n=r.data();return{id:r.id,...w(n)}}if(Array.isArray(e))return e.map(r=>w(r));if(O(e))return J(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,s]of Object.entries(e))r[n]=w(s);return r}return e}o(w,"transformFirestoreData");function A(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>A(r,t));if(typeof e=="object"&&e!==null){let r={};for(let[n,s]of Object.entries(e))t.includes(n)||(s instanceof Date?r[n]=s.toISOString():r[n]=A(s,t));return r}return e instanceof Date?e.toISOString():e}o(A,"prepareForFirestore");export{q as a,Y as b,_ as c,H as d,X as e,B as f,ne as g,se as h,oe as i,ie as j,ae as k,ce as l,ue as m,le as n,h as o,k as p,I as q,de as r,fe as s,M as t,ve as u,xe as v,Se as w,Ae as x,Ee as y,Ce as z,z as A,L as B,W as C,Ze as D,Xe as E,et as F,st as G,ot as H,it as I,mt as J,gt as K,D as L,Z as M,O as N,w as O,A as P};
|
|
22
|
+
//# sourceMappingURL=chunk-US2VOP4S.js.map
|