@donotdev/functions 0.0.20 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +3 -3
- package/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +260 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
- package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
- package/lib/firebase/auth/index.d.ts +1 -1
- package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
- package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
- package/lib/firebase/billing/changePlan.d.ts +1 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/index.d.ts +1 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
- package/lib/firebase/config/constants.d.ts +4 -4
- package/lib/firebase/config/index.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +2 -2
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/index.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -1
- package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
- package/lib/firebase/helpers/index.d.ts +1 -1
- package/lib/firebase/index.d.ts +1 -1
- package/lib/firebase/index.js +3 -3
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +1 -1
- package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
- package/lib/firebase/oauth/getConnections.d.ts +1 -1
- package/lib/firebase/oauth/githubAccess.d.ts +6 -6
- package/lib/firebase/oauth/index.d.ts +1 -1
- package/lib/firebase/oauth/refreshToken.d.ts +1 -1
- package/lib/firebase/scheduled/index.d.ts +1 -1
- package/lib/shared/ai/classifyAIError.d.ts +35 -0
- package/lib/shared/ai/costTracker.d.ts +20 -0
- package/lib/shared/ai/createAIRoute.d.ts +20 -0
- package/lib/shared/ai/index.d.ts +6 -0
- package/lib/shared/ai/resolveModelTier.d.ts +14 -0
- package/lib/shared/billing/createCheckout.d.ts +11 -5
- package/lib/shared/billing/helpers/index.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
- package/lib/shared/billing/idempotency.d.ts +2 -2
- package/lib/shared/billing/index.d.ts +1 -1
- package/lib/shared/billing/webhookHandler.d.ts +1 -1
- 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 +1 -1
- package/lib/shared/firebase.d.ts +7 -7
- package/lib/shared/github.d.ts +16 -11
- package/lib/shared/index.d.ts +3 -1
- package/lib/shared/index.js +4 -3
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +8 -6
- package/lib/shared/metadata.d.ts +3 -3
- package/lib/shared/oauth/exchangeToken.d.ts +3 -2
- package/lib/shared/oauth/grantAccess.d.ts +3 -2
- package/lib/shared/oauth/index.d.ts +1 -1
- package/lib/shared/schema.d.ts +2 -2
- package/lib/shared/utils/detectFirestore.d.ts +3 -3
- package/lib/shared/utils/external/date.d.ts +2 -2
- package/lib/shared/utils/external/index.d.ts +1 -1
- package/lib/shared/utils/external/references.d.ts +1 -1
- package/lib/shared/utils/external/subscription.d.ts +5 -5
- package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
- package/lib/shared/utils/functionWrapper.d.ts +4 -4
- package/lib/shared/utils/index.d.ts +1 -1
- package/lib/shared/utils/internal/auth.d.ts +4 -4
- package/lib/shared/utils/internal/idempotency.d.ts +3 -2
- package/lib/shared/utils/internal/index.d.ts +1 -1
- package/lib/shared/utils/internal/monitoring.d.ts +7 -7
- package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
- package/lib/shared/utils/internal/validation.d.ts +4 -4
- package/lib/shared/utils/schemaValidation.d.ts +6 -6
- package/lib/shared/utils/validation.d.ts +9 -9
- package/lib/shared/utils/vercelHelpers.d.ts +2 -2
- package/lib/shared/utils.d.ts +19 -19
- package/lib/shared/validation.d.ts +2 -2
- package/lib/supabase/ai/createAIFunction.d.ts +30 -0
- package/lib/supabase/auth/deleteAccount.d.ts +1 -1
- package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/baseFunction.d.ts +2 -2
- package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
- package/lib/supabase/billing/changePlan.d.ts +2 -2
- package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
- package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
- package/lib/supabase/crud/aggregate.d.ts +2 -1
- 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 +2 -1
- package/lib/supabase/crud/index.d.ts +1 -1
- package/lib/supabase/crud/list.d.ts +2 -1
- package/lib/supabase/crud/update.d.ts +2 -1
- package/lib/supabase/edgeFunction.d.ts +56 -0
- package/lib/supabase/email/createEmailFunction.d.ts +31 -0
- package/lib/supabase/helpers/authProvider.d.ts +2 -2
- package/lib/supabase/index.d.ts +11 -2
- package/lib/supabase/index.js +3 -2
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/oauth/disconnect.d.ts +13 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
- package/lib/supabase/oauth/getConnections.d.ts +13 -0
- package/lib/supabase/oauth/index.d.ts +12 -0
- package/lib/supabase/oauth/refreshToken.d.ts +13 -0
- package/lib/supabase/utils/idempotency.d.ts +1 -1
- package/lib/supabase/utils/monitoring.d.ts +1 -1
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- 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/index.d.ts +1 -1
- package/lib/vercel/api/billing/cancel.d.ts +1 -1
- package/lib/vercel/api/billing/change-plan.d.ts +1 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
- package/lib/vercel/api/billing/index.d.ts +1 -1
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
- package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
- package/lib/vercel/api/config/constants.d.ts +9 -9
- package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
- package/lib/vercel/api/config/index.d.ts +1 -1
- package/lib/vercel/api/crud/index.d.ts +1 -1
- package/lib/vercel/api/index.d.ts +2 -1
- 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 +1 -1
- package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
- package/lib/vercel/api/oauth/index.d.ts +1 -1
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/api/utils/cors.d.ts +4 -4
- package/lib/vercel/baseFunction.d.ts +2 -2
- package/package.json +38 -5
- package/src/firebase/auth/getCustomClaims.ts +3 -3
- package/src/firebase/auth/getUserAuthStatus.ts +3 -3
- package/src/firebase/auth/index.ts +1 -1
- package/src/firebase/auth/removeCustomClaims.ts +3 -3
- package/src/firebase/auth/setCustomClaims.ts +70 -69
- package/src/firebase/baseFunction.ts +2 -2
- package/src/firebase/billing/cancelSubscription.ts +3 -3
- package/src/firebase/billing/changePlan.ts +3 -3
- package/src/firebase/billing/createCheckoutSession.ts +79 -187
- package/src/firebase/billing/createCustomerPortal.ts +1 -1
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/index.d.ts +11 -11
- package/src/firebase/billing/index.ts +1 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
- package/src/firebase/billing/webhookHandler.ts +1 -1
- package/src/firebase/config/constants.ts +4 -4
- package/src/firebase/config/index.ts +1 -1
- package/src/firebase/config/secrets.ts +1 -1
- package/src/firebase/crud/aggregate.ts +2 -2
- package/src/firebase/crud/create.ts +2 -2
- package/src/firebase/crud/delete.ts +3 -3
- package/src/firebase/crud/get.ts +1 -1
- package/src/firebase/crud/index.ts +1 -1
- package/src/firebase/crud/list.ts +1 -1
- package/src/firebase/crud/update.ts +2 -2
- package/src/firebase/helpers/githubAccessHelper.ts +4 -4
- package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
- package/src/firebase/helpers/index.ts +1 -1
- package/src/firebase/index.d.ts +9 -9
- package/src/firebase/index.ts +1 -1
- package/src/firebase/oauth/disconnect.ts +2 -2
- package/src/firebase/oauth/exchangeToken.ts +6 -6
- package/src/firebase/oauth/getConnections.ts +2 -2
- package/src/firebase/oauth/githubAccess.ts +10 -10
- package/src/firebase/oauth/index.ts +1 -1
- package/src/firebase/oauth/refreshToken.ts +6 -6
- package/src/firebase/registerCrudFunctions.ts +1 -1
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
- package/src/firebase/scheduled/index.ts +1 -1
- package/src/shared/__tests__/auth.test.ts +46 -0
- package/src/shared/__tests__/errorHandling.test.ts +66 -1
- package/src/shared/__tests__/firebase.test.ts +293 -0
- package/src/shared/__tests__/internalValidation.test.ts +190 -0
- package/src/shared/__tests__/metadata.test.ts +66 -0
- package/src/shared/__tests__/schema.test.ts +219 -0
- package/src/shared/__tests__/schemaValidation.test.ts +72 -0
- package/src/shared/__tests__/subscription.test.ts +45 -0
- package/src/shared/__tests__/utils.test.ts +281 -0
- package/src/shared/__tests__/validation-env.test.ts +73 -0
- package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
- package/src/shared/ai/classifyAIError.ts +163 -0
- package/src/shared/ai/costTracker.ts +51 -0
- package/src/shared/ai/createAIRoute.ts +397 -0
- package/src/shared/ai/index.ts +8 -0
- package/src/shared/ai/resolveModelTier.ts +58 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
- package/src/shared/billing/createCheckout.ts +156 -11
- package/src/shared/billing/helpers/index.ts +1 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +13 -4
- package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
- package/src/shared/billing/idempotency.ts +9 -4
- package/src/shared/billing/index.ts +1 -1
- package/src/shared/billing/webhookHandler.ts +7 -7
- 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 +12 -6
- package/src/shared/firebase.ts +7 -7
- package/src/shared/github.ts +49 -11
- package/src/shared/index.d.ts +9 -9
- package/src/shared/index.ts +3 -1
- package/src/shared/logger.ts +10 -8
- package/src/shared/metadata.ts +3 -3
- package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
- package/src/shared/oauth/exchangeToken.ts +3 -2
- package/src/shared/oauth/grantAccess.ts +3 -2
- package/src/shared/oauth/index.ts +1 -1
- package/src/shared/schema.ts +4 -4
- package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
- package/src/shared/utils/detectFirestore.ts +3 -3
- package/src/shared/utils/external/date.ts +5 -5
- package/src/shared/utils/external/index.ts +1 -1
- package/src/shared/utils/external/references.ts +2 -2
- package/src/shared/utils/external/subscription.ts +5 -5
- package/src/shared/utils/firebaseHelpers.ts +3 -3
- package/src/shared/utils/functionWrapper.ts +4 -4
- package/src/shared/utils/index.ts +1 -1
- package/src/shared/utils/internal/auth.ts +7 -7
- package/src/shared/utils/internal/firebase.ts +1 -1
- package/src/shared/utils/internal/idempotency.ts +4 -3
- package/src/shared/utils/internal/index.ts +1 -1
- package/src/shared/utils/internal/monitoring.ts +8 -8
- package/src/shared/utils/internal/rateLimiter.ts +12 -9
- package/src/shared/utils/internal/validation.ts +5 -5
- package/src/shared/utils/schemaValidation.ts +6 -6
- package/src/shared/utils/validation.ts +10 -10
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +19 -19
- package/src/shared/validation.ts +3 -3
- package/src/supabase/ai/createAIFunction.ts +75 -0
- package/src/supabase/auth/deleteAccount.ts +2 -2
- package/src/supabase/auth/getCustomClaims.ts +2 -2
- package/src/supabase/auth/getUserAuthStatus.ts +2 -2
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +66 -5
- package/src/supabase/baseFunction.ts +29 -5
- package/src/supabase/billing/cancelSubscription.ts +2 -2
- package/src/supabase/billing/changePlan.ts +8 -3
- package/src/supabase/billing/createCheckoutSession.ts +18 -4
- package/src/supabase/billing/createCustomerPortal.ts +2 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
- package/src/supabase/crud/aggregate.ts +2 -1
- package/src/supabase/crud/create.ts +2 -1
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/get.ts +2 -1
- package/src/supabase/crud/index.ts +1 -1
- package/src/supabase/crud/list.ts +2 -1
- package/src/supabase/crud/update.ts +2 -1
- package/src/supabase/edgeFunction.ts +195 -0
- package/src/supabase/email/createEmailFunction.ts +75 -0
- package/src/supabase/helpers/authProvider.ts +2 -2
- package/src/supabase/index.ts +22 -2
- package/src/supabase/oauth/disconnect.ts +104 -0
- package/src/supabase/oauth/exchangeToken.ts +183 -0
- package/src/supabase/oauth/getConnections.ts +85 -0
- package/src/supabase/oauth/index.ts +15 -0
- package/src/supabase/oauth/refreshToken.ts +130 -0
- package/src/supabase/registerCrudFunctions.ts +30 -42
- package/src/supabase/utils/idempotency.ts +7 -3
- package/src/supabase/utils/monitoring.ts +1 -1
- package/src/supabase/utils/rateLimiter.ts +1 -1
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +1 -0
- package/src/vercel/api/auth/get-custom-claims.ts +1 -1
- package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
- package/src/vercel/api/auth/index.ts +1 -1
- package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
- package/src/vercel/api/auth/set-custom-claims.ts +2 -4
- package/src/vercel/api/billing/cancel.ts +3 -3
- package/src/vercel/api/billing/change-plan.ts +3 -3
- package/src/vercel/api/billing/create-checkout-session.ts +30 -7
- package/src/vercel/api/billing/customer-portal.ts +1 -1
- package/src/vercel/api/billing/index.ts +1 -1
- package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
- package/src/vercel/api/billing/webhook-handler.ts +11 -4
- package/src/vercel/api/config/constants.ts +9 -9
- package/src/vercel/api/config/firebase-admin.ts +3 -3
- package/src/vercel/api/config/index.ts +1 -1
- package/src/vercel/api/crud/create.ts +1 -1
- package/src/vercel/api/crud/delete.ts +1 -1
- package/src/vercel/api/crud/get.ts +1 -1
- package/src/vercel/api/crud/index.ts +1 -1
- package/src/vercel/api/crud/list.ts +1 -1
- package/src/vercel/api/crud/update.ts +1 -1
- package/src/vercel/api/index.d.ts +1 -1
- package/src/vercel/api/index.ts +2 -1
- package/src/vercel/api/oauth/check-github-access.ts +3 -3
- package/src/vercel/api/oauth/exchange-token.ts +25 -2
- package/src/vercel/api/oauth/grant-github-access.ts +3 -3
- package/src/vercel/api/oauth/index.ts +1 -1
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
- package/src/vercel/api/utils/cors.ts +10 -4
- package/src/vercel/baseFunction.ts +2 -2
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { calculateCost } from '../costTracker';
|
|
4
|
+
|
|
5
|
+
describe('Server-side calculateCost', () => {
|
|
6
|
+
it('calculates claude-sonnet-4 cost correctly', () => {
|
|
7
|
+
const result = calculateCost(
|
|
8
|
+
{ promptTokens: 1_000_000, completionTokens: 1_000_000, totalTokens: 2_000_000 },
|
|
9
|
+
'claude-sonnet-4-20250514',
|
|
10
|
+
4.0
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
expect(result.providerCost).toBeCloseTo(18.00);
|
|
14
|
+
expect(result.billedCost).toBeCloseTo(72.00);
|
|
15
|
+
expect(result.markup).toBe(4.0);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('calculates gpt-4o cost correctly', () => {
|
|
19
|
+
const result = calculateCost(
|
|
20
|
+
{ promptTokens: 500_000, completionTokens: 100_000, totalTokens: 600_000 },
|
|
21
|
+
'gpt-4o',
|
|
22
|
+
4.0
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
// 0.5M * $2.50/M = $1.25 prompt
|
|
26
|
+
// 0.1M * $10.00/M = $1.00 completion
|
|
27
|
+
// total = $2.25 provider, $9.00 billed
|
|
28
|
+
expect(result.providerCost).toBeCloseTo(2.25);
|
|
29
|
+
expect(result.billedCost).toBeCloseTo(9.00);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('calculates gemini-2.5-pro cost correctly', () => {
|
|
33
|
+
const result = calculateCost(
|
|
34
|
+
{ promptTokens: 100_000, completionTokens: 50_000, totalTokens: 150_000 },
|
|
35
|
+
'gemini-2.5-pro',
|
|
36
|
+
4.0
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
// 0.1M * $1.25/M = $0.125 prompt
|
|
40
|
+
// 0.05M * $10.00/M = $0.50 completion
|
|
41
|
+
// total = $0.625 provider, $2.50 billed
|
|
42
|
+
expect(result.providerCost).toBeCloseTo(0.625);
|
|
43
|
+
expect(result.billedCost).toBeCloseTo(2.50);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('uses default markup of 4.0', () => {
|
|
47
|
+
const result = calculateCost(
|
|
48
|
+
{ promptTokens: 1_000_000, completionTokens: 0, totalTokens: 1_000_000 },
|
|
49
|
+
'claude-haiku-4-5-20251001'
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
// $0.80 * 4 = $3.20
|
|
53
|
+
expect(result.providerCost).toBeCloseTo(0.80);
|
|
54
|
+
expect(result.billedCost).toBeCloseTo(3.20);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('throws for unknown model', () => {
|
|
58
|
+
expect(() =>
|
|
59
|
+
calculateCost(
|
|
60
|
+
{ promptTokens: 100, completionTokens: 50, totalTokens: 150 },
|
|
61
|
+
'imaginary-model-9000'
|
|
62
|
+
)
|
|
63
|
+
).toThrow('Unknown model for cost calculation: imaginary-model-9000');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('handles zero usage', () => {
|
|
67
|
+
const result = calculateCost(
|
|
68
|
+
{ promptTokens: 0, completionTokens: 0, totalTokens: 0 },
|
|
69
|
+
'gpt-4o-mini'
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
expect(result.providerCost).toBe(0);
|
|
73
|
+
expect(result.billedCost).toBe(0);
|
|
74
|
+
expect(result.breakdown.promptCost).toBe(0);
|
|
75
|
+
expect(result.breakdown.completionCost).toBe(0);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('returns correct breakdown', () => {
|
|
79
|
+
const result = calculateCost(
|
|
80
|
+
{ promptTokens: 2_000_000, completionTokens: 500_000, totalTokens: 2_500_000 },
|
|
81
|
+
'gpt-4.1',
|
|
82
|
+
5.0
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
// 2M * $2.00/M = $4.00 prompt
|
|
86
|
+
// 0.5M * $8.00/M = $4.00 completion
|
|
87
|
+
expect(result.breakdown.promptTokens).toBe(2_000_000);
|
|
88
|
+
expect(result.breakdown.completionTokens).toBe(500_000);
|
|
89
|
+
expect(result.breakdown.promptCost).toBeCloseTo(4.00);
|
|
90
|
+
expect(result.breakdown.completionCost).toBeCloseTo(4.00);
|
|
91
|
+
expect(result.providerCost).toBeCloseTo(8.00);
|
|
92
|
+
expect(result.billedCost).toBeCloseTo(40.00);
|
|
93
|
+
expect(result.markup).toBe(5.0);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('pricing is consistent between all supported models', () => {
|
|
97
|
+
const models = [
|
|
98
|
+
'claude-sonnet-4-20250514',
|
|
99
|
+
'claude-haiku-4-5-20251001',
|
|
100
|
+
'claude-opus-4-20250514',
|
|
101
|
+
'gpt-4o',
|
|
102
|
+
'gpt-4o-mini',
|
|
103
|
+
'gpt-4.1',
|
|
104
|
+
'gpt-4.1-mini',
|
|
105
|
+
'o3-mini',
|
|
106
|
+
'gemini-2.0-flash',
|
|
107
|
+
'gemini-2.5-pro',
|
|
108
|
+
'gemini-2.5-flash',
|
|
109
|
+
];
|
|
110
|
+
|
|
111
|
+
for (const model of models) {
|
|
112
|
+
const result = calculateCost(
|
|
113
|
+
{ promptTokens: 1000, completionTokens: 500, totalTokens: 1500 },
|
|
114
|
+
model
|
|
115
|
+
);
|
|
116
|
+
expect(result.providerCost).toBeGreaterThanOrEqual(0);
|
|
117
|
+
expect(result.billedCost).toBeGreaterThanOrEqual(result.providerCost);
|
|
118
|
+
expect(result.markup).toBe(4.0);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
});
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/classifyAIError.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Error Classifier
|
|
5
|
+
* @description Classifies Anthropic API errors into actionable categories
|
|
6
|
+
* for structured error responses in edge functions.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.6.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// =============================================================================
|
|
14
|
+
// Types
|
|
15
|
+
// =============================================================================
|
|
16
|
+
|
|
17
|
+
/** Actionable error category for AI provider failures. */
|
|
18
|
+
export type AIErrorCode =
|
|
19
|
+
| 'rate_limited'
|
|
20
|
+
| 'overloaded'
|
|
21
|
+
| 'auth_error'
|
|
22
|
+
| 'credits_exhausted'
|
|
23
|
+
| 'network'
|
|
24
|
+
| 'internal';
|
|
25
|
+
|
|
26
|
+
/** Result of classifying an AI provider error with retry and severity metadata. */
|
|
27
|
+
export interface ClassifiedAIError {
|
|
28
|
+
code: AIErrorCode;
|
|
29
|
+
retryable: boolean;
|
|
30
|
+
retryAfterMs?: number;
|
|
31
|
+
severity: 'transient' | 'critical';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// =============================================================================
|
|
35
|
+
// Classifier
|
|
36
|
+
// =============================================================================
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Classify an error from an Anthropic API call into an actionable category.
|
|
40
|
+
*
|
|
41
|
+
* | HTTP/Error | Category | Retryable | Severity |
|
|
42
|
+
* |------------------|--------------------|-----------|------------|
|
|
43
|
+
* | 429 | rate_limited | yes | transient |
|
|
44
|
+
* | 529 / 503 | overloaded | yes | transient |
|
|
45
|
+
* | 401 | auth_error | no | critical |
|
|
46
|
+
* | 402 / credits | credits_exhausted | no | critical |
|
|
47
|
+
* | Network/timeout | network | yes | transient |
|
|
48
|
+
* | Other 5xx | internal | no | critical |
|
|
49
|
+
*/
|
|
50
|
+
export function classifyAIError(err: unknown): ClassifiedAIError {
|
|
51
|
+
const status = extractStatus(err);
|
|
52
|
+
const message = extractMessage(err);
|
|
53
|
+
|
|
54
|
+
// 429 - Rate limited
|
|
55
|
+
if (status === 429) {
|
|
56
|
+
return {
|
|
57
|
+
code: 'rate_limited',
|
|
58
|
+
retryable: true,
|
|
59
|
+
retryAfterMs: extractRetryAfter(err) ?? 5_000,
|
|
60
|
+
severity: 'transient',
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 529 / 503 - Overloaded
|
|
65
|
+
if (status === 529 || status === 503) {
|
|
66
|
+
return {
|
|
67
|
+
code: 'overloaded',
|
|
68
|
+
retryable: true,
|
|
69
|
+
retryAfterMs: extractRetryAfter(err) ?? 10_000,
|
|
70
|
+
severity: 'transient',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 401 - Auth error
|
|
75
|
+
if (status === 401) {
|
|
76
|
+
return { code: 'auth_error', retryable: false, severity: 'critical' };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 402 or insufficient credits
|
|
80
|
+
if (status === 402 || message.includes('insufficient') || message.includes('credit')) {
|
|
81
|
+
return { code: 'credits_exhausted', retryable: false, severity: 'critical' };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Network / timeout errors (no HTTP status)
|
|
85
|
+
if (
|
|
86
|
+
!status &&
|
|
87
|
+
(message.includes('fetch') ||
|
|
88
|
+
message.includes('network') ||
|
|
89
|
+
message.includes('ECONNREFUSED') ||
|
|
90
|
+
message.includes('ETIMEDOUT') ||
|
|
91
|
+
message.includes('timeout') ||
|
|
92
|
+
message.includes('aborted') ||
|
|
93
|
+
err instanceof TypeError)
|
|
94
|
+
) {
|
|
95
|
+
return {
|
|
96
|
+
code: 'network',
|
|
97
|
+
retryable: true,
|
|
98
|
+
retryAfterMs: 3_000,
|
|
99
|
+
severity: 'transient',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Everything else
|
|
104
|
+
return { code: 'internal', retryable: false, severity: 'critical' };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Map a classified error code to an HTTP status for the edge function response.
|
|
109
|
+
*/
|
|
110
|
+
export function mapClassifiedToHTTP(code: AIErrorCode): number {
|
|
111
|
+
switch (code) {
|
|
112
|
+
case 'rate_limited': return 429;
|
|
113
|
+
case 'overloaded': return 503;
|
|
114
|
+
case 'auth_error': return 502;
|
|
115
|
+
case 'credits_exhausted': return 502;
|
|
116
|
+
case 'network': return 502;
|
|
117
|
+
case 'internal': return 500;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// =============================================================================
|
|
122
|
+
// Helpers
|
|
123
|
+
// =============================================================================
|
|
124
|
+
|
|
125
|
+
function extractStatus(err: unknown): number | undefined {
|
|
126
|
+
if (err && typeof err === 'object') {
|
|
127
|
+
// Anthropic SDK errors have .status
|
|
128
|
+
if ('status' in err && typeof (err as any).status === 'number') {
|
|
129
|
+
return (err as any).status;
|
|
130
|
+
}
|
|
131
|
+
// Some errors nest status in .error
|
|
132
|
+
if ('error' in err && typeof (err as any).error?.status === 'number') {
|
|
133
|
+
return (err as any).error.status;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function extractMessage(err: unknown): string {
|
|
140
|
+
if (err instanceof Error) return err.message.toLowerCase();
|
|
141
|
+
if (typeof err === 'string') return err.toLowerCase();
|
|
142
|
+
if (err && typeof err === 'object' && 'message' in err) {
|
|
143
|
+
return String((err as any).message).toLowerCase();
|
|
144
|
+
}
|
|
145
|
+
return '';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function extractRetryAfter(err: unknown): number | undefined {
|
|
149
|
+
if (err && typeof err === 'object') {
|
|
150
|
+
// Anthropic SDK puts headers on the error
|
|
151
|
+
const headers = (err as any).headers;
|
|
152
|
+
if (headers) {
|
|
153
|
+
const retryAfter = typeof headers.get === 'function'
|
|
154
|
+
? headers.get('retry-after')
|
|
155
|
+
: headers['retry-after'];
|
|
156
|
+
if (retryAfter) {
|
|
157
|
+
const seconds = Number(retryAfter);
|
|
158
|
+
if (!Number.isNaN(seconds)) return seconds * 1000;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/costTracker.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Server-Side Cost Calculator
|
|
5
|
+
* @description Calculate per-request AI costs using SSOT pricing from `@donotdev/core`.
|
|
6
|
+
* Cost records are written async by platform wrappers (Supabase, Vercel, Firebase).
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { AICostResult, AIUsage } from '@donotdev/core/server';
|
|
14
|
+
import { AI_TOKEN_PRICING, DEFAULT_AI_MARKUP } from '@donotdev/core/server';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Calculate cost from token usage for a given model.
|
|
18
|
+
*
|
|
19
|
+
* @param usage - Token usage counts
|
|
20
|
+
* @param model - Model ID (must exist in AI_TOKEN_PRICING)
|
|
21
|
+
* @param markup - Markup multiplier (default: 4.0)
|
|
22
|
+
* @returns Cost breakdown with provider and billed amounts
|
|
23
|
+
* @throws Error if model is not in pricing table
|
|
24
|
+
*/
|
|
25
|
+
export function calculateCost(
|
|
26
|
+
usage: AIUsage,
|
|
27
|
+
model: string,
|
|
28
|
+
markup: number = DEFAULT_AI_MARKUP
|
|
29
|
+
): AICostResult {
|
|
30
|
+
const pricing = AI_TOKEN_PRICING[model];
|
|
31
|
+
if (!pricing) {
|
|
32
|
+
throw new Error(`Unknown model for cost calculation: ${model}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const promptCost = (usage.promptTokens / 1_000_000) * pricing.promptPer1M;
|
|
36
|
+
const completionCost =
|
|
37
|
+
(usage.completionTokens / 1_000_000) * pricing.completionPer1M;
|
|
38
|
+
const providerCost = promptCost + completionCost;
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
providerCost,
|
|
42
|
+
billedCost: providerCost * markup,
|
|
43
|
+
markup,
|
|
44
|
+
breakdown: {
|
|
45
|
+
promptTokens: usage.promptTokens,
|
|
46
|
+
completionTokens: usage.completionTokens,
|
|
47
|
+
promptCost,
|
|
48
|
+
completionCost,
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|