@donotdev/functions 0.1.0 → 0.1.42
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/LICENSE.md +21 -242
- package/README.md +4 -4
- package/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +286 -0
- 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 +10 -13
- 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/bulk.d.ts +107 -0
- package/lib/firebase/crud/create.d.ts +1 -1
- 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 +1 -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 +3 -3
- package/lib/firebase/index.js.map +4 -4
- 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 +35 -0
- package/lib/shared/ai/costTracker.d.ts +20 -0
- package/lib/shared/ai/createAIHandler.d.ts +39 -0
- package/lib/shared/ai/createAIRoute.d.ts +20 -0
- package/lib/shared/ai/index.d.ts +6 -0
- package/lib/shared/ai/providers/anthropic.d.ts +12 -0
- package/lib/shared/ai/providers/google.d.ts +10 -0
- package/lib/shared/ai/providers/index.d.ts +23 -0
- package/lib/shared/ai/providers/openai.d.ts +10 -0
- package/lib/shared/ai/resolveModelTier.d.ts +14 -0
- package/lib/shared/ai/utils/parseSSE.d.ts +22 -0
- package/lib/shared/billing/createCheckout.d.ts +8 -2
- 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 +0 -0
- package/lib/shared/billing/index.d.ts +0 -0
- package/lib/shared/billing/webhookHandler.d.ts +0 -0
- package/lib/shared/crud/bulkCore.d.ts +211 -0
- package/lib/shared/crud/index.d.ts +13 -0
- package/lib/shared/email/createEmailRoute.d.ts +30 -0
- package/lib/shared/email/index.d.ts +3 -0
- package/lib/shared/email/provider.d.ts +30 -0
- package/lib/shared/email/resendProvider.d.ts +22 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +5 -0
- package/lib/shared/index.d.ts +3 -0
- package/lib/shared/index.js +4 -3
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +2 -0
- package/lib/shared/metadata.d.ts +6 -6
- package/lib/shared/oauth/exchangeToken.d.ts +1 -0
- package/lib/shared/oauth/grantAccess.d.ts +1 -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 +1 -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 -0
- 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 -0
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +30 -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 +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/baseFunction.d.ts +0 -0
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +1 -1
- 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 +1 -0
- package/lib/supabase/crud/bulk.d.ts +63 -0
- package/lib/supabase/crud/create.d.ts +2 -1
- package/lib/supabase/crud/delete.d.ts +1 -0
- package/lib/supabase/crud/get.d.ts +1 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/crud/list.d.ts +1 -0
- package/lib/supabase/crud/update.d.ts +1 -0
- package/lib/supabase/edgeFunction.d.ts +56 -0
- package/lib/supabase/email/createEmailFunction.d.ts +31 -0
- package/lib/supabase/helpers/authProvider.d.ts +0 -0
- package/lib/supabase/index.d.ts +8 -0
- package/lib/supabase/index.js +3 -2
- package/lib/supabase/index.js.map +4 -4
- 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 +29 -0
- package/lib/vercel/api/ai/index.d.ts +1 -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/bulk.d.ts +31 -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 +1 -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 +1 -0
- package/lib/vercel/api/index.js +3 -2
- package/lib/vercel/api/index.js.map +4 -4
- 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 +40 -7
- package/src/firebase/auth/getCustomClaims.ts +0 -0
- package/src/firebase/auth/getUserAuthStatus.ts +0 -0
- package/src/firebase/auth/index.ts +0 -0
- package/src/firebase/auth/removeCustomClaims.ts +0 -0
- package/src/firebase/auth/setCustomClaims.ts +0 -0
- package/src/firebase/baseFunction.ts +0 -0
- package/src/firebase/billing/cancelSubscription.ts +0 -0
- package/src/firebase/billing/changePlan.ts +0 -0
- package/src/firebase/billing/createCheckoutSession.ts +82 -186
- package/src/firebase/billing/createCustomerPortal.ts +0 -0
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.d.ts +0 -0
- package/src/firebase/billing/index.ts +0 -0
- package/src/firebase/billing/refreshSubscriptionStatus.ts +0 -0
- package/src/firebase/billing/webhookHandler.ts +0 -0
- package/src/firebase/config/constants.ts +0 -0
- package/src/firebase/config/index.ts +0 -0
- package/src/firebase/config/secrets.ts +0 -0
- package/src/firebase/crud/__tests__/bulk.test.ts +322 -0
- package/src/firebase/crud/aggregate.ts +0 -0
- package/src/firebase/crud/bulk.ts +272 -0
- package/src/firebase/crud/create.ts +20 -33
- package/src/firebase/crud/delete.ts +0 -0
- package/src/firebase/crud/get.ts +0 -0
- package/src/firebase/crud/index.ts +1 -0
- package/src/firebase/crud/list.ts +0 -0
- package/src/firebase/crud/update.ts +0 -0
- package/src/firebase/helpers/githubAccessHelper.ts +0 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +0 -0
- package/src/firebase/helpers/index.ts +0 -0
- package/src/firebase/index.d.ts +0 -0
- package/src/firebase/index.ts +0 -0
- package/src/firebase/oauth/disconnect.ts +0 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -4
- package/src/firebase/oauth/getConnections.ts +0 -0
- package/src/firebase/oauth/githubAccess.ts +0 -0
- package/src/firebase/oauth/index.ts +0 -0
- package/src/firebase/oauth/refreshToken.ts +4 -4
- package/src/firebase/registerCrudFunctions.ts +13 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +0 -0
- package/src/firebase/scheduled/index.ts +0 -0
- package/src/shared/__tests__/auth.test.ts +0 -0
- package/src/shared/__tests__/bulkCore.test.ts +487 -0
- package/src/shared/__tests__/errorHandling.test.ts +0 -0
- package/src/shared/__tests__/firebase.test.ts +9 -3
- package/src/shared/__tests__/idempotency.test.ts +0 -0
- package/src/shared/__tests__/internalValidation.test.ts +9 -3
- package/src/shared/__tests__/metadata.test.ts +10 -10
- package/src/shared/__tests__/rateLimiter.test.ts +0 -0
- package/src/shared/__tests__/schema.test.ts +0 -0
- package/src/shared/__tests__/schemaValidation.test.ts +0 -0
- package/src/shared/__tests__/subscription.test.ts +0 -0
- package/src/shared/__tests__/utils.test.ts +10 -4
- package/src/shared/__tests__/validation-env.test.ts +9 -3
- package/src/shared/__tests__/validation.test.ts +0 -0
- package/src/shared/ai/__tests__/costTracker.test.ts +133 -0
- package/src/shared/ai/classifyAIError.ts +178 -0
- package/src/shared/ai/costTracker.ts +51 -0
- package/src/shared/ai/createAIRoute.ts +400 -0
- package/src/shared/ai/index.ts +8 -0
- package/src/shared/ai/resolveModelTier.ts +61 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +0 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +0 -0
- package/src/shared/billing/createCheckout.ts +168 -8
- package/src/shared/billing/helpers/index.ts +0 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
- package/src/shared/billing/helpers/updateUserSubscription.ts +0 -0
- package/src/shared/billing/idempotency.ts +5 -0
- package/src/shared/billing/index.ts +0 -0
- package/src/shared/billing/webhookHandler.ts +0 -0
- package/src/shared/crud/bulkCore.ts +483 -0
- package/src/shared/crud/index.ts +23 -0
- package/src/shared/email/createEmailRoute.ts +81 -0
- package/src/shared/email/index.ts +5 -0
- package/src/shared/email/provider.ts +31 -0
- package/src/shared/email/resendProvider.ts +56 -0
- package/src/shared/errorHandling.ts +10 -4
- package/src/shared/firebase.ts +0 -0
- package/src/shared/github.ts +38 -0
- package/src/shared/index.d.ts +9 -0
- package/src/shared/index.ts +3 -0
- package/src/shared/logger.ts +2 -0
- package/src/shared/metadata.ts +6 -6
- package/src/shared/oauth/__tests__/exchangeToken.test.ts +0 -0
- package/src/shared/oauth/__tests__/grantAccess.test.ts +0 -0
- package/src/shared/oauth/exchangeToken.ts +1 -0
- package/src/shared/oauth/grantAccess.ts +1 -0
- package/src/shared/oauth/index.ts +0 -0
- package/src/shared/schema.ts +0 -0
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -0
- package/src/shared/utils/detectFirestore.ts +0 -0
- package/src/shared/utils/external/date.ts +0 -0
- package/src/shared/utils/external/index.ts +0 -0
- package/src/shared/utils/external/references.ts +0 -0
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +0 -0
- package/src/shared/utils/functionWrapper.ts +0 -0
- package/src/shared/utils/index.ts +0 -0
- package/src/shared/utils/internal/auth.ts +0 -0
- package/src/shared/utils/internal/firebase.ts +0 -0
- package/src/shared/utils/internal/idempotency.ts +1 -0
- package/src/shared/utils/internal/index.ts +0 -0
- package/src/shared/utils/internal/monitoring.ts +0 -0
- package/src/shared/utils/internal/rateLimiter.ts +6 -3
- package/src/shared/utils/internal/validation.ts +0 -0
- package/src/shared/utils/schemaValidation.ts +0 -0
- package/src/shared/utils/validation.ts +0 -0
- package/src/shared/utils/vercelHelpers.ts +0 -0
- package/src/shared/utils.ts +0 -0
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +330 -0
- package/src/supabase/ai/createAIFunction.ts +76 -0
- package/src/supabase/auth/deleteAccount.ts +0 -0
- package/src/supabase/auth/getCustomClaims.ts +0 -0
- package/src/supabase/auth/getUserAuthStatus.ts +0 -0
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +64 -5
- package/src/supabase/baseFunction.ts +26 -2
- package/src/supabase/billing/cancelSubscription.ts +0 -0
- package/src/supabase/billing/changePlan.ts +6 -1
- package/src/supabase/billing/createCheckoutSession.ts +16 -2
- package/src/supabase/billing/createCustomerPortal.ts +0 -0
- package/src/supabase/billing/refreshSubscriptionStatus.ts +0 -0
- package/src/supabase/crud/aggregate.ts +1 -0
- package/src/supabase/crud/bulk.ts +244 -0
- package/src/supabase/crud/create.ts +16 -14
- package/src/supabase/crud/delete.ts +1 -0
- package/src/supabase/crud/get.ts +1 -0
- package/src/supabase/crud/index.ts +2 -0
- package/src/supabase/crud/list.ts +1 -0
- package/src/supabase/crud/update.ts +1 -0
- package/src/supabase/edgeFunction.ts +196 -0
- package/src/supabase/email/createEmailFunction.ts +72 -0
- package/src/supabase/helpers/authProvider.ts +0 -0
- package/src/supabase/index.ts +21 -0
- package/src/supabase/oauth/disconnect.ts +1 -2
- package/src/supabase/oauth/exchangeToken.ts +39 -10
- package/src/supabase/oauth/getConnections.ts +1 -4
- package/src/supabase/oauth/index.ts +0 -0
- package/src/supabase/oauth/refreshToken.ts +6 -12
- package/src/supabase/registerCrudFunctions.ts +20 -20
- package/src/supabase/utils/idempotency.ts +6 -2
- package/src/supabase/utils/monitoring.ts +0 -0
- package/src/supabase/utils/rateLimiter.ts +0 -0
- package/src/vercel/__tests__/bulk.test.ts +301 -0
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +3 -0
- package/src/vercel/api/auth/get-custom-claims.ts +0 -0
- package/src/vercel/api/auth/get-user-auth-status.ts +0 -0
- package/src/vercel/api/auth/index.ts +0 -0
- package/src/vercel/api/auth/remove-custom-claims.ts +0 -0
- package/src/vercel/api/auth/set-custom-claims.ts +0 -0
- package/src/vercel/api/billing/cancel.ts +0 -0
- package/src/vercel/api/billing/change-plan.ts +0 -0
- package/src/vercel/api/billing/create-checkout-session.ts +31 -4
- package/src/vercel/api/billing/customer-portal.ts +0 -0
- package/src/vercel/api/billing/index.ts +0 -0
- package/src/vercel/api/billing/refresh-subscription-status.ts +0 -0
- package/src/vercel/api/billing/webhook-handler.ts +8 -1
- package/src/vercel/api/config/constants.ts +0 -0
- package/src/vercel/api/config/firebase-admin.ts +0 -0
- package/src/vercel/api/config/index.ts +0 -0
- package/src/vercel/api/crud/bulk.ts +216 -0
- package/src/vercel/api/crud/create.ts +10 -9
- package/src/vercel/api/crud/delete.ts +0 -0
- package/src/vercel/api/crud/get.ts +0 -0
- package/src/vercel/api/crud/index.ts +1 -0
- package/src/vercel/api/crud/list.ts +0 -0
- package/src/vercel/api/crud/update.ts +0 -0
- package/src/vercel/api/index.d.ts +0 -0
- package/src/vercel/api/index.ts +1 -0
- package/src/vercel/api/oauth/check-github-access.ts +0 -0
- package/src/vercel/api/oauth/exchange-token.ts +27 -1
- package/src/vercel/api/oauth/grant-github-access.ts +0 -0
- package/src/vercel/api/oauth/index.ts +0 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +0 -0
- package/src/vercel/api/utils/cors.ts +8 -0
- package/src/vercel/baseFunction.ts +0 -0
|
@@ -208,6 +208,15 @@ export async function createCustomerPortalSession(
|
|
|
208
208
|
throw handleError(new Error('No customer found'));
|
|
209
209
|
}
|
|
210
210
|
|
|
211
|
+
// Validate returnUrl domain
|
|
212
|
+
if (returnUrl) {
|
|
213
|
+
const parsed = new URL(returnUrl);
|
|
214
|
+
const frontendUrl = new URL(process.env.FRONTEND_URL || '');
|
|
215
|
+
if (parsed.origin !== frontendUrl.origin) {
|
|
216
|
+
throw new Error('Invalid return URL: must match frontend domain');
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
211
220
|
// Create portal session
|
|
212
221
|
const session = await stripe.billingPortal.sessions.create({
|
|
213
222
|
customer: customerId,
|
|
File without changes
|
|
@@ -57,6 +57,11 @@ class InMemoryIdempotency implements IdempotencyStore {
|
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* @limitation Not truly atomic for concurrent async operations within the same event loop tick.
|
|
62
|
+
* Two webhook retries arriving simultaneously could both pass the check.
|
|
63
|
+
* For production billing, use the Firestore/Supabase implementations which provide true atomicity.
|
|
64
|
+
*/
|
|
60
65
|
async checkAndReserve(eventId: string): Promise<boolean> {
|
|
61
66
|
if (this.store.has(eventId)) return true;
|
|
62
67
|
this.store.add(eventId);
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
// packages/functions/src/shared/crud/bulkCore.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Shared bulk CRUD orchestration core.
|
|
5
|
+
* @description Target-agnostic orchestrator that owns the bulk policy
|
|
6
|
+
* (wire validation, collision detection, per-bucket ACL, per-row schema
|
|
7
|
+
* validation, id minting, metadata stamping, audit, response validation).
|
|
8
|
+
* Target storage is delegated to a caller-supplied `transact` callback —
|
|
9
|
+
* this lets Firestore admin, Supabase RPC, Vercel firebase-admin, future
|
|
10
|
+
* GraphQL and future REST-CRUD server aids share one source of truth for
|
|
11
|
+
* correctness without pulling any platform-specific dependencies here.
|
|
12
|
+
*
|
|
13
|
+
* This module is server-only (`shared/` but never imported from `client/`
|
|
14
|
+
* or `common/`) and designed to stay portable across Node and Deno — it
|
|
15
|
+
* does not import `fs`, `net`, `firebase-admin`, `supabase-js`, etc.
|
|
16
|
+
*
|
|
17
|
+
* @version 0.1.0
|
|
18
|
+
* @since 0.7.0
|
|
19
|
+
* @author AMBROISE PARK Consulting
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import * as v from 'valibot';
|
|
23
|
+
|
|
24
|
+
import {
|
|
25
|
+
BulkCollisionError,
|
|
26
|
+
BulkRequestSchema,
|
|
27
|
+
BulkResponseSchema,
|
|
28
|
+
detectBulkCollisions,
|
|
29
|
+
DoNotDevError,
|
|
30
|
+
hasRoleAccess,
|
|
31
|
+
DEFAULT_STATUS_VALUE,
|
|
32
|
+
} from '@donotdev/core/server';
|
|
33
|
+
import type {
|
|
34
|
+
BulkRequest,
|
|
35
|
+
BulkResponse,
|
|
36
|
+
EntityAccessConfig,
|
|
37
|
+
UserRole,
|
|
38
|
+
} from '@donotdev/core/server';
|
|
39
|
+
|
|
40
|
+
// =============================================================================
|
|
41
|
+
// Public types
|
|
42
|
+
// =============================================================================
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Valibot schema alias accepted by {@link executeBulk}. Kept loose (`any` on
|
|
46
|
+
* the parsed output) so callers can pass entity-specific schemas generated by
|
|
47
|
+
* `createSchemas()` without fighting variance.
|
|
48
|
+
*/
|
|
49
|
+
export type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A prepared insert row passed to the caller-supplied `transact` callback.
|
|
53
|
+
* When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted
|
|
54
|
+
* value; otherwise it carries whatever id (if any) the client supplied and
|
|
55
|
+
* the storage layer is expected to mint its own.
|
|
56
|
+
*/
|
|
57
|
+
export interface PreparedInsert {
|
|
58
|
+
/** Minted insert id, or the empty string when the target mints its own. */
|
|
59
|
+
id: string;
|
|
60
|
+
/** Fully stamped row ready for storage. */
|
|
61
|
+
row: Record<string, unknown>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A prepared update passed to `transact`.
|
|
66
|
+
*/
|
|
67
|
+
export interface PreparedUpdate {
|
|
68
|
+
/** Target row id. */
|
|
69
|
+
id: string;
|
|
70
|
+
/** Fully stamped patch ready for storage. */
|
|
71
|
+
patch: Record<string, unknown>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Payload handed to the caller-supplied `transact` callback. All three
|
|
76
|
+
* arrays preserve input order and only include non-empty buckets' work.
|
|
77
|
+
*/
|
|
78
|
+
export interface PreparedBulk {
|
|
79
|
+
inserts: PreparedInsert[];
|
|
80
|
+
updates: PreparedUpdate[];
|
|
81
|
+
deletes: string[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Parameters for {@link executeBulk}.
|
|
86
|
+
*
|
|
87
|
+
* @template TRow - Row type recorded for documentation; runtime is opaque.
|
|
88
|
+
*/
|
|
89
|
+
export interface ExecuteBulkParams<TRow = unknown> {
|
|
90
|
+
/** Collection / table name. Passed through to audit + transact as metadata. */
|
|
91
|
+
collection: string;
|
|
92
|
+
/** Raw wire payload to orchestrate. Parsed with {@link BulkRequestSchema}. */
|
|
93
|
+
ops: BulkRequest;
|
|
94
|
+
/** Valibot schema validating each insert row. */
|
|
95
|
+
createSchema: BulkRowSchema;
|
|
96
|
+
/** Valibot schema validating each insert row when status === 'draft'. */
|
|
97
|
+
draftCreateSchema?: BulkRowSchema;
|
|
98
|
+
/** Valibot schema validating each update patch. */
|
|
99
|
+
updateSchema: BulkRowSchema;
|
|
100
|
+
/** Per-bucket required roles. Missing entries are treated as "no bucket allowed". */
|
|
101
|
+
access: EntityAccessConfig;
|
|
102
|
+
/** Authenticated caller id (for metadata + audit). */
|
|
103
|
+
uid: string;
|
|
104
|
+
/** Caller's role (for per-bucket ACL). */
|
|
105
|
+
userRole: UserRole;
|
|
106
|
+
/**
|
|
107
|
+
* Target-specific storage. Invoked exactly once when the bulk carries at
|
|
108
|
+
* least one op. Must run all three buckets inside one atomic transaction
|
|
109
|
+
* (writeBatch, runTransaction, Postgres RPC wrapping BEGIN/COMMIT, etc.)
|
|
110
|
+
* and return ids per bucket in input order.
|
|
111
|
+
*
|
|
112
|
+
* The returned shape is validated against `BulkResponseSchema` before
|
|
113
|
+
* being returned to the caller.
|
|
114
|
+
*/
|
|
115
|
+
transact: (prepared: PreparedBulk) => Promise<BulkResponse>;
|
|
116
|
+
/**
|
|
117
|
+
* Optional id minting. When provided, every insert is stamped with a
|
|
118
|
+
* freshly-minted id before `transact` runs. When omitted, `id` on each
|
|
119
|
+
* {@link PreparedInsert} is the empty string and the storage layer is
|
|
120
|
+
* expected to mint its own ids (Supabase RPC, GraphQL server, etc.).
|
|
121
|
+
*/
|
|
122
|
+
mintInsertId?: () => string;
|
|
123
|
+
/**
|
|
124
|
+
* Optional hook to stamp platform-specific metadata on every insert row
|
|
125
|
+
* (timestamps, createdById, defaults, field-name mapping). Called once per
|
|
126
|
+
* insert row, in input order.
|
|
127
|
+
*/
|
|
128
|
+
stampInsertMetadata?: (
|
|
129
|
+
row: Record<string, unknown>,
|
|
130
|
+
uid: string
|
|
131
|
+
) => Record<string, unknown>;
|
|
132
|
+
/**
|
|
133
|
+
* Optional hook to stamp platform-specific metadata on every update patch.
|
|
134
|
+
*/
|
|
135
|
+
stampUpdateMetadata?: (
|
|
136
|
+
patch: Record<string, unknown>,
|
|
137
|
+
uid: string
|
|
138
|
+
) => Record<string, unknown>;
|
|
139
|
+
/**
|
|
140
|
+
* Optional audit hook. Fires exactly once when `transact` succeeds, with the
|
|
141
|
+
* three op counts. Never fires for empty bulks or rejected validations —
|
|
142
|
+
* matches the "one audit entry" contract from `BULK_CRUD_TODO.md` §4.
|
|
143
|
+
*/
|
|
144
|
+
audit?: (
|
|
145
|
+
event: string,
|
|
146
|
+
payload: {
|
|
147
|
+
counts: { inserts: number; updates: number; deletes: number };
|
|
148
|
+
}
|
|
149
|
+
) => void;
|
|
150
|
+
/**
|
|
151
|
+
* Optional rate-limit bookkeeping key. `executeBulk` does NOT perform
|
|
152
|
+
* rate-limit enforcement itself — the surrounding base-function wrapper
|
|
153
|
+
* already charges one hit at entry. This field is forwarded to `audit()`
|
|
154
|
+
* callers that want to correlate telemetry.
|
|
155
|
+
*/
|
|
156
|
+
rateLimitKey?: string;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// =============================================================================
|
|
160
|
+
// Core orchestrator
|
|
161
|
+
// =============================================================================
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Empty response returned for a no-op bulk. Frozen so accidental mutation
|
|
165
|
+
* from a caller blows up at dev time instead of poisoning the next call.
|
|
166
|
+
*/
|
|
167
|
+
const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
|
|
168
|
+
insertedIds: [],
|
|
169
|
+
updatedIds: [],
|
|
170
|
+
deletedIds: [],
|
|
171
|
+
}) as BulkResponse;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Run a bulk CRUD operation against a caller-supplied storage target.
|
|
175
|
+
*
|
|
176
|
+
* **Order of operations** (every step fails loud — no fallbacks, no partial
|
|
177
|
+
* writes):
|
|
178
|
+
*
|
|
179
|
+
* 1. Parse `ops` with {@link BulkRequestSchema}. Invalid shape → throws.
|
|
180
|
+
* 2. Collision detection via {@link detectBulkCollisions}. Collision →
|
|
181
|
+
* throws {@link BulkCollisionError}.
|
|
182
|
+
* 3. Empty short-circuit — if no op carries work, returns a zeroed
|
|
183
|
+
* {@link BulkResponse} without invoking `transact` or `audit`.
|
|
184
|
+
* 4. Per-bucket ACL — for each populated bucket, asserts the caller's role
|
|
185
|
+
* clears the corresponding `access.{create|update|delete}`. A missing
|
|
186
|
+
* role on a populated bucket is a configuration error and is rejected.
|
|
187
|
+
* 5. Per-row validation — inserts against `createSchema`, updates against
|
|
188
|
+
* `updateSchema`. The first failure throws a `DoNotDevError` prefixed
|
|
189
|
+
* with `inserts[i]` or `updates[i]` so callers can pinpoint the row.
|
|
190
|
+
* 6. Id minting — if `mintInsertId` is supplied, every insert gets a fresh
|
|
191
|
+
* id stamped onto its {@link PreparedInsert}. Otherwise `id` is `""` and
|
|
192
|
+
* the storage layer mints its own.
|
|
193
|
+
* 7. Metadata stamping — `stampInsertMetadata` / `stampUpdateMetadata` run
|
|
194
|
+
* per row / per patch if provided.
|
|
195
|
+
* 8. `transact(prepared)` runs exactly once. Must be atomic. Throws
|
|
196
|
+
* propagate unchanged so the caller's error handler can classify them.
|
|
197
|
+
* 9. Response-shape validation via {@link BulkResponseSchema}. A non-conforming
|
|
198
|
+
* target response throws `DoNotDevError(internal)`.
|
|
199
|
+
* 10. `audit()` fires once with the three op counts.
|
|
200
|
+
*
|
|
201
|
+
* **Not this function's job:** rate-limiting, authentication, HTTP status
|
|
202
|
+
* mapping, target-specific connection pooling, retry policy. All of those
|
|
203
|
+
* belong to the surrounding handler wrapper.
|
|
204
|
+
*
|
|
205
|
+
* @template TRow - Row type (documentation only).
|
|
206
|
+
* @param params - See {@link ExecuteBulkParams}.
|
|
207
|
+
* @returns The validated {@link BulkResponse} from the target.
|
|
208
|
+
*
|
|
209
|
+
* @throws {BulkCollisionError} When the payload contains the same id in
|
|
210
|
+
* two mutually-exclusive buckets.
|
|
211
|
+
* @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row
|
|
212
|
+
* validation failure, or collision (wrapped for callers that only rethrow
|
|
213
|
+
* `DoNotDevError`).
|
|
214
|
+
* @throws {DoNotDevError} `permission-denied` when the caller's role cannot
|
|
215
|
+
* satisfy a populated bucket's access requirement.
|
|
216
|
+
* @throws {DoNotDevError} `internal` when the `transact` return value fails
|
|
217
|
+
* {@link BulkResponseSchema}.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```typescript
|
|
221
|
+
* import { executeBulk } from '@donotdev/functions/shared';
|
|
222
|
+
* import { BulkResponseSchema } from '@donotdev/core/server';
|
|
223
|
+
*
|
|
224
|
+
* const response = await executeBulk({
|
|
225
|
+
* collection: 'events',
|
|
226
|
+
* ops: req.body,
|
|
227
|
+
* createSchema,
|
|
228
|
+
* updateSchema,
|
|
229
|
+
* access,
|
|
230
|
+
* uid,
|
|
231
|
+
* userRole,
|
|
232
|
+
* mintInsertId: () => crypto.randomUUID(),
|
|
233
|
+
* stampInsertMetadata: (row, uid) => ({
|
|
234
|
+
* ...row,
|
|
235
|
+
* createdById: uid,
|
|
236
|
+
* createdAt: new Date().toISOString(),
|
|
237
|
+
* }),
|
|
238
|
+
* transact: async ({ inserts, updates, deletes }) => {
|
|
239
|
+
* return db.runTransaction(async (tx) => {
|
|
240
|
+
* for (const { id, row } of inserts) tx.set(col.doc(id), row);
|
|
241
|
+
* for (const { id, patch } of updates) tx.update(col.doc(id), patch);
|
|
242
|
+
* for (const id of deletes) tx.delete(col.doc(id));
|
|
243
|
+
* return {
|
|
244
|
+
* insertedIds: inserts.map((i) => i.id),
|
|
245
|
+
* updatedIds: updates.map((u) => u.id),
|
|
246
|
+
* deletedIds: deletes,
|
|
247
|
+
* };
|
|
248
|
+
* });
|
|
249
|
+
* },
|
|
250
|
+
* audit: (event, { counts }) => logger.info(event, counts),
|
|
251
|
+
* });
|
|
252
|
+
* ```
|
|
253
|
+
*
|
|
254
|
+
* @version 0.1.0
|
|
255
|
+
* @since 0.7.0
|
|
256
|
+
* @author AMBROISE PARK Consulting
|
|
257
|
+
*/
|
|
258
|
+
export async function executeBulk<TRow = unknown>(
|
|
259
|
+
params: ExecuteBulkParams<TRow>
|
|
260
|
+
): Promise<BulkResponse> {
|
|
261
|
+
const {
|
|
262
|
+
collection,
|
|
263
|
+
ops,
|
|
264
|
+
createSchema,
|
|
265
|
+
draftCreateSchema,
|
|
266
|
+
updateSchema,
|
|
267
|
+
access,
|
|
268
|
+
uid,
|
|
269
|
+
userRole,
|
|
270
|
+
transact,
|
|
271
|
+
mintInsertId,
|
|
272
|
+
stampInsertMetadata,
|
|
273
|
+
stampUpdateMetadata,
|
|
274
|
+
audit,
|
|
275
|
+
} = params;
|
|
276
|
+
|
|
277
|
+
// 1. Wire-schema validation. Guarantees the three buckets are arrays of
|
|
278
|
+
// the right shape; per-field entity validation happens in step 5.
|
|
279
|
+
const parsed = v.safeParse(BulkRequestSchema, ops);
|
|
280
|
+
if (!parsed.success) {
|
|
281
|
+
const messages = parsed.issues
|
|
282
|
+
.map(
|
|
283
|
+
(issue) =>
|
|
284
|
+
`${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
|
|
285
|
+
)
|
|
286
|
+
.join('; ');
|
|
287
|
+
throw new DoNotDevError(
|
|
288
|
+
`Bulk payload validation failed: ${messages}`,
|
|
289
|
+
'invalid-argument',
|
|
290
|
+
{ details: { validationErrors: parsed.issues } }
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
const request: BulkRequest = parsed.output;
|
|
294
|
+
|
|
295
|
+
const inserts = request.inserts ?? [];
|
|
296
|
+
const updates = request.updates ?? [];
|
|
297
|
+
const deletes = request.deletes ?? [];
|
|
298
|
+
|
|
299
|
+
// 2. Collision detection. Rejects ambiguous intents BEFORE any further
|
|
300
|
+
// work so a rate-limit hit + HTTP round-trip never buys a partial
|
|
301
|
+
// validation pass only to fail later.
|
|
302
|
+
const collision = detectBulkCollisions(request);
|
|
303
|
+
if (collision.where !== null) {
|
|
304
|
+
throw new BulkCollisionError(collision.collisions, collision.where);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// 3. Empty bulk short-circuit. Per `BULK_CRUD_TODO.md` §8 this never
|
|
308
|
+
// touches the storage layer, never fires audit, and returns a frozen
|
|
309
|
+
// empty response shared across calls (safe — consumers never mutate).
|
|
310
|
+
if (inserts.length === 0 && updates.length === 0 && deletes.length === 0) {
|
|
311
|
+
return EMPTY_BULK_RESPONSE;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// 4. Per-bucket ACL. The surrounding base-function wrapper already cleared
|
|
315
|
+
// the weakest role; we re-check each populated bucket so mixed-ACL
|
|
316
|
+
// entities reject precisely. A populated bucket with no configured
|
|
317
|
+
// role is a config error — fail loud rather than silently allow.
|
|
318
|
+
if (inserts.length > 0) {
|
|
319
|
+
if (!access.create) {
|
|
320
|
+
throw new DoNotDevError(
|
|
321
|
+
`Bulk insert requested on ${collection} but no create role is configured`,
|
|
322
|
+
'permission-denied'
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
if (!hasRoleAccess(userRole, access.create)) {
|
|
326
|
+
throw new DoNotDevError(
|
|
327
|
+
`Access denied for bulk insert on ${collection}. Required: ${access.create}, your role: ${userRole}`,
|
|
328
|
+
'permission-denied'
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (updates.length > 0) {
|
|
333
|
+
if (!access.update) {
|
|
334
|
+
throw new DoNotDevError(
|
|
335
|
+
`Bulk update requested on ${collection} but no update role is configured`,
|
|
336
|
+
'permission-denied'
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
if (!hasRoleAccess(userRole, access.update)) {
|
|
340
|
+
throw new DoNotDevError(
|
|
341
|
+
`Access denied for bulk update on ${collection}. Required: ${access.update}, your role: ${userRole}`,
|
|
342
|
+
'permission-denied'
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (deletes.length > 0) {
|
|
347
|
+
if (!access.delete) {
|
|
348
|
+
throw new DoNotDevError(
|
|
349
|
+
`Bulk delete requested on ${collection} but no delete role is configured`,
|
|
350
|
+
'permission-denied'
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
if (!hasRoleAccess(userRole, access.delete)) {
|
|
354
|
+
throw new DoNotDevError(
|
|
355
|
+
`Access denied for bulk delete on ${collection}. Required: ${access.delete}, your role: ${userRole}`,
|
|
356
|
+
'permission-denied'
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// 5. Per-row validation. First failure wins — prefixed with its bucket
|
|
362
|
+
// index so callers can point at the offending row.
|
|
363
|
+
for (let i = 0; i < inserts.length; i++) {
|
|
364
|
+
const row = inserts[i]!;
|
|
365
|
+
const rowObj = row as unknown as Record<string, unknown>;
|
|
366
|
+
const status =
|
|
367
|
+
(rowObj.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
|
|
368
|
+
const isDraft = status === 'draft';
|
|
369
|
+
const schemaToUse =
|
|
370
|
+
isDraft && draftCreateSchema ? draftCreateSchema : createSchema;
|
|
371
|
+
// Only inject default `status` when validating against the draft schema.
|
|
372
|
+
// This avoids breaking createSchema-only tests/entities that don't define
|
|
373
|
+
// `status` in their schema shape (valibot's `v.object` is strict by
|
|
374
|
+
// default).
|
|
375
|
+
const payloadForValidation =
|
|
376
|
+
isDraft && draftCreateSchema ? { ...rowObj, status } : rowObj;
|
|
377
|
+
validateRow(payloadForValidation, schemaToUse, `inserts[${i}]`);
|
|
378
|
+
}
|
|
379
|
+
for (let i = 0; i < updates.length; i++) {
|
|
380
|
+
validateRow(updates[i]!.patch, updateSchema, `updates[${i}]`);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// 6. Id minting (if provided). Minting at this layer means `transact`
|
|
384
|
+
// receives stable ids — crucial for Firestore's retry-able transaction
|
|
385
|
+
// callbacks where the callback body may run more than once.
|
|
386
|
+
const preparedInserts: PreparedInsert[] = inserts.map((row) => {
|
|
387
|
+
const rowRecord = row as unknown as Record<string, unknown>;
|
|
388
|
+
// Always ensure status is present for storage + downstream schema
|
|
389
|
+
// stamping. Validation may have used `draftCreateSchema` to relax
|
|
390
|
+
// required-field enforcement, but storage should still persist a
|
|
391
|
+
// concrete status value.
|
|
392
|
+
const status =
|
|
393
|
+
(rowRecord.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
|
|
394
|
+
const id = mintInsertId ? mintInsertId() : '';
|
|
395
|
+
const stamped = stampInsertMetadata
|
|
396
|
+
? stampInsertMetadata({ ...rowRecord, status }, uid)
|
|
397
|
+
: ({ ...rowRecord, status } as Record<string, unknown>);
|
|
398
|
+
return { id, row: stamped };
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
// 7. Update metadata stamping.
|
|
402
|
+
const preparedUpdates: PreparedUpdate[] = updates.map((u) => ({
|
|
403
|
+
id: u.id,
|
|
404
|
+
patch: stampUpdateMetadata
|
|
405
|
+
? stampUpdateMetadata(u.patch as Record<string, unknown>, uid)
|
|
406
|
+
: (u.patch as Record<string, unknown>),
|
|
407
|
+
}));
|
|
408
|
+
|
|
409
|
+
// 8. Atomic dispatch. Propagates any `transact` error verbatim — the
|
|
410
|
+
// surrounding handler wrapper classifies into HTTP / callable codes.
|
|
411
|
+
const raw = await transact({
|
|
412
|
+
inserts: preparedInserts,
|
|
413
|
+
updates: preparedUpdates,
|
|
414
|
+
deletes: [...deletes],
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// 9. Response-shape validation at the wire boundary. Drift between a
|
|
418
|
+
// target's return shape and `BulkResponseSchema` would silently corrupt
|
|
419
|
+
// clients that zip ids back onto optimistic entries — fail loud.
|
|
420
|
+
const responseParse = v.safeParse(BulkResponseSchema, raw);
|
|
421
|
+
if (!responseParse.success) {
|
|
422
|
+
throw new DoNotDevError(
|
|
423
|
+
`Bulk transact() returned an unexpected shape for ${collection}`,
|
|
424
|
+
'internal'
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// 10. One audit entry, counts only (never row ids — anomaly detection
|
|
429
|
+
// fires on the bulk count per contract §4).
|
|
430
|
+
if (audit) {
|
|
431
|
+
audit(`crud.bulk.${collection}`, {
|
|
432
|
+
counts: {
|
|
433
|
+
inserts: preparedInserts.length,
|
|
434
|
+
updates: preparedUpdates.length,
|
|
435
|
+
deletes: deletes.length,
|
|
436
|
+
},
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return responseParse.output;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// =============================================================================
|
|
444
|
+
// Internal helpers
|
|
445
|
+
// =============================================================================
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Validate a row against a Valibot schema and rethrow a `DoNotDevError`
|
|
449
|
+
* prefixed with the bucket position so callers can point at the offending
|
|
450
|
+
* row. Keeps the hot path free of try/catch overhead when no schema is
|
|
451
|
+
* supplied.
|
|
452
|
+
*
|
|
453
|
+
* @param value - Row or patch to validate.
|
|
454
|
+
* @param schema - Valibot schema.
|
|
455
|
+
* @param locator - Human-readable pointer such as `inserts[2]`.
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* ```typescript
|
|
459
|
+
* validateRow(inserts[i], createSchema, `inserts[${i}]`);
|
|
460
|
+
* ```
|
|
461
|
+
*
|
|
462
|
+
* @internal
|
|
463
|
+
*/
|
|
464
|
+
function validateRow(
|
|
465
|
+
value: unknown,
|
|
466
|
+
schema: BulkRowSchema,
|
|
467
|
+
locator: string
|
|
468
|
+
): void {
|
|
469
|
+
const parsed = v.safeParse(schema, value);
|
|
470
|
+
if (parsed.success) return;
|
|
471
|
+
|
|
472
|
+
const messages = parsed.issues
|
|
473
|
+
.map(
|
|
474
|
+
(issue) =>
|
|
475
|
+
`${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
|
|
476
|
+
)
|
|
477
|
+
.join('; ');
|
|
478
|
+
throw new DoNotDevError(
|
|
479
|
+
`Validation failed on ${locator}: ${messages}`,
|
|
480
|
+
'invalid-argument',
|
|
481
|
+
{ details: { validationErrors: parsed.issues } }
|
|
482
|
+
);
|
|
483
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// packages/functions/src/shared/crud/index.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Shared CRUD orchestration primitives.
|
|
5
|
+
* @description Barrel for the target-agnostic CRUD cores that Firestore,
|
|
6
|
+
* Supabase, Vercel, GraphQL and REST-CRUD server aids all consume.
|
|
7
|
+
* Exported from `@donotdev/functions/shared` (and the root entry) so
|
|
8
|
+
* out-of-package consumers can build their own adapters without pulling
|
|
9
|
+
* a target-specific SDK.
|
|
10
|
+
*
|
|
11
|
+
* @version 0.1.0
|
|
12
|
+
* @since 0.7.0
|
|
13
|
+
* @author AMBROISE PARK Consulting
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
executeBulk,
|
|
18
|
+
type ExecuteBulkParams,
|
|
19
|
+
type PreparedBulk,
|
|
20
|
+
type PreparedInsert,
|
|
21
|
+
type PreparedUpdate,
|
|
22
|
+
type BulkRowSchema,
|
|
23
|
+
} from './bulkCore.js';
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// packages/functions/src/shared/email/createEmailRoute.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Email Route Handler
|
|
5
|
+
* @description Platform-agnostic handler for email send requests.
|
|
6
|
+
* Validates request, resolves template, renders with locale, sends via provider.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
EmailRouteConfig,
|
|
15
|
+
SendEmailRequest,
|
|
16
|
+
SendEmailResponse,
|
|
17
|
+
} from '@donotdev/core/server';
|
|
18
|
+
import { validateSendEmailRequest } from '@donotdev/core/server';
|
|
19
|
+
|
|
20
|
+
import type { EmailProviderAdapter } from './provider.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Handle an email send request.
|
|
24
|
+
* Validates input, resolves the template from the registry, renders with locale, and sends.
|
|
25
|
+
*
|
|
26
|
+
* @param request - Email send request (templateId, to, data, locale)
|
|
27
|
+
* @param config - Email route configuration (provider, templates, defaultFrom)
|
|
28
|
+
* @param provider - Email provider adapter (Resend, etc.)
|
|
29
|
+
* @returns Send result with success status and messageId
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```typescript
|
|
33
|
+
* const result = await handleEmailRequest(
|
|
34
|
+
* { templateId: 'order-confirmation', to: 'user@example.com', data: { orderId: '123' }, locale: 'fr' },
|
|
35
|
+
* emailConfig,
|
|
36
|
+
* resendProvider
|
|
37
|
+
* );
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export async function handleEmailRequest(
|
|
41
|
+
request: SendEmailRequest,
|
|
42
|
+
config: EmailRouteConfig,
|
|
43
|
+
provider: EmailProviderAdapter
|
|
44
|
+
): Promise<SendEmailResponse> {
|
|
45
|
+
// Validate request
|
|
46
|
+
const validation = validateSendEmailRequest(request);
|
|
47
|
+
if (!validation.success) {
|
|
48
|
+
return {
|
|
49
|
+
success: false,
|
|
50
|
+
error: `Invalid email request: ${validation.issues?.map((i) => i.message).join(', ')}`,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Resolve template
|
|
55
|
+
const template = config.templates[request.templateId];
|
|
56
|
+
if (!template) {
|
|
57
|
+
return {
|
|
58
|
+
success: false,
|
|
59
|
+
error: `Template not found: ${request.templateId}`,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Render template with locale
|
|
64
|
+
const locale = request.locale || 'fr';
|
|
65
|
+
const subject = template.subject(request.data as any, locale);
|
|
66
|
+
const html = template.html(request.data as any, locale);
|
|
67
|
+
|
|
68
|
+
// Send via provider
|
|
69
|
+
const result = await provider.send({
|
|
70
|
+
from: request.from || config.defaultFrom,
|
|
71
|
+
to: request.to,
|
|
72
|
+
subject,
|
|
73
|
+
html,
|
|
74
|
+
replyTo: request.replyTo || config.replyTo,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
success: true,
|
|
79
|
+
messageId: result.messageId,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// packages/functions/src/shared/email/provider.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Email Provider Adapter Interface
|
|
5
|
+
* @description Abstract interface for email sending. Providers implement this.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @since 0.1.0
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Email provider adapter interface.
|
|
14
|
+
* Each provider (Resend, SES, etc.) implements this single method.
|
|
15
|
+
*/
|
|
16
|
+
export interface EmailProviderAdapter {
|
|
17
|
+
/**
|
|
18
|
+
* Send an email via the provider.
|
|
19
|
+
*
|
|
20
|
+
* @param params - Email parameters
|
|
21
|
+
* @returns Provider message ID for tracking
|
|
22
|
+
* @throws On provider error (network, auth, etc.)
|
|
23
|
+
*/
|
|
24
|
+
send(params: {
|
|
25
|
+
from: string;
|
|
26
|
+
to: string;
|
|
27
|
+
subject: string;
|
|
28
|
+
html: string;
|
|
29
|
+
replyTo?: string;
|
|
30
|
+
}): Promise<{ messageId: string }>;
|
|
31
|
+
}
|