@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,400 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/createAIRoute.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Route Handler (Vercel AI SDK)
|
|
5
|
+
* @description Platform-agnostic handler for AI chat requests using Vercel AI SDK.
|
|
6
|
+
* Handles auth (via platform wrapper), rate limiting (Upstash), streaming, and cost tracking.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { streamText, generateText, tool, jsonSchema } from 'ai';
|
|
14
|
+
import type { LanguageModel, CoreTool } from 'ai';
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
AIChatRequest,
|
|
18
|
+
AICostConfig,
|
|
19
|
+
AICostRecord,
|
|
20
|
+
AIRateLimitConfig,
|
|
21
|
+
AIRouteConfig,
|
|
22
|
+
AIToolDefinition,
|
|
23
|
+
AIUsage,
|
|
24
|
+
} from '@donotdev/core/server';
|
|
25
|
+
import { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';
|
|
26
|
+
|
|
27
|
+
import { calculateCost } from './costTracker.js';
|
|
28
|
+
|
|
29
|
+
// =============================================================================
|
|
30
|
+
// Types
|
|
31
|
+
// =============================================================================
|
|
32
|
+
|
|
33
|
+
/** Per-request options passed to the AI route handler. */
|
|
34
|
+
export interface AIRouteOptions {
|
|
35
|
+
/** Authenticated user ID */
|
|
36
|
+
userId: string;
|
|
37
|
+
/** Request ID for cost tracking */
|
|
38
|
+
requestId?: string;
|
|
39
|
+
/** Callback to persist cost record (platform-specific) */
|
|
40
|
+
onCostRecord?: (record: AICostRecord) => Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Provider factory map - lazily creates provider instances */
|
|
44
|
+
type ProviderFactory = (apiKey: string) => LanguageModel;
|
|
45
|
+
|
|
46
|
+
// =============================================================================
|
|
47
|
+
// Provider Resolution
|
|
48
|
+
// =============================================================================
|
|
49
|
+
|
|
50
|
+
/** Lazily import and create provider models */
|
|
51
|
+
async function resolveModel(
|
|
52
|
+
provider: string,
|
|
53
|
+
model: string
|
|
54
|
+
): Promise<LanguageModel> {
|
|
55
|
+
const factories: Record<string, () => Promise<ProviderFactory>> = {
|
|
56
|
+
anthropic: async () => {
|
|
57
|
+
const { createAnthropic } = await import('@ai-sdk/anthropic');
|
|
58
|
+
return (apiKey: string) => createAnthropic({ apiKey })(model);
|
|
59
|
+
},
|
|
60
|
+
openai: async () => {
|
|
61
|
+
const { createOpenAI } = await import('@ai-sdk/openai');
|
|
62
|
+
return (apiKey: string) => createOpenAI({ apiKey })(model);
|
|
63
|
+
},
|
|
64
|
+
google: async () => {
|
|
65
|
+
const { createGoogleGenerativeAI } = await import('@ai-sdk/google');
|
|
66
|
+
return (apiKey: string) => createGoogleGenerativeAI({ apiKey })(model);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const factory = factories[provider];
|
|
71
|
+
if (!factory) {
|
|
72
|
+
throw new Error(`Unsupported AI provider: ${provider}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const apiKey = getAIApiKey(provider);
|
|
76
|
+
const createModel = await factory();
|
|
77
|
+
return createModel(apiKey);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// =============================================================================
|
|
81
|
+
// Rate Limiting (reused from old handler)
|
|
82
|
+
// =============================================================================
|
|
83
|
+
|
|
84
|
+
const DEFAULT_RATE_LIMIT: AIRateLimitConfig = {
|
|
85
|
+
maxRequests: 30,
|
|
86
|
+
windowMs: 60_000,
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
let rateLimiter: {
|
|
90
|
+
check: (userId: string, config: AIRateLimitConfig) => Promise<void>;
|
|
91
|
+
} | null = null;
|
|
92
|
+
|
|
93
|
+
async function getRateLimiter() {
|
|
94
|
+
if (rateLimiter) return rateLimiter;
|
|
95
|
+
|
|
96
|
+
const redisUrl = getEnv('UPSTASH_REDIS_REST_URL');
|
|
97
|
+
const redisToken = getEnv('UPSTASH_REDIS_REST_TOKEN');
|
|
98
|
+
|
|
99
|
+
if (!redisUrl || !redisToken) {
|
|
100
|
+
console.warn(
|
|
101
|
+
'[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled.'
|
|
102
|
+
);
|
|
103
|
+
rateLimiter = { check: async () => {} };
|
|
104
|
+
return rateLimiter;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const { Ratelimit } = await import('@upstash/ratelimit');
|
|
109
|
+
const { Redis } = await import('@upstash/redis');
|
|
110
|
+
|
|
111
|
+
const redis = new Redis({ url: redisUrl, token: redisToken });
|
|
112
|
+
const limiters = new Map<string, InstanceType<typeof Ratelimit>>();
|
|
113
|
+
|
|
114
|
+
rateLimiter = {
|
|
115
|
+
check: async (userId: string, config: AIRateLimitConfig) => {
|
|
116
|
+
const key = `${config.maxRequests}:${config.windowMs}`;
|
|
117
|
+
let rl = limiters.get(key);
|
|
118
|
+
if (!rl) {
|
|
119
|
+
rl = new Ratelimit({
|
|
120
|
+
redis,
|
|
121
|
+
limiter: Ratelimit.slidingWindow(
|
|
122
|
+
config.maxRequests,
|
|
123
|
+
`${config.windowMs}ms`
|
|
124
|
+
),
|
|
125
|
+
prefix: 'ai_rl',
|
|
126
|
+
});
|
|
127
|
+
limiters.set(key, rl);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const result = await rl.limit(userId);
|
|
131
|
+
if (!result.success) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`Rate limit exceeded. Maximum ${config.maxRequests} requests per ${config.windowMs / 1000}s.`
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
return rateLimiter;
|
|
139
|
+
} catch (err) {
|
|
140
|
+
console.warn(
|
|
141
|
+
'[AI] Failed to initialize Upstash rate limiter:',
|
|
142
|
+
err instanceof Error ? err.message : err
|
|
143
|
+
);
|
|
144
|
+
rateLimiter = { check: async () => {} };
|
|
145
|
+
return rateLimiter;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// =============================================================================
|
|
150
|
+
// Tool Conversion (JSON Schema → Vercel AI SDK tool)
|
|
151
|
+
// =============================================================================
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Convert framework tool definitions to Vercel AI SDK tools.
|
|
155
|
+
* Uses `jsonSchema()` from the AI SDK to pass JSON Schema directly (no zod dependency).
|
|
156
|
+
* Merges request-level tools with config-level tools (request takes precedence).
|
|
157
|
+
*/
|
|
158
|
+
function resolveTools(
|
|
159
|
+
requestTools?: Record<string, AIToolDefinition>,
|
|
160
|
+
configTools?: Record<string, AIToolDefinition>
|
|
161
|
+
): Record<string, CoreTool> | undefined {
|
|
162
|
+
const merged = { ...configTools, ...requestTools };
|
|
163
|
+
if (Object.keys(merged).length === 0) return undefined;
|
|
164
|
+
|
|
165
|
+
const sdkTools: Record<string, CoreTool> = {};
|
|
166
|
+
for (const [name, def] of Object.entries(merged)) {
|
|
167
|
+
sdkTools[name] = tool({
|
|
168
|
+
description: def.description,
|
|
169
|
+
parameters: jsonSchema(def.parameters),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return sdkTools;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// =============================================================================
|
|
176
|
+
// Core Handler
|
|
177
|
+
// =============================================================================
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Handle an AI chat request using Vercel AI SDK.
|
|
181
|
+
* Supports both streaming (returns SSE Response) and non-streaming (returns JSON).
|
|
182
|
+
*
|
|
183
|
+
* @param request - Validated AI chat request
|
|
184
|
+
* @param config - Route configuration
|
|
185
|
+
* @param options - Per-request options (userId, cost callback)
|
|
186
|
+
* @returns Response (SSE stream or JSON)
|
|
187
|
+
*/
|
|
188
|
+
export async function handleAIRequest(
|
|
189
|
+
request: AIChatRequest,
|
|
190
|
+
config: AIRouteConfig,
|
|
191
|
+
options: AIRouteOptions
|
|
192
|
+
): Promise<Response> {
|
|
193
|
+
// Validate request
|
|
194
|
+
const validation = validateAIChatRequest(request);
|
|
195
|
+
if (!validation.success) {
|
|
196
|
+
return jsonError(
|
|
197
|
+
`Invalid AI request: ${validation.issues?.map((i) => i.message).join(', ')}`,
|
|
198
|
+
400
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Resolve provider + model
|
|
203
|
+
const provider = request.provider || config.provider || 'anthropic';
|
|
204
|
+
const providerModels = AI_MODELS[provider as keyof typeof AI_MODELS];
|
|
205
|
+
const model =
|
|
206
|
+
request.model ||
|
|
207
|
+
config.model ||
|
|
208
|
+
providerModels?.default ||
|
|
209
|
+
'claude-sonnet-4-20250514';
|
|
210
|
+
|
|
211
|
+
// Validate model against allowed list
|
|
212
|
+
if (providerModels) {
|
|
213
|
+
const allowed = providerModels.models as readonly string[];
|
|
214
|
+
if (!allowed.includes(model)) {
|
|
215
|
+
return jsonError(
|
|
216
|
+
`Model '${model}' is not allowed for provider '${provider}'. Allowed: ${allowed.join(', ')}`,
|
|
217
|
+
400
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Rate limit
|
|
223
|
+
try {
|
|
224
|
+
const rl = await getRateLimiter();
|
|
225
|
+
await rl.check(
|
|
226
|
+
options.userId,
|
|
227
|
+
config.rateLimitConfig || DEFAULT_RATE_LIMIT
|
|
228
|
+
);
|
|
229
|
+
} catch (err) {
|
|
230
|
+
return jsonError(
|
|
231
|
+
err instanceof Error ? err.message : 'Rate limit exceeded',
|
|
232
|
+
429
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Resolve AI SDK model
|
|
237
|
+
let languageModel: LanguageModel;
|
|
238
|
+
try {
|
|
239
|
+
languageModel = await resolveModel(provider, model);
|
|
240
|
+
} catch (err) {
|
|
241
|
+
return jsonError(
|
|
242
|
+
`Failed to initialize provider: ${err instanceof Error ? err.message : String(err)}`,
|
|
243
|
+
500
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Build messages for AI SDK
|
|
248
|
+
const systemMessages = request.messages
|
|
249
|
+
.filter((m) => m.role === 'system')
|
|
250
|
+
.map((m) => m.content);
|
|
251
|
+
const systemPrompt =
|
|
252
|
+
request.systemPrompt ||
|
|
253
|
+
config.systemPrompt ||
|
|
254
|
+
(systemMessages.length > 0 ? systemMessages.join('\n') : undefined);
|
|
255
|
+
|
|
256
|
+
const messages = request.messages
|
|
257
|
+
.filter((m) => m.role !== 'system')
|
|
258
|
+
.map((m) => ({
|
|
259
|
+
role: m.role as 'user' | 'assistant',
|
|
260
|
+
content: m.content,
|
|
261
|
+
}));
|
|
262
|
+
|
|
263
|
+
const maxTokens = request.maxTokens || config.maxTokens || 4096;
|
|
264
|
+
const temperature = request.temperature ?? config.temperature ?? 0.7;
|
|
265
|
+
const requestId = options.requestId || crypto.randomUUID();
|
|
266
|
+
|
|
267
|
+
// Resolve tools (request-level overrides config-level)
|
|
268
|
+
const tools = resolveTools(request.tools, config.tools);
|
|
269
|
+
|
|
270
|
+
// Cost tracking helper
|
|
271
|
+
const recordCost = async (usage: AIUsage) => {
|
|
272
|
+
if (!options.onCostRecord) return;
|
|
273
|
+
|
|
274
|
+
const markup = config.cost?.markup ?? 4.0;
|
|
275
|
+
const cost = calculateCost(usage, model, markup);
|
|
276
|
+
|
|
277
|
+
const record: AICostRecord = {
|
|
278
|
+
userId: options.userId,
|
|
279
|
+
model,
|
|
280
|
+
provider,
|
|
281
|
+
usage,
|
|
282
|
+
providerCost: cost.providerCost,
|
|
283
|
+
billedCost: cost.billedCost,
|
|
284
|
+
markup,
|
|
285
|
+
timestamp: new Date().toISOString(),
|
|
286
|
+
requestId,
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// Non-blocking - don't let cost recording failure break the response
|
|
290
|
+
options.onCostRecord(record).catch((err) => {
|
|
291
|
+
console.error('[AI] Failed to record cost:', err);
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// Streaming vs non-streaming
|
|
296
|
+
if (request.stream !== false) {
|
|
297
|
+
// Streaming (default)
|
|
298
|
+
const result = streamText({
|
|
299
|
+
model: languageModel,
|
|
300
|
+
messages,
|
|
301
|
+
system: systemPrompt,
|
|
302
|
+
maxTokens,
|
|
303
|
+
temperature,
|
|
304
|
+
tools,
|
|
305
|
+
onFinish: async ({ usage }: { usage: any }) => {
|
|
306
|
+
await recordCost({
|
|
307
|
+
promptTokens: usage.promptTokens,
|
|
308
|
+
completionTokens: usage.completionTokens,
|
|
309
|
+
totalTokens: usage.promptTokens + usage.completionTokens,
|
|
310
|
+
});
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
return result.toDataStreamResponse();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Non-streaming
|
|
318
|
+
const result = await generateText({
|
|
319
|
+
model: languageModel,
|
|
320
|
+
messages,
|
|
321
|
+
system: systemPrompt,
|
|
322
|
+
maxTokens,
|
|
323
|
+
temperature,
|
|
324
|
+
tools,
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
const usage: AIUsage = {
|
|
328
|
+
promptTokens: result.usage.promptTokens,
|
|
329
|
+
completionTokens: result.usage.completionTokens,
|
|
330
|
+
totalTokens: result.usage.promptTokens + result.usage.completionTokens,
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
await recordCost(usage);
|
|
334
|
+
|
|
335
|
+
// Extract tool calls from result
|
|
336
|
+
const toolCalls =
|
|
337
|
+
result.toolCalls?.map((tc: any) => ({
|
|
338
|
+
id: tc.toolCallId,
|
|
339
|
+
name: tc.toolName,
|
|
340
|
+
args: tc.args,
|
|
341
|
+
})) ?? [];
|
|
342
|
+
|
|
343
|
+
return new Response(
|
|
344
|
+
JSON.stringify({
|
|
345
|
+
message: {
|
|
346
|
+
role: 'assistant',
|
|
347
|
+
content: result.text,
|
|
348
|
+
},
|
|
349
|
+
usage,
|
|
350
|
+
finishReason: result.finishReason,
|
|
351
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
352
|
+
model,
|
|
353
|
+
provider,
|
|
354
|
+
}),
|
|
355
|
+
{
|
|
356
|
+
status: 200,
|
|
357
|
+
headers: { 'Content-Type': 'application/json' },
|
|
358
|
+
}
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// =============================================================================
|
|
363
|
+
// Helpers
|
|
364
|
+
// =============================================================================
|
|
365
|
+
|
|
366
|
+
function jsonError(message: string, status: number): Response {
|
|
367
|
+
return new Response(JSON.stringify({ error: message }), {
|
|
368
|
+
status,
|
|
369
|
+
headers: { 'Content-Type': 'application/json' },
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function getEnv(name: string): string | undefined {
|
|
374
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
375
|
+
return (globalThis as any).Deno?.env?.get(name);
|
|
376
|
+
}
|
|
377
|
+
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function getAIApiKey(provider: string): string {
|
|
381
|
+
const providerKeyMap: Record<string, string> = {
|
|
382
|
+
anthropic: 'ANTHROPIC_API_KEY',
|
|
383
|
+
openai: 'OPENAI_API_KEY',
|
|
384
|
+
google: 'GOOGLE_AI_API_KEY',
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const providerKey = providerKeyMap[provider];
|
|
388
|
+
if (providerKey) {
|
|
389
|
+
const key = getEnv(providerKey);
|
|
390
|
+
if (key) return key;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const key = getEnv('AI_API_KEY');
|
|
394
|
+
if (!key) {
|
|
395
|
+
throw new Error(
|
|
396
|
+
`Missing API key. Set ${providerKey || 'AI_API_KEY'} environment variable.`
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
return key;
|
|
400
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/index.ts
|
|
2
|
+
|
|
3
|
+
export { handleAIRequest } from './createAIRoute.js';
|
|
4
|
+
export type { AIRouteOptions } from './createAIRoute.js';
|
|
5
|
+
export { calculateCost } from './costTracker.js';
|
|
6
|
+
export { resolveModelForTier } from './resolveModelTier.js';
|
|
7
|
+
export { classifyAIError, mapClassifiedToHTTP } from './classifyAIError.js';
|
|
8
|
+
export type { AIErrorCode, ClassifiedAIError } from './classifyAIError.js';
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/resolveModelTier.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Model Tier Resolver
|
|
5
|
+
* @description Resolves the model ID for a given tier via env var chain.
|
|
6
|
+
* Resolution: per-function env → per-tier env → static SSOT.
|
|
7
|
+
* Cross-runtime: Deno (edge functions) + Node (Vercel/Firebase).
|
|
8
|
+
*
|
|
9
|
+
* @version 0.1.0
|
|
10
|
+
* @since 0.6.0
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { AI_TIERS } from '@donotdev/core/server';
|
|
15
|
+
import type { AITierId } from '@donotdev/core/server';
|
|
16
|
+
|
|
17
|
+
// =============================================================================
|
|
18
|
+
// Env helper (Deno + Node cross-runtime)
|
|
19
|
+
// =============================================================================
|
|
20
|
+
|
|
21
|
+
function getEnv(name: string): string | undefined {
|
|
22
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
23
|
+
return (globalThis as any).Deno?.env?.get(name);
|
|
24
|
+
}
|
|
25
|
+
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// =============================================================================
|
|
29
|
+
// Resolver
|
|
30
|
+
// =============================================================================
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Resolve the AI model ID for a given tier.
|
|
34
|
+
*
|
|
35
|
+
* Resolution chain (first non-empty wins):
|
|
36
|
+
* 1. `AI_MODEL_<FUNCTION_NAME>` env var (per-function override)
|
|
37
|
+
* 2. `AI_TIER_<TIER>` env var (per-tier override)
|
|
38
|
+
* 3. `AI_TIERS.<TIER>.defaultModel` (static SSOT from constants)
|
|
39
|
+
*
|
|
40
|
+
* @param tier - The tier ID ('fast', 'standard', 'premium')
|
|
41
|
+
* @param functionName - Optional function name for per-function env var lookup
|
|
42
|
+
* @returns The resolved model ID string
|
|
43
|
+
*/
|
|
44
|
+
export function resolveModelForTier(
|
|
45
|
+
tier: AITierId,
|
|
46
|
+
functionName?: string
|
|
47
|
+
): string {
|
|
48
|
+
// 1. Per-function env var: AI_MODEL_BRAINSTORM, AI_MODEL_SPEC_CHAT, etc.
|
|
49
|
+
if (functionName) {
|
|
50
|
+
const perFn = getEnv(`AI_MODEL_${functionName.toUpperCase()}`);
|
|
51
|
+
if (perFn) return perFn;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 2. Per-tier env var: AI_TIER_FAST, AI_TIER_STANDARD, AI_TIER_PREMIUM
|
|
55
|
+
const perTier = getEnv(`AI_TIER_${tier.toUpperCase()}`);
|
|
56
|
+
if (perTier) return perTier;
|
|
57
|
+
|
|
58
|
+
// 3. Static SSOT
|
|
59
|
+
const tierConfig = Object.values(AI_TIERS).find((t) => t.id === tier);
|
|
60
|
+
return tierConfig?.defaultModel ?? AI_TIERS.STANDARD.defaultModel;
|
|
61
|
+
}
|
|
File without changes
|
|
File without changes
|
|
@@ -24,7 +24,13 @@ import type {
|
|
|
24
24
|
*/
|
|
25
25
|
export interface StripeCheckoutProvider {
|
|
26
26
|
createCheckoutSession(params: {
|
|
27
|
-
priceId
|
|
27
|
+
priceId?: string;
|
|
28
|
+
/** Amount in cents (dynamic pricing mode) */
|
|
29
|
+
unitAmount?: number;
|
|
30
|
+
/** Product name for Stripe checkout (dynamic pricing mode) */
|
|
31
|
+
productName?: string;
|
|
32
|
+
/** Currency code, defaults to 'eur' */
|
|
33
|
+
currency?: string;
|
|
28
34
|
customerEmail?: string;
|
|
29
35
|
metadata: Record<string, string>;
|
|
30
36
|
allowPromotionCodes: boolean;
|
|
@@ -50,10 +56,64 @@ export interface AuthCheckoutProvider {
|
|
|
50
56
|
}>;
|
|
51
57
|
}
|
|
52
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Validate URL has http/https protocol.
|
|
61
|
+
* Platform-agnostic (no firebase logger dependency).
|
|
62
|
+
*/
|
|
63
|
+
function validateCheckoutUrl(url: string, name: string): void {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = new URL(url);
|
|
66
|
+
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
|
67
|
+
throw new Error(`Invalid protocol: ${parsed.protocol}`);
|
|
68
|
+
}
|
|
69
|
+
} catch (error) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`Invalid ${name} URL: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Sanitize metadata: enforce string values, strip script injection, cap lengths.
|
|
78
|
+
* Platform-agnostic (no firebase logger dependency).
|
|
79
|
+
*/
|
|
80
|
+
function sanitizeMetadata(
|
|
81
|
+
metadata: Record<string, any>
|
|
82
|
+
): Record<string, string> {
|
|
83
|
+
const sanitized: Record<string, string> = {};
|
|
84
|
+
|
|
85
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
86
|
+
if (typeof value !== 'string') {
|
|
87
|
+
throw new Error(
|
|
88
|
+
`Metadata value for key '${key}' must be a string, got ${typeof value}`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const sanitizedValue = value
|
|
93
|
+
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
|
|
94
|
+
.replace(/javascript:/gi, '')
|
|
95
|
+
.replace(/on\w+\s*=/gi, '');
|
|
96
|
+
|
|
97
|
+
if (sanitizedValue.length > 1000) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
`Metadata value for key '${key}' is too long (max 1000 characters)`
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (key.length > 100) {
|
|
104
|
+
throw new Error(`Metadata key '${key}' is too long (max 100 characters)`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
sanitized[key] = sanitizedValue;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return sanitized;
|
|
111
|
+
}
|
|
112
|
+
|
|
53
113
|
/**
|
|
54
114
|
* Create checkout session algorithm
|
|
55
115
|
*
|
|
56
|
-
* @version 0.
|
|
116
|
+
* @version 0.2.0
|
|
57
117
|
* @since 0.0.1
|
|
58
118
|
* @author AMBROISE PARK Consulting
|
|
59
119
|
*/
|
|
@@ -63,8 +123,15 @@ export async function createCheckoutAlgorithm(
|
|
|
63
123
|
authProvider: AuthCheckoutProvider,
|
|
64
124
|
billingConfig: StripeBackConfig
|
|
65
125
|
): Promise<CreateCheckoutSessionResponse> {
|
|
126
|
+
if (!process.env.FRONTEND_URL) {
|
|
127
|
+
throw new Error('FRONTEND_URL environment variable is required');
|
|
128
|
+
}
|
|
129
|
+
|
|
66
130
|
const {
|
|
67
131
|
priceId,
|
|
132
|
+
unitAmount,
|
|
133
|
+
productName,
|
|
134
|
+
currency,
|
|
68
135
|
userId,
|
|
69
136
|
customerEmail,
|
|
70
137
|
metadata = {},
|
|
@@ -86,9 +153,39 @@ export async function createCheckoutAlgorithm(
|
|
|
86
153
|
throw new Error(`Invalid billing config key: ${configKey}`);
|
|
87
154
|
}
|
|
88
155
|
|
|
89
|
-
// ✅ VALIDATE: priceId
|
|
90
|
-
|
|
91
|
-
|
|
156
|
+
// ✅ VALIDATE: either priceId or (unitAmount + productName)
|
|
157
|
+
const useDynamicPricing = !priceId && unitAmount && productName;
|
|
158
|
+
if (!priceId && !useDynamicPricing) {
|
|
159
|
+
throw new Error('Either priceId or (unitAmount + productName) is required');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ✅ VALIDATE: price_data not supported for subscriptions
|
|
163
|
+
if (useDynamicPricing && mode === 'subscription') {
|
|
164
|
+
throw new Error(
|
|
165
|
+
'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (priceId) {
|
|
170
|
+
// Fixed pricing: validate priceId matches config (if config has one)
|
|
171
|
+
if (billingItem.priceId && billingItem.priceId !== priceId) {
|
|
172
|
+
throw new Error('Price ID mismatch with configuration');
|
|
173
|
+
}
|
|
174
|
+
} else {
|
|
175
|
+
// Dynamic pricing: maxUnitAmount is required as a security cap
|
|
176
|
+
if (!billingItem.maxUnitAmount) {
|
|
177
|
+
throw new Error(
|
|
178
|
+
'Dynamic pricing requires maxUnitAmount in billing config for security'
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
if (unitAmount! > billingItem.maxUnitAmount) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
`Unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
if (unitAmount! < 100) {
|
|
187
|
+
throw new Error('Unit amount must be at least 100 cents (1.00)');
|
|
188
|
+
}
|
|
92
189
|
}
|
|
93
190
|
|
|
94
191
|
// ✅ VALIDATE: userId exists
|
|
@@ -99,18 +196,81 @@ export async function createCheckoutAlgorithm(
|
|
|
99
196
|
// Verify user exists
|
|
100
197
|
await authProvider.getUser(userId);
|
|
101
198
|
|
|
199
|
+
// ✅ HOOK: beforeCheckout (ownership check, status validation, server-resolved pricing)
|
|
200
|
+
let finalUnitAmount = unitAmount;
|
|
201
|
+
let finalProductName = productName;
|
|
202
|
+
|
|
203
|
+
if (billingItem.beforeCheckout) {
|
|
204
|
+
const hookResult = await billingItem.beforeCheckout(
|
|
205
|
+
userId,
|
|
206
|
+
{
|
|
207
|
+
priceId,
|
|
208
|
+
unitAmount,
|
|
209
|
+
productName,
|
|
210
|
+
currency,
|
|
211
|
+
mode,
|
|
212
|
+
metadata,
|
|
213
|
+
allowPromotionCodes,
|
|
214
|
+
},
|
|
215
|
+
sanitizeMetadata(metadata)
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
if (!hookResult.allowed) {
|
|
219
|
+
throw new Error(
|
|
220
|
+
hookResult.reason || 'Checkout blocked by beforeCheckout hook'
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (hookResult.overrides) {
|
|
225
|
+
if (hookResult.overrides.unitAmount !== undefined) {
|
|
226
|
+
finalUnitAmount = hookResult.overrides.unitAmount;
|
|
227
|
+
}
|
|
228
|
+
if (hookResult.overrides.productName !== undefined) {
|
|
229
|
+
finalProductName = hookResult.overrides.productName;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const finalUseDynamicPricing =
|
|
235
|
+
!priceId && finalUnitAmount && finalProductName;
|
|
236
|
+
|
|
237
|
+
// ✅ VALIDATE: overridden amount still respects security cap
|
|
238
|
+
if (
|
|
239
|
+
finalUseDynamicPricing &&
|
|
240
|
+
billingItem.maxUnitAmount &&
|
|
241
|
+
finalUnitAmount! > billingItem.maxUnitAmount
|
|
242
|
+
) {
|
|
243
|
+
throw new Error(
|
|
244
|
+
`Hook-overridden unit amount ${finalUnitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ✅ VALIDATE: URLs are valid http/https
|
|
249
|
+
const resolvedSuccessUrl =
|
|
250
|
+
successUrl || `${process.env.FRONTEND_URL}/billing/success`;
|
|
251
|
+
const resolvedCancelUrl =
|
|
252
|
+
cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`;
|
|
253
|
+
validateCheckoutUrl(resolvedSuccessUrl, 'success');
|
|
254
|
+
validateCheckoutUrl(resolvedCancelUrl, 'cancel');
|
|
255
|
+
|
|
256
|
+
// ✅ SANITIZE: metadata values (strip scripts, cap lengths)
|
|
257
|
+
const sanitizedMetadata = sanitizeMetadata(metadata);
|
|
258
|
+
|
|
102
259
|
// Create checkout session
|
|
103
260
|
const session = await stripeProvider.createCheckoutSession({
|
|
104
261
|
priceId,
|
|
262
|
+
unitAmount: finalUseDynamicPricing ? finalUnitAmount : undefined,
|
|
263
|
+
productName: finalUseDynamicPricing ? finalProductName : undefined,
|
|
264
|
+
currency: currency || billingItem.currency || 'eur',
|
|
105
265
|
customerEmail,
|
|
106
266
|
metadata: {
|
|
107
|
-
...
|
|
267
|
+
...sanitizedMetadata,
|
|
108
268
|
userId,
|
|
109
269
|
billingConfigKey: configKey as string, // ✅ Server values AFTER spread — cannot be overwritten by client
|
|
110
270
|
},
|
|
111
271
|
allowPromotionCodes,
|
|
112
|
-
successUrl:
|
|
113
|
-
cancelUrl:
|
|
272
|
+
successUrl: resolvedSuccessUrl,
|
|
273
|
+
cancelUrl: resolvedCancelUrl,
|
|
114
274
|
mode,
|
|
115
275
|
});
|
|
116
276
|
|
|
File without changes
|