@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
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// packages/functions/src/supabase/crud/bulk.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Supabase bulk CRUD handler.
|
|
5
|
+
* @description Thin Supabase RPC adapter on top of the shared `executeBulk`
|
|
6
|
+
* orchestrator. Assembles a `supabaseAdmin.rpc('crud_bulk', ...)` call as
|
|
7
|
+
* the target-specific `transact` callback; all other policy (validation,
|
|
8
|
+
* collision, per-bucket ACL, metadata stamping, audit) lives in
|
|
9
|
+
* {@link executeBulk} so Firestore, Vercel, GraphQL and future REST-CRUD
|
|
10
|
+
* server aids share one correctness surface.
|
|
11
|
+
*
|
|
12
|
+
* The Postgres RPC `crud_bulk` wraps `BEGIN ... COMMIT`, so one RPC call
|
|
13
|
+
* is one transaction from the client's perspective.
|
|
14
|
+
*
|
|
15
|
+
* @version 0.2.0
|
|
16
|
+
* @since 0.6.0
|
|
17
|
+
* @author AMBROISE PARK Consulting
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import * as v from 'valibot';
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
BulkCollisionError,
|
|
24
|
+
BulkRequestSchema,
|
|
25
|
+
DoNotDevError,
|
|
26
|
+
} from '@donotdev/core/server';
|
|
27
|
+
import type {
|
|
28
|
+
BulkRequest,
|
|
29
|
+
BulkResponse,
|
|
30
|
+
EntityAccessConfig,
|
|
31
|
+
UserRole,
|
|
32
|
+
} from '@donotdev/core/server';
|
|
33
|
+
import { defaultFieldMapper } from '@donotdev/supabase/server';
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
createMetadata,
|
|
37
|
+
executeBulk,
|
|
38
|
+
updateMetadata,
|
|
39
|
+
} from '../../shared/index.js';
|
|
40
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
41
|
+
|
|
42
|
+
// =============================================================================
|
|
43
|
+
// Types & helpers
|
|
44
|
+
// =============================================================================
|
|
45
|
+
|
|
46
|
+
const mapper = defaultFieldMapper;
|
|
47
|
+
|
|
48
|
+
/** Request payload accepted by the bulk handler — mirrors {@link BulkRequestSchema}. */
|
|
49
|
+
export type BulkEntityRequest = BulkRequest;
|
|
50
|
+
|
|
51
|
+
/** Ordered list of role levels, low → high. Used to pick the strictest needed role. */
|
|
52
|
+
const ROLE_RANK: Record<UserRole, number> = {
|
|
53
|
+
guest: 0,
|
|
54
|
+
user: 1,
|
|
55
|
+
admin: 2,
|
|
56
|
+
super: 3,
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Strip client-supplied timestamps (DB triggers own them) and convert keys to
|
|
61
|
+
* the snake_case shape the DB expects.
|
|
62
|
+
*/
|
|
63
|
+
function prepareInsertRow(
|
|
64
|
+
row: Record<string, unknown>,
|
|
65
|
+
uid: string
|
|
66
|
+
): Record<string, unknown> {
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
68
|
+
const { createdAt, updatedAt, created_at, updated_at, ...rest } =
|
|
69
|
+
row as Record<string, unknown>;
|
|
70
|
+
const snake = mapper.toBackendKeys(rest);
|
|
71
|
+
const meta = mapper.toBackendKeys(
|
|
72
|
+
createMetadata(uid) as Record<string, unknown>
|
|
73
|
+
);
|
|
74
|
+
return { ...snake, ...meta };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function preparePatch(
|
|
78
|
+
patch: Record<string, unknown>,
|
|
79
|
+
uid: string
|
|
80
|
+
): Record<string, unknown> {
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
82
|
+
const {
|
|
83
|
+
createdAt,
|
|
84
|
+
updatedAt,
|
|
85
|
+
created_at,
|
|
86
|
+
updated_at,
|
|
87
|
+
id: _id,
|
|
88
|
+
...rest
|
|
89
|
+
} = patch as Record<string, unknown>;
|
|
90
|
+
const snake = mapper.toBackendKeys(rest);
|
|
91
|
+
const meta = mapper.toBackendKeys(
|
|
92
|
+
updateMetadata(uid) as Record<string, unknown>
|
|
93
|
+
);
|
|
94
|
+
return { ...snake, ...meta };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// =============================================================================
|
|
98
|
+
// Factory
|
|
99
|
+
// =============================================================================
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Create a Supabase Edge Function handler for atomic bulk CRUD on one collection.
|
|
103
|
+
*
|
|
104
|
+
* @description
|
|
105
|
+
* One HTTP round-trip, one rate-limit hit, one audit line, one DB transaction.
|
|
106
|
+
* Inserts, updates and deletes run in input order inside the `crud_bulk` RPC
|
|
107
|
+
* which wraps `BEGIN ... COMMIT` — any failure triggers `ROLLBACK` and the
|
|
108
|
+
* client observes a rejected promise with no partial state.
|
|
109
|
+
*
|
|
110
|
+
* The factory returns a handler that is auto-registered as `bulk_${collection}`
|
|
111
|
+
* by {@link createSupabaseCrudFunctions}.
|
|
112
|
+
*
|
|
113
|
+
* @param collection - Postgres table name for the entity.
|
|
114
|
+
* @param createSchema - Valibot schema validating each `inserts[]` row.
|
|
115
|
+
* @param updateSchema - Valibot schema validating each `updates[].patch` object.
|
|
116
|
+
* @param access - Entity access config; per-bucket role check runs before writes.
|
|
117
|
+
* @returns A `(req: Request) => Promise<Response>` handler for `Deno.serve`.
|
|
118
|
+
* @throws BulkCollisionError — via the thrown DoNotDevError when an id appears in two buckets.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```typescript
|
|
122
|
+
* // Auto-registration (preferred):
|
|
123
|
+
* import * as entities from '../_shared/entities.ts';
|
|
124
|
+
* import { createSupabaseCrudFunctions } from '@donotdev/functions/supabase';
|
|
125
|
+
* const { serve } = createSupabaseCrudFunctions(entities);
|
|
126
|
+
* Deno.serve(serve);
|
|
127
|
+
* // POST { _functionName: 'bulk_events', inserts: [...], updates: [...], deletes: [...] }
|
|
128
|
+
*
|
|
129
|
+
* // Manual registration:
|
|
130
|
+
* import { createSupabaseBulkEntity } from '@donotdev/functions/supabase';
|
|
131
|
+
* import { eventEntity, eventCreateSchema, eventUpdateSchema } from '../_shared/entities.ts';
|
|
132
|
+
* Deno.serve(createSupabaseBulkEntity(
|
|
133
|
+
* eventEntity.collection,
|
|
134
|
+
* eventCreateSchema,
|
|
135
|
+
* eventUpdateSchema,
|
|
136
|
+
* eventEntity.access,
|
|
137
|
+
* ));
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* @version 0.2.0
|
|
141
|
+
* @since 0.6.0
|
|
142
|
+
*/
|
|
143
|
+
export function createSupabaseBulkEntity(
|
|
144
|
+
collection: string,
|
|
145
|
+
createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
146
|
+
draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
147
|
+
updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
148
|
+
access: EntityAccessConfig
|
|
149
|
+
): (req: Request) => Promise<Response> {
|
|
150
|
+
// The wrapper role is the strictest across the three buckets. Entities that
|
|
151
|
+
// only configure a subset (e.g. read-only) collapse to 'user' so mixed-ACL
|
|
152
|
+
// misalignments still reach the handler where `executeBulk` catches them
|
|
153
|
+
// with a precise per-bucket error.
|
|
154
|
+
const wrapperRole: UserRole = (() => {
|
|
155
|
+
const roles: UserRole[] = [];
|
|
156
|
+
if (access.create) roles.push(access.create);
|
|
157
|
+
if (access.update) roles.push(access.update);
|
|
158
|
+
if (access.delete) roles.push(access.delete);
|
|
159
|
+
if (roles.length === 0) return 'user';
|
|
160
|
+
return roles.reduce((a, b) => (ROLE_RANK[a] >= ROLE_RANK[b] ? a : b));
|
|
161
|
+
})();
|
|
162
|
+
|
|
163
|
+
return createSupabaseHandler(
|
|
164
|
+
`bulk_${collection}`,
|
|
165
|
+
BulkRequestSchema,
|
|
166
|
+
async (data: BulkEntityRequest, ctx): Promise<BulkResponse> => {
|
|
167
|
+
const { uid, userRole, supabaseAdmin } = ctx;
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
return await executeBulk({
|
|
171
|
+
collection,
|
|
172
|
+
ops: data,
|
|
173
|
+
createSchema,
|
|
174
|
+
draftCreateSchema,
|
|
175
|
+
updateSchema,
|
|
176
|
+
access,
|
|
177
|
+
uid,
|
|
178
|
+
userRole,
|
|
179
|
+
// Supabase's `crud_bulk` RPC mints ids server-side — skip the
|
|
180
|
+
// client-side mint hook so the RPC owns the id space.
|
|
181
|
+
stampInsertMetadata: prepareInsertRow,
|
|
182
|
+
stampUpdateMetadata: preparePatch,
|
|
183
|
+
transact: async ({ inserts, updates, deletes }) => {
|
|
184
|
+
const { data: rpcResult, error: rpcError } =
|
|
185
|
+
await supabaseAdmin.rpc('crud_bulk', {
|
|
186
|
+
p_collection: collection,
|
|
187
|
+
p_inserts: inserts.map((i) => i.row),
|
|
188
|
+
p_updates: updates.map((u) => ({ id: u.id, patch: u.patch })),
|
|
189
|
+
p_deletes: deletes,
|
|
190
|
+
});
|
|
191
|
+
if (rpcError) {
|
|
192
|
+
throw new DoNotDevError(
|
|
193
|
+
`Failed to execute bulk: ${rpcError.message}`,
|
|
194
|
+
'internal'
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
// RPC may return either camelCase or snake_case id arrays — normalise
|
|
198
|
+
// before `executeBulk` runs its `BulkResponseSchema` validation.
|
|
199
|
+
const raw = (rpcResult ?? {}) as Record<string, unknown>;
|
|
200
|
+
return {
|
|
201
|
+
insertedIds: Array.isArray(raw.insertedIds)
|
|
202
|
+
? (raw.insertedIds as string[])
|
|
203
|
+
: Array.isArray(raw.inserted_ids)
|
|
204
|
+
? (raw.inserted_ids as string[])
|
|
205
|
+
: [],
|
|
206
|
+
updatedIds: Array.isArray(raw.updatedIds)
|
|
207
|
+
? (raw.updatedIds as string[])
|
|
208
|
+
: Array.isArray(raw.updated_ids)
|
|
209
|
+
? (raw.updated_ids as string[])
|
|
210
|
+
: [],
|
|
211
|
+
deletedIds: Array.isArray(raw.deletedIds)
|
|
212
|
+
? (raw.deletedIds as string[])
|
|
213
|
+
: Array.isArray(raw.deleted_ids)
|
|
214
|
+
? (raw.deleted_ids as string[])
|
|
215
|
+
: [],
|
|
216
|
+
};
|
|
217
|
+
},
|
|
218
|
+
audit: (event, { counts }) => {
|
|
219
|
+
// One audit line per bulk (matches the "one audit entry"
|
|
220
|
+
// contract). Sibling handlers use console.log for parity with
|
|
221
|
+
// the edge-function logging expectations.
|
|
222
|
+
console.log(
|
|
223
|
+
`[${event}] uid=${uid} inserts=${counts.inserts} updates=${counts.updates} deletes=${counts.deletes}`
|
|
224
|
+
);
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
} catch (err) {
|
|
228
|
+
// Translate the shared orchestrator's collision error into the
|
|
229
|
+
// DoNotDevError shape expected by the Supabase wire contract
|
|
230
|
+
// (invalid-argument + collision details in `details`).
|
|
231
|
+
if (err instanceof BulkCollisionError) {
|
|
232
|
+
throw new DoNotDevError(err.message, 'invalid-argument', {
|
|
233
|
+
details: {
|
|
234
|
+
collidingIds: err.collidingIds,
|
|
235
|
+
where: err.where,
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
throw err;
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
wrapperRole
|
|
243
|
+
);
|
|
244
|
+
}
|
|
@@ -11,10 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
|
-
import {
|
|
15
|
-
DEFAULT_STATUS_VALUE,
|
|
16
|
-
filterVisibleFields,
|
|
17
|
-
} from '@donotdev/core/server';
|
|
14
|
+
import { filterVisibleFields } from '@donotdev/core/server';
|
|
18
15
|
import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
|
|
19
16
|
import { defaultFieldMapper } from '@donotdev/supabase/server';
|
|
20
17
|
|
|
@@ -25,6 +22,7 @@ import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
|
|
|
25
22
|
|
|
26
23
|
const mapper = defaultFieldMapper;
|
|
27
24
|
|
|
25
|
+
/** Request payload for creating an entity with optional idempotency. */
|
|
28
26
|
export type CreateEntityRequest = {
|
|
29
27
|
payload: Record<string, any>;
|
|
30
28
|
idempotencyKey?: string;
|
|
@@ -129,7 +127,8 @@ async function checkUniqueKeys(
|
|
|
129
127
|
*/
|
|
130
128
|
export function createSupabaseCreateEntity(
|
|
131
129
|
collection: string,
|
|
132
|
-
|
|
130
|
+
createDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
131
|
+
draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
133
132
|
requiredRole: UserRole
|
|
134
133
|
) {
|
|
135
134
|
const requestSchema = v.object({
|
|
@@ -156,12 +155,12 @@ export function createSupabaseCreateEntity(
|
|
|
156
155
|
}
|
|
157
156
|
}
|
|
158
157
|
|
|
159
|
-
//
|
|
160
|
-
const status = payload.status ??
|
|
158
|
+
// New records start as drafts unless the caller explicitly sets a status.
|
|
159
|
+
const status = payload.status ?? 'draft';
|
|
161
160
|
const isDraft = status === 'draft';
|
|
162
161
|
|
|
163
162
|
// Check unique keys if schema has metadata with uniqueKeys
|
|
164
|
-
const schemaWithMeta =
|
|
163
|
+
const schemaWithMeta = createDocumentSchema as {
|
|
165
164
|
metadata?: { uniqueKeys?: UniqueKeyDefinition[] };
|
|
166
165
|
};
|
|
167
166
|
const uniqueKeys = schemaWithMeta.metadata?.uniqueKeys;
|
|
@@ -179,7 +178,7 @@ export function createSupabaseCreateEntity(
|
|
|
179
178
|
// G67: Apply same visibility filtering as normal create path
|
|
180
179
|
return filterVisibleFields(
|
|
181
180
|
checkResult.existingDoc,
|
|
182
|
-
|
|
181
|
+
createDocumentSchema,
|
|
183
182
|
userRole
|
|
184
183
|
);
|
|
185
184
|
}
|
|
@@ -191,11 +190,14 @@ export function createSupabaseCreateEntity(
|
|
|
191
190
|
? normalizePayloadForUniqueKeys(payload, uniqueKeys)
|
|
192
191
|
: payload;
|
|
193
192
|
|
|
194
|
-
// Validate
|
|
195
|
-
//
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
193
|
+
// Validate against the appropriate schema.
|
|
194
|
+
// Drafts must validate with `schemas.draft` so required fields become
|
|
195
|
+
// nullish/optional (instead of failing strict `schemas.create`).
|
|
196
|
+
const payloadForValidation = { ...normalizedPayload, status };
|
|
197
|
+
validateDocument(
|
|
198
|
+
payloadForValidation,
|
|
199
|
+
isDraft ? draftDocumentSchema : createDocumentSchema
|
|
200
|
+
);
|
|
199
201
|
|
|
200
202
|
const metadata = createMetadata(uid);
|
|
201
203
|
const snakeMetadata = mapper.toBackendKeys(
|
|
@@ -16,6 +16,7 @@ import type { UserRole } from '@donotdev/core/server';
|
|
|
16
16
|
import { DoNotDevError } from '../../shared/utils.js';
|
|
17
17
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
18
18
|
|
|
19
|
+
/** Request payload for deleting a single entity by ID. */
|
|
19
20
|
export type DeleteEntityRequest = { id: string };
|
|
20
21
|
|
|
21
22
|
/**
|
package/src/supabase/crud/get.ts
CHANGED
|
@@ -15,6 +15,7 @@ export { createSupabaseUpdateEntity } from './update.js';
|
|
|
15
15
|
export { createSupabaseDeleteEntity } from './delete.js';
|
|
16
16
|
export { createSupabaseListEntities } from './list.js';
|
|
17
17
|
export { createSupabaseAggregateEntities } from './aggregate.js';
|
|
18
|
+
export { createSupabaseBulkEntity } from './bulk.js';
|
|
18
19
|
|
|
19
20
|
export type { GetEntityRequest } from './get.js';
|
|
20
21
|
export type { CreateEntityRequest } from './create.js';
|
|
@@ -22,3 +23,4 @@ export type { UpdateEntityRequest } from './update.js';
|
|
|
22
23
|
export type { DeleteEntityRequest, ReferenceMetadata } from './delete.js';
|
|
23
24
|
export type { ListEntityRequest } from './list.js';
|
|
24
25
|
export type { AggregateEntityRequest } from './aggregate.js';
|
|
26
|
+
export type { BulkEntityRequest } from './bulk.js';
|
|
@@ -40,6 +40,7 @@ function toBackendColumn(field: unknown): string {
|
|
|
40
40
|
);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/** Request payload for listing entities with filtering, sorting, and pagination. */
|
|
43
44
|
export interface ListEntityRequest {
|
|
44
45
|
where?: Array<[string, any, any]>;
|
|
45
46
|
orderBy?: Array<[string, 'asc' | 'desc']>;
|
|
@@ -21,6 +21,7 @@ import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
|
|
|
21
21
|
|
|
22
22
|
const mapper = defaultFieldMapper;
|
|
23
23
|
|
|
24
|
+
/** Request payload for updating an entity by ID with optional idempotency. */
|
|
24
25
|
export type UpdateEntityRequest = {
|
|
25
26
|
id: string;
|
|
26
27
|
payload: Record<string, any>;
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// packages/functions/src/supabase/edgeFunction.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Lightweight edge function wrapper
|
|
5
|
+
* @description Handles CORS, auth, and response formatting for custom Supabase
|
|
6
|
+
* Edge Functions that don't fit the typed createSupabaseHandler pattern.
|
|
7
|
+
*
|
|
8
|
+
* Use createSupabaseHandler for typed CRUD-style handlers with schema validation.
|
|
9
|
+
* Use createEdgeFunction for multi-action functions, AI chat, webhooks, etc.
|
|
10
|
+
*
|
|
11
|
+
* @version 0.1.0
|
|
12
|
+
* @since 0.6.0
|
|
13
|
+
* @author AMBROISE PARK Consulting
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createClient } from '@supabase/supabase-js';
|
|
17
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
18
|
+
|
|
19
|
+
// =============================================================================
|
|
20
|
+
// Types
|
|
21
|
+
// =============================================================================
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Context passed to edge function handlers.
|
|
25
|
+
*
|
|
26
|
+
* @version 0.1.0
|
|
27
|
+
* @since 0.6.0
|
|
28
|
+
*/
|
|
29
|
+
export interface EdgeFunctionContext {
|
|
30
|
+
/** Authenticated user (null if no valid JWT or requireAuth=false) */
|
|
31
|
+
user: { id: string; email?: string } | null;
|
|
32
|
+
/** Admin client (service role, bypasses RLS) - always available */
|
|
33
|
+
supabaseAdmin: SupabaseClient;
|
|
34
|
+
/** User-scoped client (RLS) - null if no valid JWT */
|
|
35
|
+
userClient: SupabaseClient | null;
|
|
36
|
+
/** JSON response with CORS headers */
|
|
37
|
+
json: (data: unknown, status?: number) => Response;
|
|
38
|
+
/** JSON error response: { error: message } with CORS headers */
|
|
39
|
+
error: (message: string, status?: number) => Response;
|
|
40
|
+
/** Raw response with CORS headers (for structured payloads) */
|
|
41
|
+
respond: (data: unknown, status: number) => Response;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Configuration options for edge function creation. */
|
|
45
|
+
export interface EdgeFunctionOptions {
|
|
46
|
+
/** Require JWT auth - returns 401 if missing/invalid (default: true) */
|
|
47
|
+
requireAuth?: boolean;
|
|
48
|
+
/** Extra CORS allowed headers (e.g., 'stripe-signature', 'x-build-secret') */
|
|
49
|
+
extraHeaders?: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// =============================================================================
|
|
53
|
+
// Factory
|
|
54
|
+
// =============================================================================
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Create a Supabase Edge Function handler with CORS, optional auth, and response helpers.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // Auth required (default)
|
|
62
|
+
* Deno.serve(createEdgeFunction(async (req, ctx) => {
|
|
63
|
+
* const body = await req.json();
|
|
64
|
+
* return ctx.json({ result: 'ok' });
|
|
65
|
+
* }));
|
|
66
|
+
*
|
|
67
|
+
* // No auth (public endpoint)
|
|
68
|
+
* Deno.serve(createEdgeFunction(async (req, ctx) => {
|
|
69
|
+
* return ctx.json({ public: true });
|
|
70
|
+
* }, { requireAuth: false }));
|
|
71
|
+
*
|
|
72
|
+
* // Custom auth (webhook)
|
|
73
|
+
* Deno.serve(createEdgeFunction(async (req, ctx) => {
|
|
74
|
+
* const sig = req.headers.get('stripe-signature');
|
|
75
|
+
* if (!sig) return ctx.error('Missing signature', 401);
|
|
76
|
+
* return ctx.json({ received: true });
|
|
77
|
+
* }, { requireAuth: false, extraHeaders: ['stripe-signature'] }));
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function createEdgeFunction(
|
|
81
|
+
handler: (req: Request, ctx: EdgeFunctionContext) => Promise<Response>,
|
|
82
|
+
options?: EdgeFunctionOptions
|
|
83
|
+
): (req: Request) => Promise<Response> {
|
|
84
|
+
const requireAuth = options?.requireAuth ?? true;
|
|
85
|
+
const baseHeaders = 'authorization, content-type, x-client-info, apikey';
|
|
86
|
+
const allowedHeaders = options?.extraHeaders?.length
|
|
87
|
+
? `${baseHeaders}, ${options.extraHeaders.join(', ')}`
|
|
88
|
+
: baseHeaders;
|
|
89
|
+
|
|
90
|
+
return async (req: Request): Promise<Response> => {
|
|
91
|
+
const allowedOrigin = getEnv('ALLOWED_ORIGIN') || '*';
|
|
92
|
+
|
|
93
|
+
// Response helpers (closed over allowedOrigin)
|
|
94
|
+
const respond = (data: unknown, status: number) =>
|
|
95
|
+
jsonResponse(data, status, allowedOrigin);
|
|
96
|
+
const json = (data: unknown, status = 200) => respond(data, status);
|
|
97
|
+
const error = (message: string, status = 400) =>
|
|
98
|
+
respond({ error: message }, status);
|
|
99
|
+
|
|
100
|
+
// CORS preflight
|
|
101
|
+
if (req.method === 'OPTIONS') {
|
|
102
|
+
return new Response(null, {
|
|
103
|
+
status: 204,
|
|
104
|
+
headers: {
|
|
105
|
+
'Access-Control-Allow-Origin': allowedOrigin,
|
|
106
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
107
|
+
'Access-Control-Allow-Headers': allowedHeaders,
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Method check
|
|
113
|
+
if (req.method !== 'POST') {
|
|
114
|
+
return error('Method not allowed', 405);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Supabase clients
|
|
118
|
+
const supabaseUrl = getEnv('SUPABASE_URL');
|
|
119
|
+
const serviceKey =
|
|
120
|
+
getEnv('SUPABASE_SECRET_KEY') || getEnv('SUPABASE_SERVICE_ROLE_KEY');
|
|
121
|
+
|
|
122
|
+
if (!supabaseUrl || !serviceKey) {
|
|
123
|
+
console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY');
|
|
124
|
+
return error('Server misconfigured', 500);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const supabaseAdmin = createClient(supabaseUrl, serviceKey, {
|
|
128
|
+
auth: { autoRefreshToken: false, persistSession: false },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
// Auth
|
|
132
|
+
let user: { id: string; email?: string } | null = null;
|
|
133
|
+
let userClient: SupabaseClient | null = null;
|
|
134
|
+
|
|
135
|
+
const authHeader = req.headers.get('authorization');
|
|
136
|
+
if (authHeader?.startsWith('Bearer ')) {
|
|
137
|
+
const jwt = authHeader.slice(7);
|
|
138
|
+
const anonKey = getEnv('SUPABASE_ANON_KEY');
|
|
139
|
+
if (anonKey) {
|
|
140
|
+
userClient = createClient(supabaseUrl, anonKey, {
|
|
141
|
+
global: { headers: { Authorization: `Bearer ${jwt}` } },
|
|
142
|
+
});
|
|
143
|
+
const { data, error: authError } =
|
|
144
|
+
await supabaseAdmin.auth.getUser(jwt);
|
|
145
|
+
if (!authError && data.user) {
|
|
146
|
+
user = { id: data.user.id, email: data.user.email ?? undefined };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (requireAuth && !user) {
|
|
152
|
+
return error('Unauthorized', 401);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const ctx: EdgeFunctionContext = {
|
|
156
|
+
user,
|
|
157
|
+
supabaseAdmin,
|
|
158
|
+
userClient,
|
|
159
|
+
json,
|
|
160
|
+
error,
|
|
161
|
+
respond,
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
return await handler(req, ctx);
|
|
166
|
+
} catch (e) {
|
|
167
|
+
console.error('Edge function error:', e);
|
|
168
|
+
return error('Internal error', 500);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// =============================================================================
|
|
174
|
+
// Helpers
|
|
175
|
+
// =============================================================================
|
|
176
|
+
|
|
177
|
+
function jsonResponse(
|
|
178
|
+
data: unknown,
|
|
179
|
+
status: number,
|
|
180
|
+
allowedOrigin: string
|
|
181
|
+
): Response {
|
|
182
|
+
return new Response(JSON.stringify(data), {
|
|
183
|
+
status,
|
|
184
|
+
headers: {
|
|
185
|
+
'Content-Type': 'application/json',
|
|
186
|
+
'Access-Control-Allow-Origin': allowedOrigin,
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function getEnv(key: string): string {
|
|
192
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
193
|
+
return (globalThis as any).Deno?.env?.get(key) ?? '';
|
|
194
|
+
}
|
|
195
|
+
return typeof process !== 'undefined' ? (process.env[key] ?? '') : '';
|
|
196
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// packages/functions/src/supabase/email/createEmailFunction.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Email Send - Supabase Edge Function Factory
|
|
5
|
+
* @description Wraps the shared email handler for Supabase Edge Functions.
|
|
6
|
+
* Resolves Resend provider from env, adds auth context.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { EmailRouteConfig, SendEmailRequest } from '@donotdev/core/server';
|
|
14
|
+
import { SendEmailRequestSchema } from '@donotdev/core/server';
|
|
15
|
+
|
|
16
|
+
import { handleEmailRequest } from '../../shared/email/index.js';
|
|
17
|
+
import { createResendProvider } from '../../shared/email/resendProvider.js';
|
|
18
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Create a Supabase Edge Function handler for sending emails.
|
|
22
|
+
* Requires RESEND_API_KEY environment variable.
|
|
23
|
+
*
|
|
24
|
+
* @param config - Email route configuration (templates, defaultFrom)
|
|
25
|
+
* @returns `(req: Request) => Promise<Response>` handler
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```typescript
|
|
29
|
+
* // supabase/functions/send-email/index.ts
|
|
30
|
+
* import { createEmailFunction } from '@donotdev/functions/supabase';
|
|
31
|
+
*
|
|
32
|
+
* const handler = createEmailFunction({
|
|
33
|
+
* provider: 'resend',
|
|
34
|
+
* defaultFrom: 'Frabled <noreply@frabled.com>',
|
|
35
|
+
* templates: { 'order-confirmation': orderConfirmationTemplate },
|
|
36
|
+
* });
|
|
37
|
+
* Deno.serve(handler);
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export function createEmailFunction(config: EmailRouteConfig) {
|
|
41
|
+
return createSupabaseHandler(
|
|
42
|
+
'send-email',
|
|
43
|
+
SendEmailRequestSchema,
|
|
44
|
+
async (data: SendEmailRequest, _ctx) => {
|
|
45
|
+
const apiKey = getEnv('RESEND_API_KEY');
|
|
46
|
+
if (!apiKey) {
|
|
47
|
+
return new Response(
|
|
48
|
+
JSON.stringify({
|
|
49
|
+
success: false,
|
|
50
|
+
error: 'Email provider not configured',
|
|
51
|
+
}),
|
|
52
|
+
{ status: 500, headers: { 'Content-Type': 'application/json' } }
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const provider = createResendProvider(apiKey);
|
|
57
|
+
const result = await handleEmailRequest(data, config, provider);
|
|
58
|
+
|
|
59
|
+
return new Response(JSON.stringify(result), {
|
|
60
|
+
status: result.success ? 200 : 400,
|
|
61
|
+
headers: { 'Content-Type': 'application/json' },
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function getEnv(name: string): string | undefined {
|
|
68
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
69
|
+
return (globalThis as any).Deno?.env?.get(name);
|
|
70
|
+
}
|
|
71
|
+
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
72
|
+
}
|
|
File without changes
|
package/src/supabase/index.ts
CHANGED
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
// Base
|
|
13
13
|
export { createSupabaseHandler } from './baseFunction.js';
|
|
14
14
|
export type { SupabaseHandlerContext } from './baseFunction.js';
|
|
15
|
+
export { createEdgeFunction } from './edgeFunction.js';
|
|
16
|
+
export type {
|
|
17
|
+
EdgeFunctionContext,
|
|
18
|
+
EdgeFunctionOptions,
|
|
19
|
+
} from './edgeFunction.js';
|
|
15
20
|
|
|
16
21
|
// Helpers
|
|
17
22
|
export { createSupabaseAuthProvider } from './helpers/authProvider.js';
|
|
@@ -19,6 +24,7 @@ export { createSupabaseAuthProvider } from './helpers/authProvider.js';
|
|
|
19
24
|
// Auth
|
|
20
25
|
export { createDeleteAccount } from './auth/deleteAccount.js';
|
|
21
26
|
export { createSetCustomClaims } from './auth/setCustomClaims.js';
|
|
27
|
+
export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
|
|
22
28
|
export { createGetCustomClaims } from './auth/getCustomClaims.js';
|
|
23
29
|
export { createRemoveCustomClaims } from './auth/removeCustomClaims.js';
|
|
24
30
|
export { createGetUserAuthStatus } from './auth/getUserAuthStatus.js';
|
|
@@ -38,6 +44,21 @@ export {
|
|
|
38
44
|
createGetConnections,
|
|
39
45
|
} from './oauth/index.js';
|
|
40
46
|
|
|
47
|
+
// AI
|
|
48
|
+
export { createAIFunction } from './ai/createAIFunction.js';
|
|
49
|
+
export { resolveModelForTier } from '../shared/ai/resolveModelTier.js';
|
|
50
|
+
export {
|
|
51
|
+
classifyAIError,
|
|
52
|
+
mapClassifiedToHTTP,
|
|
53
|
+
} from '../shared/ai/classifyAIError.js';
|
|
54
|
+
export type {
|
|
55
|
+
AIErrorCode,
|
|
56
|
+
ClassifiedAIError,
|
|
57
|
+
} from '../shared/ai/classifyAIError.js';
|
|
58
|
+
|
|
59
|
+
// Email
|
|
60
|
+
export { createEmailFunction } from './email/createEmailFunction.js';
|
|
61
|
+
|
|
41
62
|
// CRUD
|
|
42
63
|
export {
|
|
43
64
|
createSupabaseGetEntity,
|