@donotdev/functions 0.1.0 → 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/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +260 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
- package/lib/firebase/index.js +3 -3
- package/lib/firebase/index.js.map +4 -4
- 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 +8 -2
- 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/github.d.ts +5 -0
- package/lib/shared/index.d.ts +2 -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/oauth/exchangeToken.d.ts +1 -0
- package/lib/shared/oauth/grantAccess.d.ts +1 -0
- package/lib/shared/utils/internal/idempotency.d.ts +1 -0
- package/lib/supabase/ai/createAIFunction.d.ts +30 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/billing/changePlan.d.ts +1 -1
- package/lib/supabase/crud/aggregate.d.ts +1 -0
- package/lib/supabase/crud/create.d.ts +1 -0
- package/lib/supabase/crud/delete.d.ts +1 -0
- package/lib/supabase/crud/get.d.ts +1 -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/index.d.ts +8 -0
- package/lib/supabase/index.js +3 -2
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/ai/chat.d.ts +29 -0
- package/lib/vercel/api/ai/index.d.ts +1 -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/package.json +38 -5
- package/src/firebase/billing/createCheckoutSession.ts +79 -187
- package/src/firebase/oauth/exchangeToken.ts +4 -4
- package/src/firebase/oauth/refreshToken.ts +4 -4
- 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/createCheckout.ts +153 -8
- package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
- package/src/shared/billing/idempotency.ts +5 -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/github.ts +38 -0
- package/src/shared/index.ts +2 -0
- package/src/shared/logger.ts +2 -0
- package/src/shared/oauth/exchangeToken.ts +1 -0
- package/src/shared/oauth/grantAccess.ts +1 -0
- package/src/shared/utils/internal/idempotency.ts +1 -0
- package/src/shared/utils/internal/rateLimiter.ts +6 -3
- package/src/shared/validation.ts +1 -1
- package/src/supabase/ai/createAIFunction.ts +75 -0
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +66 -5
- package/src/supabase/baseFunction.ts +26 -2
- package/src/supabase/billing/changePlan.ts +6 -1
- package/src/supabase/billing/createCheckoutSession.ts +16 -2
- package/src/supabase/crud/aggregate.ts +1 -0
- package/src/supabase/crud/create.ts +1 -0
- package/src/supabase/crud/delete.ts +1 -0
- package/src/supabase/crud/get.ts +1 -0
- package/src/supabase/crud/list.ts +1 -0
- package/src/supabase/crud/update.ts +1 -0
- package/src/supabase/edgeFunction.ts +195 -0
- package/src/supabase/email/createEmailFunction.ts +75 -0
- package/src/supabase/index.ts +12 -0
- package/src/supabase/oauth/exchangeToken.ts +38 -7
- package/src/supabase/oauth/refreshToken.ts +4 -5
- package/src/supabase/registerCrudFunctions.ts +29 -41
- package/src/supabase/utils/idempotency.ts +6 -2
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +1 -0
- package/src/vercel/api/billing/create-checkout-session.ts +27 -4
- package/src/vercel/api/billing/webhook-handler.ts +8 -1
- package/src/vercel/api/index.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +24 -1
- package/src/vercel/api/utils/cors.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/functions",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
|
|
6
6
|
"main": "./lib/firebase/index.js",
|
|
@@ -8,10 +8,16 @@
|
|
|
8
8
|
"files": [
|
|
9
9
|
"lib/",
|
|
10
10
|
"src/",
|
|
11
|
+
"guidelines",
|
|
11
12
|
"README.md",
|
|
12
13
|
"LICENSE.md"
|
|
13
14
|
],
|
|
14
15
|
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./lib/shared/index.d.ts",
|
|
18
|
+
"import": "./lib/shared/index.js",
|
|
19
|
+
"default": "./lib/shared/index.js"
|
|
20
|
+
},
|
|
15
21
|
"./firebase": {
|
|
16
22
|
"types": "./lib/firebase/index.d.ts",
|
|
17
23
|
"import": "./lib/firebase/index.js",
|
|
@@ -47,18 +53,24 @@
|
|
|
47
53
|
"serve": "firebase emulators:start --only functions"
|
|
48
54
|
},
|
|
49
55
|
"dependencies": {
|
|
50
|
-
"@donotdev/core": "^0.1.
|
|
51
|
-
"@donotdev/firebase": "^0.1.
|
|
52
|
-
"@donotdev/supabase": "^0.1.
|
|
56
|
+
"@donotdev/core": "^0.1.1",
|
|
57
|
+
"@donotdev/firebase": "^0.1.1",
|
|
58
|
+
"@donotdev/supabase": "^0.1.1"
|
|
53
59
|
},
|
|
54
60
|
"peerDependencies": {
|
|
61
|
+
"@ai-sdk/anthropic": "^1.2.0",
|
|
62
|
+
"@ai-sdk/google": "^1.2.0",
|
|
63
|
+
"@ai-sdk/openai": "^1.2.0",
|
|
55
64
|
"@sentry/node": "^10.39.0",
|
|
56
65
|
"@supabase/supabase-js": "^2.76.14",
|
|
66
|
+
"ai": "^4.3.0",
|
|
57
67
|
"firebase-admin": "^13.6.1",
|
|
58
68
|
"firebase-functions": "^7.0.5",
|
|
59
69
|
"next": "^16.1.6",
|
|
60
70
|
"stripe": "^20.3.1",
|
|
61
|
-
"valibot": "^1.2.0"
|
|
71
|
+
"valibot": "^1.2.0",
|
|
72
|
+
"@upstash/ratelimit": "^2.0.8",
|
|
73
|
+
"@upstash/redis": "^1.37.0"
|
|
62
74
|
},
|
|
63
75
|
"repository": {
|
|
64
76
|
"type": "git",
|
|
@@ -85,6 +97,18 @@
|
|
|
85
97
|
"access": "public"
|
|
86
98
|
},
|
|
87
99
|
"peerDependenciesMeta": {
|
|
100
|
+
"@ai-sdk/anthropic": {
|
|
101
|
+
"optional": true
|
|
102
|
+
},
|
|
103
|
+
"@ai-sdk/google": {
|
|
104
|
+
"optional": true
|
|
105
|
+
},
|
|
106
|
+
"@ai-sdk/openai": {
|
|
107
|
+
"optional": true
|
|
108
|
+
},
|
|
109
|
+
"ai": {
|
|
110
|
+
"optional": true
|
|
111
|
+
},
|
|
88
112
|
"@sentry/node": {
|
|
89
113
|
"optional": true
|
|
90
114
|
},
|
|
@@ -99,6 +123,15 @@
|
|
|
99
123
|
},
|
|
100
124
|
"next": {
|
|
101
125
|
"optional": true
|
|
126
|
+
},
|
|
127
|
+
"stripe": {
|
|
128
|
+
"optional": true
|
|
129
|
+
},
|
|
130
|
+
"@upstash/ratelimit": {
|
|
131
|
+
"optional": true
|
|
132
|
+
},
|
|
133
|
+
"@upstash/redis": {
|
|
134
|
+
"optional": true
|
|
102
135
|
}
|
|
103
136
|
}
|
|
104
137
|
}
|
|
@@ -2,33 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @fileoverview Create checkout session Firebase function
|
|
5
|
-
* @description Firebase callable function for creating Stripe checkout sessions
|
|
5
|
+
* @description Firebase callable function for creating Stripe checkout sessions.
|
|
6
|
+
* Delegates to shared createCheckoutAlgorithm (SSOT).
|
|
6
7
|
*
|
|
7
|
-
* @version 0.
|
|
8
|
+
* @version 0.2.0
|
|
8
9
|
* @since 0.0.1
|
|
9
10
|
* @author AMBROISE PARK Consulting
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
|
-
import { logger } from 'firebase-functions/v2';
|
|
13
|
-
|
|
14
13
|
import type {
|
|
15
14
|
CreateCheckoutSessionRequest,
|
|
16
15
|
StripeBackConfig,
|
|
17
16
|
} from '@donotdev/core/server';
|
|
18
|
-
import { STRIPE_MODES } from '@donotdev/core/server';
|
|
19
17
|
import { CreateCheckoutSessionRequestSchema } from '@donotdev/core/server';
|
|
20
18
|
import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
|
|
21
19
|
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
validateUrl,
|
|
25
|
-
validateMetadata,
|
|
26
|
-
} from '../../shared/utils/validation.js';
|
|
27
|
-
import { stripe, validateStripeEnvironment } from '../../shared/utils.js';
|
|
28
|
-
import { initStripe } from '../../shared/utils.js'; // ✅ IMPORT INIT
|
|
20
|
+
import { createCheckoutAlgorithm } from '../../shared/billing/createCheckout.js';
|
|
21
|
+
import { initStripe, stripe, validateStripeEnvironment } from '../../shared/utils.js';
|
|
29
22
|
import { createBaseFunction } from '../baseFunction.js';
|
|
30
23
|
import { STRIPE_CONFIG } from '../config/constants.js';
|
|
31
|
-
import { stripeSecretKey } from '../config/secrets.js';
|
|
24
|
+
import { stripeSecretKey } from '../config/secrets.js';
|
|
32
25
|
|
|
33
26
|
import type {
|
|
34
27
|
CallableFunction,
|
|
@@ -36,7 +29,8 @@ import type {
|
|
|
36
29
|
} from 'firebase-functions/v2/https';
|
|
37
30
|
|
|
38
31
|
/**
|
|
39
|
-
* Business logic for creating Stripe checkout session
|
|
32
|
+
* Business logic for creating Stripe checkout session.
|
|
33
|
+
* Uses shared algorithm - same as Supabase and Vercel handlers.
|
|
40
34
|
*/
|
|
41
35
|
async function createCheckoutSessionLogic(
|
|
42
36
|
data: CreateCheckoutSessionRequest,
|
|
@@ -46,200 +40,98 @@ async function createCheckoutSessionLogic(
|
|
|
46
40
|
},
|
|
47
41
|
billingConfig: StripeBackConfig
|
|
48
42
|
) {
|
|
49
|
-
//
|
|
43
|
+
// Initialize Stripe with Firebase secret
|
|
50
44
|
initStripe(stripeSecretKey.value());
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
metadata,
|
|
89
|
-
});
|
|
90
|
-
throw handleError(new Error('Missing billingConfigKey in metadata'));
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const billingItem = billingConfig[configKey];
|
|
94
|
-
if (!billingItem) {
|
|
95
|
-
logger.error('[createCheckoutSession] Invalid billing config key', {
|
|
96
|
-
configKey,
|
|
97
|
-
availableKeys: Object.keys(billingConfig),
|
|
98
|
-
});
|
|
99
|
-
throw handleError(new Error(`Invalid billing config key: ${configKey}`));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// ✅ VALIDATE: priceId matches config
|
|
103
|
-
if (billingItem.priceId !== priceId) {
|
|
104
|
-
logger.error('[createCheckoutSession] Price ID mismatch', {
|
|
105
|
-
requested: priceId,
|
|
106
|
-
expected: billingItem.priceId,
|
|
107
|
-
configKey,
|
|
108
|
-
});
|
|
109
|
-
throw handleError(new Error('Price ID mismatch with configuration'));
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// Verify user exists
|
|
113
|
-
let user;
|
|
114
|
-
try {
|
|
115
|
-
user = await getFirebaseAdminAuth().getUser(userId);
|
|
116
|
-
} catch (error) {
|
|
117
|
-
logger.error('[createCheckoutSession] Failed to get user', {
|
|
118
|
-
userId,
|
|
119
|
-
error: error instanceof Error ? error.message : String(error),
|
|
120
|
-
});
|
|
121
|
-
throw handleError(new Error(`User not found: ${userId}`));
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// Validate URLs from request parameters (frontend responsibility)
|
|
125
|
-
try {
|
|
126
|
-
validateUrl(successUrl, 'success');
|
|
127
|
-
validateUrl(cancelUrl, 'cancel');
|
|
128
|
-
} catch (error) {
|
|
129
|
-
logger.error('[createCheckoutSession] URL validation failed', {
|
|
130
|
-
successUrl,
|
|
131
|
-
cancelUrl,
|
|
132
|
-
error: error instanceof Error ? error.message : String(error),
|
|
133
|
-
});
|
|
134
|
-
throw error;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Validate and sanitize metadata
|
|
138
|
-
let sanitizedMetadata: Record<string, string>;
|
|
139
|
-
try {
|
|
140
|
-
sanitizedMetadata = validateMetadata(metadata);
|
|
141
|
-
} catch (error) {
|
|
142
|
-
logger.error('[createCheckoutSession] Metadata validation failed', {
|
|
143
|
-
metadata,
|
|
144
|
-
error: error instanceof Error ? error.message : String(error),
|
|
145
|
-
});
|
|
146
|
-
throw error;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Create checkout session with Stripe
|
|
150
|
-
let session;
|
|
151
|
-
try {
|
|
152
|
-
session = await stripe.checkout.sessions.create({
|
|
153
|
-
mode,
|
|
154
|
-
line_items: [
|
|
155
|
-
{
|
|
156
|
-
price: priceId,
|
|
157
|
-
quantity: 1,
|
|
45
|
+
validateStripeEnvironment();
|
|
46
|
+
|
|
47
|
+
// Create Stripe provider
|
|
48
|
+
const stripeProvider = {
|
|
49
|
+
async createCheckoutSession(params: {
|
|
50
|
+
priceId?: string;
|
|
51
|
+
unitAmount?: number;
|
|
52
|
+
productName?: string;
|
|
53
|
+
currency?: string;
|
|
54
|
+
customerEmail?: string;
|
|
55
|
+
metadata: Record<string, string>;
|
|
56
|
+
allowPromotionCodes: boolean;
|
|
57
|
+
successUrl: string;
|
|
58
|
+
cancelUrl: string;
|
|
59
|
+
mode?: 'payment' | 'subscription';
|
|
60
|
+
}) {
|
|
61
|
+
const session = await stripe.checkout.sessions.create({
|
|
62
|
+
line_items: [
|
|
63
|
+
params.priceId
|
|
64
|
+
? { price: params.priceId, quantity: 1 }
|
|
65
|
+
: {
|
|
66
|
+
price_data: {
|
|
67
|
+
currency: params.currency || 'eur',
|
|
68
|
+
unit_amount: params.unitAmount!,
|
|
69
|
+
product_data: { name: params.productName! },
|
|
70
|
+
},
|
|
71
|
+
quantity: 1,
|
|
72
|
+
},
|
|
73
|
+
],
|
|
74
|
+
mode: params.mode || 'payment',
|
|
75
|
+
allow_promotion_codes: params.allowPromotionCodes,
|
|
76
|
+
success_url: params.successUrl,
|
|
77
|
+
cancel_url: params.cancelUrl,
|
|
78
|
+
customer_email: params.customerEmail,
|
|
79
|
+
metadata: {
|
|
80
|
+
...params.metadata,
|
|
81
|
+
firebaseUid: params.metadata.userId || '',
|
|
158
82
|
},
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
...sanitizedMetadata,
|
|
166
|
-
userId,
|
|
167
|
-
firebaseUid: userId,
|
|
168
|
-
billingConfigKey: configKey, // ✅ Server values AFTER spread — cannot be overwritten by client
|
|
169
|
-
},
|
|
170
|
-
// For subscriptions, automatically create customer in Stripe
|
|
171
|
-
...(mode === 'subscription' && {
|
|
172
|
-
subscription_data: {
|
|
173
|
-
metadata: {
|
|
174
|
-
...sanitizedMetadata,
|
|
175
|
-
userId,
|
|
176
|
-
firebaseUid: userId,
|
|
177
|
-
billingConfigKey: configKey, // ✅ Server values AFTER spread — cannot be overwritten by client
|
|
83
|
+
...(params.mode === 'subscription' && {
|
|
84
|
+
subscription_data: {
|
|
85
|
+
metadata: {
|
|
86
|
+
...params.metadata,
|
|
87
|
+
firebaseUid: params.metadata.userId || '',
|
|
88
|
+
},
|
|
178
89
|
},
|
|
179
|
-
},
|
|
180
|
-
})
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
priceId,
|
|
185
|
-
userId,
|
|
186
|
-
error: error instanceof Error ? error.message : String(error),
|
|
187
|
-
stripeError: (error as any).type || (error as any).code,
|
|
188
|
-
});
|
|
189
|
-
throw handleError(
|
|
190
|
-
new Error(
|
|
191
|
-
`Stripe checkout session creation failed: ${error instanceof Error ? error.message : String(error)}`
|
|
192
|
-
)
|
|
193
|
-
);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
if (!session.url) {
|
|
197
|
-
logger.error('[createCheckoutSession] Session created but no URL', {
|
|
198
|
-
sessionId: session.id,
|
|
199
|
-
});
|
|
200
|
-
throw handleError(new Error('Failed to create checkout session URL'));
|
|
201
|
-
}
|
|
90
|
+
}),
|
|
91
|
+
});
|
|
92
|
+
return { id: session.id, url: session.url };
|
|
93
|
+
},
|
|
94
|
+
};
|
|
202
95
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
userId
|
|
206
|
-
|
|
207
|
-
|
|
96
|
+
// Create auth provider
|
|
97
|
+
const authProvider = {
|
|
98
|
+
async getUser(userId: string) {
|
|
99
|
+
const user = await getFirebaseAdminAuth().getUser(userId);
|
|
100
|
+
return { customClaims: user.customClaims };
|
|
101
|
+
},
|
|
102
|
+
};
|
|
208
103
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
104
|
+
// Inject userId from authenticated context (not from client)
|
|
105
|
+
const requestWithUserId = {
|
|
106
|
+
...data,
|
|
107
|
+
userId: context.uid,
|
|
212
108
|
};
|
|
109
|
+
|
|
110
|
+
// Delegate to shared algorithm (SSOT)
|
|
111
|
+
return createCheckoutAlgorithm(
|
|
112
|
+
requestWithUserId,
|
|
113
|
+
stripeProvider,
|
|
114
|
+
authProvider,
|
|
115
|
+
billingConfig
|
|
116
|
+
);
|
|
213
117
|
}
|
|
214
118
|
|
|
215
119
|
/**
|
|
216
120
|
* Create Firebase function for checkout session creation
|
|
217
|
-
*
|
|
218
|
-
* @param billingConfig - Billing configuration with product definitions
|
|
219
|
-
* @returns Firebase function for checkout session creation
|
|
220
|
-
*
|
|
221
|
-
* @example
|
|
222
|
-
* const createCheckout = createCheckoutSession(billingConfig);
|
|
223
|
-
* const result = await createCheckout({
|
|
224
|
-
* priceId: 'price_xxx',
|
|
225
|
-
* userId: 'user123',
|
|
226
|
-
* metadata: { billingConfigKey: 'early_bird' }
|
|
227
|
-
* });
|
|
228
|
-
* window.location.href = result.data.sessionUrl;
|
|
229
121
|
*/
|
|
230
122
|
export function createCheckoutSession(
|
|
231
123
|
billingConfig: StripeBackConfig
|
|
232
124
|
): CallableFunction<
|
|
233
125
|
CreateCheckoutSessionRequest,
|
|
234
|
-
Promise<{ sessionId: string; sessionUrl: string }>
|
|
126
|
+
Promise<{ sessionId: string; sessionUrl: string | null }>
|
|
235
127
|
> {
|
|
236
128
|
return createBaseFunction<
|
|
237
129
|
CreateCheckoutSessionRequest,
|
|
238
|
-
{ sessionId: string; sessionUrl: string }
|
|
130
|
+
{ sessionId: string; sessionUrl: string | null }
|
|
239
131
|
>(
|
|
240
132
|
STRIPE_CONFIG,
|
|
241
133
|
CreateCheckoutSessionRequestSchema,
|
|
242
134
|
'create_checkout_session',
|
|
243
|
-
(data, context) => createCheckoutSessionLogic(data, context, billingConfig)
|
|
135
|
+
(data, context) => createCheckoutSessionLogic(data, context, billingConfig)
|
|
244
136
|
);
|
|
245
137
|
}
|
|
@@ -103,10 +103,10 @@ export const exchangeToken = onCall<ExchangeTokenRequest>(async (request) => {
|
|
|
103
103
|
);
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
-
// Get client
|
|
107
|
-
const
|
|
108
|
-
const
|
|
109
|
-
|
|
106
|
+
// Get client credentials: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
|
|
107
|
+
const upper = provider.toUpperCase();
|
|
108
|
+
const clientId = process.env[`${upper}_CLIENT_ID`];
|
|
109
|
+
const clientSecret = process.env[`${upper}_CLIENT_SECRET`];
|
|
110
110
|
|
|
111
111
|
if (!clientId || !clientSecret) {
|
|
112
112
|
throw new HttpsError(
|
|
@@ -49,10 +49,10 @@ export const refreshToken = onCall<OAuthRefreshRequest>(async (request) => {
|
|
|
49
49
|
);
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
// Get client credentials
|
|
53
|
-
const
|
|
54
|
-
const
|
|
55
|
-
|
|
52
|
+
// Get client credentials: {PROVIDER}_CLIENT_ID, {PROVIDER}_CLIENT_SECRET
|
|
53
|
+
const upper = provider.toUpperCase();
|
|
54
|
+
const clientId = process.env[`${upper}_CLIENT_ID`];
|
|
55
|
+
const clientSecret = process.env[`${upper}_CLIENT_SECRET`];
|
|
56
56
|
|
|
57
57
|
if (!clientId || !clientSecret) {
|
|
58
58
|
throw new HttpsError(
|
|
@@ -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
|
+
});
|