@donotdev/functions 0.2.0 → 0.2.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/lib/chunks/{chunk-IFOYVSPU.js → chunk-3F4BWKQD.js} +2 -2
- package/lib/chunks/{chunk-JTAGPPPL.js → chunk-5IPULSUX.js} +2 -2
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.js.map +7 -0
- package/lib/chunks/{chunk-RM7DV6IQ.js → chunk-CXBSROEW.js} +2 -2
- package/lib/chunks/{chunk-5DTPEM64.js → chunk-GYTCWMXV.js} +1 -1
- package/lib/chunks/{chunk-5DTPEM64.js.map → chunk-GYTCWMXV.js.map} +1 -1
- package/lib/chunks/chunk-LCDLG4VG.js +151 -0
- package/lib/chunks/{chunk-UH4L3EF3.js.map → chunk-LCDLG4VG.js.map} +4 -4
- package/lib/chunks/{chunk-4U7QQWYG.js → chunk-MQANUSY3.js} +2 -2
- package/lib/chunks/chunk-OFQVO3FD.js +22 -0
- package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/{chunk-QJAU2MWV.js → chunk-US2VOP4S.js} +2 -2
- package/lib/chunks/{chunk-QJAU2MWV.js.map → chunk-US2VOP4S.js.map} +3 -3
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/{monitoring-AGCSU3FI.js → monitoring-E7JBYBHQ.js} +2 -2
- package/lib/chunks/{rateLimiter-6KO7AIZP.js → rateLimiter-SQISLOP5.js} +2 -2
- package/lib/chunks/{server-32A5RH4C.js → server-IQ5JNJOM.js} +2 -2
- 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 +0 -0
- 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/create.d.ts +0 -0
- 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 +0 -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 +1 -1
- package/lib/firebase/index.js.map +2 -2
- 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 +0 -0
- package/lib/shared/ai/costTracker.d.ts +0 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- package/lib/shared/billing/createCheckout.d.ts +0 -0
- package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
- 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 +1 -12
- package/lib/shared/billing/index.d.ts +0 -0
- package/lib/shared/billing/stripeClient.d.ts +45 -0
- package/lib/shared/billing/webhookHandler.d.ts +5 -4
- package/lib/shared/email/createEmailRoute.d.ts +0 -0
- package/lib/shared/email/index.d.ts +0 -0
- package/lib/shared/email/provider.d.ts +0 -0
- package/lib/shared/email/resendProvider.d.ts +0 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +0 -0
- package/lib/shared/index.d.ts +0 -0
- package/lib/shared/index.js +1 -1
- package/lib/shared/index.js.map +0 -0
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +0 -0
- package/lib/shared/oauth/exchangeToken.d.ts +0 -0
- package/lib/shared/oauth/grantAccess.d.ts +0 -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 +0 -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 -8
- 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 -43
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +0 -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 +0 -0
- package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
- package/lib/supabase/baseFunction.d.ts +0 -0
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +0 -0
- 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 +0 -0
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +0 -0
- package/lib/supabase/crud/list.d.ts +0 -8
- package/lib/supabase/crud/update.d.ts +0 -0
- package/lib/supabase/edgeFunction.d.ts +0 -0
- package/lib/supabase/email/createEmailFunction.d.ts +0 -0
- package/lib/supabase/helpers/authProvider.d.ts +0 -0
- package/lib/supabase/index.d.ts +3 -2
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +3 -3
- 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 +0 -0
- package/lib/vercel/api/ai/index.d.ts +0 -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/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 +0 -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 +0 -0
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +2 -2
- 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 +2 -2
- package/src/firebase/billing/cancelSubscription.ts +1 -1
- package/src/firebase/billing/changePlan.ts +1 -5
- package/src/firebase/billing/createCheckoutSession.ts +1 -5
- package/src/firebase/billing/createCustomerPortal.ts +1 -1
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
- package/src/firebase/billing/webhookHandler.ts +2 -2
- package/src/shared/__tests__/internalValidation.test.ts +1 -40
- package/src/shared/__tests__/logger.test.ts +31 -0
- package/src/shared/__tests__/utils.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -38
- package/src/shared/billing/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +1 -1
- package/src/shared/billing/idempotency.ts +5 -172
- package/src/shared/billing/stripeClient.ts +91 -0
- package/src/shared/billing/webhookHandler.ts +5 -5
- package/src/shared/logger.ts +4 -6
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils.ts +0 -77
- package/src/supabase/billing/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +1 -5
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -5
- package/src/supabase/billing/stripeWebhook.ts +2 -2
- package/src/supabase/crud/list.ts +2 -0
- package/src/supabase/index.ts +3 -3
- package/src/vercel/api/billing/change-plan.ts +1 -1
- package/src/vercel/api/billing/create-checkout-session.ts +1 -5
- package/src/vercel/api/billing/customer-portal.ts +1 -1
- package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
- package/src/vercel/api/billing/webhook-handler.ts +1 -1
- package/lib/chunks/chunk-2JL3GDTO.js +0 -151
- package/lib/chunks/chunk-2JL3GDTO.js.map +0 -7
- package/lib/chunks/chunk-4TVLH2W2.js +0 -22
- package/lib/chunks/chunk-6CQXHNVL.js +0 -22
- package/lib/chunks/chunk-6CQXHNVL.js.map +0 -7
- package/lib/chunks/chunk-6DSCPZC6.js +0 -22
- package/lib/chunks/chunk-6DSCPZC6.js.map +0 -7
- package/lib/chunks/chunk-7E6TGWHU.js +0 -22
- package/lib/chunks/chunk-7E6TGWHU.js.map +0 -7
- package/lib/chunks/chunk-7LT32OWE.js +0 -22
- package/lib/chunks/chunk-7VH2GJXT.js +0 -151
- package/lib/chunks/chunk-7VH2GJXT.js.map +0 -7
- package/lib/chunks/chunk-API5A4BV.js +0 -22
- package/lib/chunks/chunk-API5A4BV.js.map +0 -7
- package/lib/chunks/chunk-BUP7SXPV.js +0 -23
- package/lib/chunks/chunk-BXKRI3JJ.js +0 -22
- package/lib/chunks/chunk-BXKRI3JJ.js.map +0 -7
- package/lib/chunks/chunk-FSLGZD7A.js +0 -21
- package/lib/chunks/chunk-GVLSPWDD.js +0 -151
- package/lib/chunks/chunk-GVLSPWDD.js.map +0 -7
- package/lib/chunks/chunk-GXQVWEFT.js +0 -22
- package/lib/chunks/chunk-GXQVWEFT.js.map +0 -7
- package/lib/chunks/chunk-HB7EGXVI.js +0 -22
- package/lib/chunks/chunk-HB7EGXVI.js.map +0 -7
- package/lib/chunks/chunk-HM7XCMWW.js +0 -22
- package/lib/chunks/chunk-HM7XCMWW.js.map +0 -7
- package/lib/chunks/chunk-I7IOIL6U.js +0 -151
- package/lib/chunks/chunk-I7IOIL6U.js.map +0 -7
- package/lib/chunks/chunk-IFOYVSPU.js.map +0 -7
- package/lib/chunks/chunk-JTAGPPPL.js.map +0 -7
- package/lib/chunks/chunk-MZ232FUE.js +0 -22
- package/lib/chunks/chunk-MZ232FUE.js.map +0 -7
- package/lib/chunks/chunk-NE5ZTUUZ.js +0 -22
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +0 -7
- package/lib/chunks/chunk-NP2AN2TV.js +0 -22
- package/lib/chunks/chunk-NP2AN2TV.js.map +0 -7
- package/lib/chunks/chunk-RM7DV6IQ.js.map +0 -7
- package/lib/chunks/chunk-RQZGIZHD.js +0 -151
- package/lib/chunks/chunk-RQZGIZHD.js.map +0 -7
- package/lib/chunks/chunk-TBEDQLOB.js +0 -23
- package/lib/chunks/chunk-TBEDQLOB.js.map +0 -7
- package/lib/chunks/chunk-TMHBP3HB.js +0 -22
- package/lib/chunks/chunk-TMHBP3HB.js.map +0 -7
- package/lib/chunks/chunk-UH4L3EF3.js +0 -151
- package/lib/chunks/chunk-UJBIU6TL.js +0 -22
- package/lib/chunks/chunk-UJBIU6TL.js.map +0 -7
- package/lib/chunks/chunk-VKEYW3NT.js +0 -22
- package/lib/chunks/chunk-VKEYW3NT.js.map +0 -7
- package/lib/chunks/chunk-XGXBMXJ6.js +0 -22
- package/lib/chunks/chunk-XGXBMXJ6.js.map +0 -7
- package/lib/chunks/chunk-Y44NEQQG.js +0 -22
- package/lib/chunks/chunk-Y44NEQQG.js.map +0 -7
- package/lib/chunks/chunk-ZVU3KPXI.js +0 -22
- package/lib/chunks/chunk-ZVU3KPXI.js.map +0 -7
- package/lib/chunks/monitoring-PVQMFL34.js +0 -22
- package/lib/chunks/monitoring-V7FZXTTW.js +0 -22
- package/lib/chunks/monitoring-V7FZXTTW.js.map +0 -7
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +0 -7
- package/lib/chunks/rateLimiter-OXVBFW5C.js +0 -22
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +0 -7
- package/lib/chunks/rateLimiter-U45OMTWR.js +0 -22
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +0 -7
- package/lib/chunks/server-32A5RH4C.js.map +0 -7
- package/lib/chunks/server-7HDAP5DL.js +0 -22
- package/lib/chunks/server-7HDAP5DL.js.map +0 -7
- package/lib/chunks/server-S2IMFOY7.js +0 -22
- package/lib/chunks/server-S2IMFOY7.js.map +0 -7
- package/lib/shared/ai/createAIHandler.d.ts +0 -39
- package/lib/shared/ai/providers/anthropic.d.ts +0 -12
- package/lib/shared/ai/providers/google.d.ts +0 -10
- package/lib/shared/ai/providers/index.d.ts +0 -23
- package/lib/shared/ai/providers/openai.d.ts +0 -10
- package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
- /package/lib/chunks/{chunk-7LT32OWE.js.map → chunk-3F4BWKQD.js.map} +0 -0
- /package/lib/chunks/{chunk-4TVLH2W2.js.map → chunk-5IPULSUX.js.map} +0 -0
- /package/lib/chunks/{chunk-BUP7SXPV.js.map → chunk-CXBSROEW.js.map} +0 -0
- /package/lib/chunks/{chunk-4U7QQWYG.js.map → chunk-MQANUSY3.js.map} +0 -0
- /package/lib/chunks/{chunk-FSLGZD7A.js.map → monitoring-E7JBYBHQ.js.map} +0 -0
- /package/lib/chunks/{monitoring-AGCSU3FI.js.map → rateLimiter-SQISLOP5.js.map} +0 -0
- /package/lib/chunks/{monitoring-PVQMFL34.js.map → server-IQ5JNJOM.js.map} +0 -0
package/src/shared/logger.ts
CHANGED
|
@@ -23,12 +23,10 @@
|
|
|
23
23
|
* @author AMBROISE PARK Consulting
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
-
//
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
// ServerShim: Warn if not in Node.js (e.g., Deno) but don't throw — allow fallback logging
|
|
26
|
+
// Node-only metadata (pid, version) is added when running on Node; Deno runtimes
|
|
27
|
+
// (Supabase Edge) log without it. Server-only by package: @donotdev/functions is
|
|
28
|
+
// never imported by client code, so no runtime browser check (Supabase Edge
|
|
29
|
+
// defines `window`, which made such a check throw on every edge function).
|
|
32
30
|
const _isNodeEnv = typeof process !== 'undefined' && !!process.versions?.node;
|
|
33
31
|
|
|
34
32
|
let sentryEnabled = false;
|
|
@@ -13,24 +13,6 @@ import * as v from 'valibot';
|
|
|
13
13
|
|
|
14
14
|
import { DoNotDevError } from '@donotdev/core/server';
|
|
15
15
|
|
|
16
|
-
/**
|
|
17
|
-
* Validates environment variables required for Stripe
|
|
18
|
-
*
|
|
19
|
-
* @version 0.1.0
|
|
20
|
-
* @since 0.0.1
|
|
21
|
-
* @author AMBROISE PARK Consulting
|
|
22
|
-
*/
|
|
23
|
-
export function validateStripeEnvironment(): void {
|
|
24
|
-
const required = ['STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET'];
|
|
25
|
-
const missing = required.filter((key) => !process.env[key]);
|
|
26
|
-
|
|
27
|
-
if (missing.length > 0) {
|
|
28
|
-
throw new Error(
|
|
29
|
-
`Missing required environment variables: ${missing.join(', ')}`
|
|
30
|
-
);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
16
|
/**
|
|
35
17
|
* Safely parses JSON with error handling
|
|
36
18
|
*
|
package/src/shared/utils.ts
CHANGED
|
@@ -9,13 +9,11 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import Stripe from 'stripe';
|
|
13
12
|
import * as v from 'valibot';
|
|
14
13
|
|
|
15
14
|
import { DoNotDevError } from '@donotdev/core/server';
|
|
16
15
|
import type { OAuthPartnerId, UserRole } from '@donotdev/core/server';
|
|
17
16
|
|
|
18
|
-
import { STRIPE_API_VERSION_PIN } from './billing/apiVersion.js';
|
|
19
17
|
import {
|
|
20
18
|
assertAuthenticated as internalAssertAuthenticated,
|
|
21
19
|
assertAdmin as internalAssertAdmin,
|
|
@@ -24,66 +22,6 @@ import {
|
|
|
24
22
|
// Re-export DoNotDevError for external use
|
|
25
23
|
export { DoNotDevError };
|
|
26
24
|
|
|
27
|
-
// Lazy initialization of Stripe
|
|
28
|
-
let _stripe: Stripe | null = null;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Initialize Stripe explicitly (e.g. with a secret from defineSecret).
|
|
32
|
-
* API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.
|
|
33
|
-
* @param apiKey - Stripe secret key
|
|
34
|
-
*
|
|
35
|
-
* @version 0.2.0
|
|
36
|
-
* @since 0.0.1
|
|
37
|
-
* @author AMBROISE PARK Consulting
|
|
38
|
-
*/
|
|
39
|
-
export function initStripe(apiKey: string) {
|
|
40
|
-
if (!apiKey) throw new Error('Stripe API key is required');
|
|
41
|
-
|
|
42
|
-
// Unset: the framework pin (pre-basil fields are still read by subscription handlers)
|
|
43
|
-
const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
|
|
44
|
-
|
|
45
|
-
_stripe = new Stripe(apiKey, {
|
|
46
|
-
apiVersion: apiVersion as any,
|
|
47
|
-
});
|
|
48
|
-
return _stripe;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Get Stripe instance with lazy initialization
|
|
53
|
-
*
|
|
54
|
-
* @version 0.1.0
|
|
55
|
-
* @since 0.0.1
|
|
56
|
-
* @author AMBROISE PARK Consulting
|
|
57
|
-
*/
|
|
58
|
-
export function getStripe(): Stripe {
|
|
59
|
-
if (!_stripe) {
|
|
60
|
-
// Legacy/Vercel fallback: Try process.env
|
|
61
|
-
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
|
|
62
|
-
if (STRIPE_SECRET_KEY) {
|
|
63
|
-
initStripe(STRIPE_SECRET_KEY);
|
|
64
|
-
} else {
|
|
65
|
-
throw new Error(
|
|
66
|
-
'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'
|
|
67
|
-
);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
// We know _stripe is set here or we threw
|
|
71
|
-
return _stripe!;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Lazy-initialized Stripe instance proxy
|
|
76
|
-
*
|
|
77
|
-
* @version 0.1.0
|
|
78
|
-
* @since 0.0.1
|
|
79
|
-
* @author AMBROISE PARK Consulting
|
|
80
|
-
*/
|
|
81
|
-
export const stripe = new Proxy({} as Stripe, {
|
|
82
|
-
get(target, prop) {
|
|
83
|
-
return getStripe()[prop as keyof Stripe];
|
|
84
|
-
},
|
|
85
|
-
});
|
|
86
|
-
|
|
87
25
|
/**
|
|
88
26
|
* Assert that a user is authenticated from a Firebase callable auth context.
|
|
89
27
|
*
|
|
@@ -137,21 +75,6 @@ export function getUserRole(auth: any): UserRole {
|
|
|
137
75
|
return 'user';
|
|
138
76
|
}
|
|
139
77
|
|
|
140
|
-
/**
|
|
141
|
-
* Validates that required Stripe environment variables are set
|
|
142
|
-
*
|
|
143
|
-
* @version 0.1.0
|
|
144
|
-
* @since 0.0.1
|
|
145
|
-
* @author AMBROISE PARK Consulting
|
|
146
|
-
*/
|
|
147
|
-
export function validateStripeEnvironment(): void {
|
|
148
|
-
// Functions v2 automatically injects secrets as process.env when declared in config
|
|
149
|
-
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
|
|
150
|
-
if (!STRIPE_SECRET_KEY) {
|
|
151
|
-
throw new Error('Missing STRIPE_SECRET_KEY environment variable');
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
78
|
/**
|
|
156
79
|
* Creates a standardized success response
|
|
157
80
|
*
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
14
|
import { cancelUserSubscription } from '../../shared/billing/helpers/subscriptionManagement.js';
|
|
15
|
-
import { initStripe } from '../../shared/
|
|
15
|
+
import { initStripe } from '../../shared/billing/stripeClient.js';
|
|
16
16
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
17
17
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
18
18
|
|
|
@@ -14,7 +14,7 @@ import * as v from 'valibot';
|
|
|
14
14
|
import { hasRoleAccess, type StripeBackConfig } from '@donotdev/core/server';
|
|
15
15
|
|
|
16
16
|
import { changeUserPlan } from '../../shared/billing/helpers/subscriptionManagement.js';
|
|
17
|
-
import { initStripe } from '../../shared/
|
|
17
|
+
import { initStripe } from '../../shared/billing/stripeClient.js';
|
|
18
18
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
19
19
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
20
20
|
|
|
@@ -15,11 +15,7 @@ import type { CreateCheckoutSessionRequest } from '@donotdev/core/server';
|
|
|
15
15
|
|
|
16
16
|
import { createCheckoutAlgorithm } from '../../shared/billing/createCheckout.js';
|
|
17
17
|
import type { StripeSessionProvider } from '../../shared/billing/createCheckout.js';
|
|
18
|
-
import {
|
|
19
|
-
initStripe,
|
|
20
|
-
stripe,
|
|
21
|
-
validateStripeEnvironment,
|
|
22
|
-
} from '../../shared/utils.js';
|
|
18
|
+
import { initStripe, stripe, validateStripeEnvironment } from '../../shared/billing/stripeClient.js';
|
|
23
19
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
24
20
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
25
21
|
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import * as v from 'valibot';
|
|
13
13
|
|
|
14
14
|
import { createCustomerPortalSession } from '../../shared/billing/helpers/subscriptionManagement.js';
|
|
15
|
-
import { initStripe } from '../../shared/
|
|
15
|
+
import { initStripe } from '../../shared/billing/stripeClient.js';
|
|
16
16
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
17
17
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
18
18
|
|
|
@@ -12,11 +12,7 @@
|
|
|
12
12
|
import type Stripe from 'stripe';
|
|
13
13
|
import * as v from 'valibot';
|
|
14
14
|
|
|
15
|
-
import {
|
|
16
|
-
initStripe,
|
|
17
|
-
stripe,
|
|
18
|
-
validateStripeEnvironment,
|
|
19
|
-
} from '../../shared/utils.js';
|
|
15
|
+
import { initStripe, stripe, validateStripeEnvironment } from '../../shared/billing/stripeClient.js';
|
|
20
16
|
import { createSupabaseHandler } from '../baseFunction.js';
|
|
21
17
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
22
18
|
|
|
@@ -13,9 +13,9 @@
|
|
|
13
13
|
import type { StripeBackConfig } from '@donotdev/core/server';
|
|
14
14
|
|
|
15
15
|
import { updateUserSubscription } from '../../shared/billing/helpers/updateUserSubscription.js';
|
|
16
|
-
import { createSupabaseIdempotencyStore } from '../../shared/billing/
|
|
16
|
+
import { createSupabaseIdempotencyStore } from '../../shared/billing/supabaseIdempotency.js';
|
|
17
17
|
import { processWebhook } from '../../shared/billing/webhookHandler.js';
|
|
18
|
-
import { initStripe, stripe } from '../../shared/
|
|
18
|
+
import { initStripe, stripe } from '../../shared/billing/stripeClient.js';
|
|
19
19
|
import { createEdgeFunction } from '../edgeFunction.js';
|
|
20
20
|
import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
|
|
21
21
|
|
package/src/supabase/index.ts
CHANGED
|
@@ -34,13 +34,13 @@ export { createCheckoutSession } from './billing/createCheckoutSession.js';
|
|
|
34
34
|
export { createStripeWebhook } from './billing/stripeWebhook.js';
|
|
35
35
|
export {
|
|
36
36
|
createSupabaseIdempotencyStore,
|
|
37
|
-
ReservationLostError,
|
|
38
37
|
WEBHOOK_EVENTS_SQL,
|
|
39
|
-
} from '../shared/billing/
|
|
38
|
+
} from '../shared/billing/supabaseIdempotency.js';
|
|
39
|
+
export { ReservationLostError } from '../shared/billing/idempotencyContract.js';
|
|
40
40
|
export type {
|
|
41
41
|
IdempotencyStore,
|
|
42
42
|
ReservationResult,
|
|
43
|
-
} from '../shared/billing/
|
|
43
|
+
} from '../shared/billing/idempotencyContract.js';
|
|
44
44
|
// Custom StripeOrder entry points (app request shape, own StripeSessionProvider)
|
|
45
45
|
export { createCheckoutAlgorithm } from '../shared/billing/createCheckout.js';
|
|
46
46
|
export type { StripeSessionProvider } from '../shared/billing/createCheckout.js';
|
|
@@ -17,7 +17,7 @@ import type { StripeBackConfig } from '@donotdev/core/server';
|
|
|
17
17
|
|
|
18
18
|
import { updateUserSubscription } from '../../../shared/billing/helpers/updateUserSubscription.js';
|
|
19
19
|
import { handleError } from '../../../shared/errorHandling.js';
|
|
20
|
-
import { stripe, validateStripeEnvironment } from '../../../shared/
|
|
20
|
+
import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
|
|
21
21
|
import { createVercelBaseFunction } from '../../baseFunction.js';
|
|
22
22
|
|
|
23
23
|
const changePlanSchema = v.object({
|
|
@@ -22,11 +22,7 @@ import { resolveBillingBackend } from './backend.js';
|
|
|
22
22
|
import type { VercelBillingOptions } from './backend.js';
|
|
23
23
|
import { createCheckoutAlgorithm } from '../../../shared/billing/createCheckout.js';
|
|
24
24
|
import type { StripeSessionProvider } from '../../../shared/billing/createCheckout.js';
|
|
25
|
-
import {
|
|
26
|
-
initStripe,
|
|
27
|
-
stripe,
|
|
28
|
-
validateStripeEnvironment,
|
|
29
|
-
} from '../../../shared/utils.js';
|
|
25
|
+
import { initStripe, stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
|
|
30
26
|
import { createVercelBaseFunction } from '../../baseFunction.js';
|
|
31
27
|
|
|
32
28
|
/**
|
|
@@ -13,7 +13,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
|
|
|
13
13
|
import * as v from 'valibot';
|
|
14
14
|
|
|
15
15
|
import { handleError } from '../../../shared/errorHandling.js';
|
|
16
|
-
import { stripe, validateStripeEnvironment } from '../../../shared/
|
|
16
|
+
import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
|
|
17
17
|
import { createVercelBaseFunction } from '../../baseFunction.js';
|
|
18
18
|
|
|
19
19
|
const customerPortalSchema = v.object({
|
|
@@ -15,7 +15,7 @@ import * as v from 'valibot';
|
|
|
15
15
|
|
|
16
16
|
import type { RefreshSubscriptionRequest } from '@donotdev/core/server';
|
|
17
17
|
|
|
18
|
-
import { stripe, validateStripeEnvironment } from '../../../shared/
|
|
18
|
+
import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
|
|
19
19
|
import { createVercelBaseFunction } from '../../baseFunction.js';
|
|
20
20
|
|
|
21
21
|
const refreshSubscriptionStatusSchema = v.object({
|
|
@@ -18,7 +18,7 @@ import type { VercelBillingOptions } from './backend.js';
|
|
|
18
18
|
import { updateUserSubscription } from '../../../shared/billing/helpers/updateUserSubscription.js';
|
|
19
19
|
import { processWebhook } from '../../../shared/billing/webhookHandler.js';
|
|
20
20
|
import { logger } from '../../../shared/logger.js';
|
|
21
|
-
import { stripe } from '../../../shared/
|
|
21
|
+
import { stripe } from '../../../shared/billing/stripeClient.js';
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* Create Vercel webhook handler from billing config.
|
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname } from 'node:path';
|
|
4
|
-
import { Buffer } from 'node:buffer';
|
|
5
|
-
import process from 'node:process';
|
|
6
|
-
|
|
7
|
-
const require = __createRequire(import.meta.url);
|
|
8
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
-
const __dirname = dirname(__filename);
|
|
10
|
-
|
|
11
|
-
if (typeof globalThis !== 'undefined') {
|
|
12
|
-
globalThis.require = require;
|
|
13
|
-
globalThis.__filename = __filename;
|
|
14
|
-
globalThis.__dirname = __dirname;
|
|
15
|
-
globalThis.Buffer = Buffer;
|
|
16
|
-
globalThis.process = process;
|
|
17
|
-
if (typeof global === 'undefined') {
|
|
18
|
-
globalThis.global = globalThis;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
import{A as fe,B as P,D as he,E as ye,F as M,H as Ee,L as b,V,W as G,_ as D,a as se,b as j,c as ie,d as ae,k as ce,o as de,p as ue,q as H,r as pe,s as L,t as T,v as le,x as me}from"./chunk-6CQXHNVL.js";import{a as l}from"./chunk-NP2AN2TV.js";import{a as i}from"./chunk-AYY7UXNI.js";function y(e){let t,r,o;if(e instanceof b)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new b(r,t,o?{details:o}:void 0)}i(y,"handleError");var ge=T(["firebase","supabase"]);function Tt(e){let t=P(ge,e);if(!t.success){let r=ge.options.map(o=>`'${o}'`).join(", ");throw new b(`Invalid backend ${JSON.stringify(e)}: expected one of ${r}`,"invalid-argument")}return t.output}i(Tt,"parseAuthBackend");async function Y(){let{getFirebaseAdminAuth:e}=await import("./server-S2IMFOY7.js");return e()}i(Y,"getFirebaseAuth");function Ke(e){if(!e||typeof e!="string")throw new Error("Authentication required");return e}i(Ke,"assertAuthenticated");async function Pt(e){Ke(e);try{let t={};G("serverAuth")?t=(await V("serverAuth").getUser(e))?.customClaims??{}:t=(await(await Y()).getUser(e)).customClaims??{};let r=t.role;if(!(r==="admin"||r==="super"||t.isAdmin===!0||t.isSuper===!0))throw new Error("Admin privileges required");return e}catch(t){throw t instanceof Error&&t.message==="Admin privileges required"?t:new Error("Failed to verify admin status")}}i(Pt,"assertAdmin");function qe(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}i(qe,"extractBearerToken");async function je(e,t){try{return t==="supabase"?await He(e):t==="firebase"?{uid:(await(await Y()).verifyIdToken(e)).uid}:G("serverAuth")?{uid:(await V("serverAuth").verifyToken(e)).uid}:{uid:(await(await Y()).verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}i(je,"verifyToken");async function He(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let n=t(r,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:a}=await n.auth.getUser(e);if(a||!s)throw new Error("Invalid or expired token");return{uid:s.id}}i(He,"verifySupabaseToken");async function Ve(e,t){let r=qe(e.headers.authorization),{uid:o}=await je(r,t);return o}i(Ve,"verifyAuthToken");var xt=Ve;function X(e,t,r=ie){let o=ae[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,s=e.completionTokens/1e6*o.completionPer1M,a=n+s;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:s}}}i(X,"calculateCost");async function Ge(e,t){let o={anthropic:i(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:i(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:i(async()=>{let{createGoogleGenerativeAI:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=Qe(e);return(await o())(n)}i(Ge,"resolveModel");var Ye={maxRequests:30,windowMs:6e4},I=null;async function Xe(){if(I)return I;let e=B("UPSTASH_REDIS_REST_URL"),t=B("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),I={check:i(async()=>{},"check")},I;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),s=new Map;return I={check:i(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=s.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),s.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},I}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),I={check:i(async()=>{},"check")},I}}i(Xe,"getRateLimiter");function ze(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[s,a]of Object.entries(o))n[s]=e.tool({description:a.description,parameters:e.jsonSchema(a.parameters)});return n}i(ze,"resolveTools");async function Je(e,t,r){let o=he(e);if(!o.success)return F(`Invalid AI request: ${o.issues?.map(p=>p.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",s=se[n],a=e.model||t.model||s?.default||"claude-sonnet-4-20250514";if(s){let p=s.models;if(!p.includes(a))return F(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${p.join(", ")}`,400)}try{await(await Xe()).check(r.userId,t.rateLimitConfig||Ye)}catch(p){return F(p instanceof Error?p.message:"Rate limit exceeded",429)}let c;try{c=await Ge(n,a)}catch(p){return F(`Failed to initialize provider: ${p instanceof Error?p.message:String(p)}`,500)}let u=e.messages.filter(p=>p.role==="system").map(p=>p.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
|
|
22
|
-
`):void 0),m=e.messages.filter(p=>p.role!=="system").map(p=>({role:p.role,content:p.content})),f=e.maxTokens||t.maxTokens||4096,h=e.temperature??t.temperature??.7,S=r.requestId||crypto.randomUUID(),U=await import("ai"),{streamText:k,generateText:A}=U,R=ze(U,e.tools,t.tools),C=i(async p=>{if(!r.onCostRecord)return;let w=t.cost?.markup??4,ne=X(p,a,w),Be={userId:r.userId,model:a,provider:n,usage:p,providerCost:ne.providerCost,billedCost:ne.billedCost,markup:w,timestamp:new Date().toISOString(),requestId:S};r.onCostRecord(Be).catch(We=>{console.error("[AI] Failed to record cost:",We)})},"recordCost");if(e.stream!==!1)return k({model:c,messages:m,system:d,maxTokens:f,temperature:h,tools:R,onFinish:i(async({usage:w})=>{await C({promptTokens:w.promptTokens,completionTokens:w.completionTokens,totalTokens:w.promptTokens+w.completionTokens})},"onFinish")}).toDataStreamResponse();let g=await A({model:c,messages:m,system:d,maxTokens:f,temperature:h,tools:R}),_={promptTokens:g.usage.promptTokens,completionTokens:g.usage.completionTokens,totalTokens:g.usage.promptTokens+g.usage.completionTokens};await C(_);let E=g.toolCalls?.map(p=>({id:p.toolCallId,name:p.toolName,args:p.args}))??[];return new Response(JSON.stringify({message:{role:"assistant",content:g.text},usage:_,finishReason:g.finishReason,toolCalls:E.length>0?E:void 0,model:a,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}i(Je,"handleAIRequest");function F(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}i(F,"jsonError");function B(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(B,"getEnv");function Qe(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=B(r);if(n)return n}let o=B("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}i(Qe,"getAIApiKey");function we(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(we,"getEnv");function Ze(e,t){if(t){let n=we(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=we(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(j).find(n=>n.id===e)?.defaultModel??j.STANDARD.defaultModel)}i(Ze,"resolveModelForTier");function et(e){let t=rt(e),r=ot(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:ve(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:ve(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}i(et,"classifyAIError");function tt(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}i(tt,"mapClassifiedToHTTP");function rt(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error?.status=="number")return e.error.status}}i(rt,"extractStatus");function ot(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}i(ot,"extractMessage");function ve(e){if(e&&typeof e=="object"){let t=e.headers;if(t){let r=typeof t.get=="function"?t.get("retry-after"):t["retry-after"];if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}i(ve,"extractRetryAfter");var Se="2025-02-24.acacia";var z=Se,$="orderId",W="productId";function J(e){return e===null?null:typeof e=="string"?e:e.id}i(J,"idOf");function ke(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}i(ke,"toAddress");function nt(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:J(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?ke(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:ke(r.address)}:null,invoiceId:J(e.invoice),paymentIntentId:J(e.payment_intent),metadata:e.metadata??{}}}i(nt,"toCheckoutSessionSnapshot");async function st(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,s=n&&typeof n!="string"&&!n.deleted?n.metadata[W]:void 0;if(!s)throw new Error(`Line item ${o.id} of session ${t} has no ${W} product metadata`);r.push({productId:s,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}i(st,"listPaidLineItems");async function Ie(e,t,r,o,n,s,a){if(!r||r.slice(0,10)<z.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[$]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${z} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${z}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[$];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},f=nt(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let S=await st(a,o.id);await s.onOrderPaid(f,S,m),l.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":l.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":s.onOrderPaymentFailed&&await s.onOrderPaymentFailed(f,m),l.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":s.onOrderExpired&&await s.onOrderExpired(f,m),l.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}i(Ie,"handleOrderSessionEvent");function be(e,t){let{billingConfigKey:r,priceId:o,unitAmount:n,productName:s}=t,[a]=t.lineItems;if(t.lineItems.length!==1||!a||a.productId!==r||a.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let c=!o&&!!n&&!!s,u=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,dynamic:c,mode:u}}if(c){if(u==="subscription")throw new Error("Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.");if(!e.maxUnitAmount)throw new Error("Dynamic pricing requires maxUnitAmount in billing config for security");if(n>e.maxUnitAmount)throw new Error(`Unit amount ${n} exceeds maximum allowed: ${e.maxUnitAmount}`);if(n<100)throw new Error("Unit amount must be at least 100 cents (1.00)");return{dynamic:c,mode:u}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,dynamic:c,mode:u}}i(be,"resolvePricePlan");function Ae(e){let t=e.mode||"payment";return{mode:t,line_items:[e.priceId?{price:e.priceId,quantity:1}:{price_data:{currency:e.currency||"eur",unit_amount:e.unitAmount,product_data:{name:e.productName}},quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}i(Ae,"toStripeSessionParams");var it={maxKeys:50,maxKeyLength:40,maxValueLength:500};function Z(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}i(Z,"validateCheckoutUrl");function Ce(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}i(Ce,"sanitizeMetadata");function ee(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=it,s=Object.entries(e);if(s.length>r)throw new Error(`${t}: ${s.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[a,c]of s){if(a.length>o)throw new Error(`${t}: metadata key '${a}' is too long (max ${o} characters)`);if(/[[\]]/.test(a))throw new Error(`${t}: metadata key '${a}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${a}' is too long (max ${n} characters)`)}}i(ee,"assertStripeMetadata");function te(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&ee(o,r)}i(te,"assertCheckoutSessionMetadata");function Te(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&dt(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`)}}i(Te,"assertResolvedOrder");var at={minSeconds:1800,maxSeconds:1440*60},Re=5e3,ct=["card","sepa_debit"];function dt(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:s,invoiceFooter:a}=e;if(o&&o.some(c=>typeof c!="string"||c.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let c of n)if(!ct.includes(c))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${c}'`)}if(s!==void 0){let{minSeconds:c,maxSeconds:u}=at;if(!Number.isInteger(s)||s<r+c||s>r+u)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${s}`)}if(a!==void 0&&(a.length===0||a.length>Re))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${Re} characters`)}i(dt,"assertResolvedOrderSession");var Q=new Map;async function re(e,t,r){for(let o of t){let n=Q.get(o);if(n||(n=e(o).then(s=>s.inclusive),Q.set(o,n),n.catch(()=>Q.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}i(re,"assertExclusiveTaxRates");function Pe(e){return"createStripeSession"in e}i(Pe,"isSessionProvider");function xe(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}i(xe,"resolveRedirectUrl");function ut(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,s={...r.metadata,[$]:t.orderId};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(a=>({price_data:{currency:e.currency,unit_amount:a.unitAmount,tax_behavior:"exclusive",product_data:{name:a.name,...a.description&&{description:a.description},metadata:{[W]:a.productId}}},quantity:a.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:e.taxIdCollection==="disabled"?{enabled:!1}:{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(a=>({shipping_rate:a}))}},customer_creation:e.customerCreation,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:s,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,customer_email:r.customerEmail,metadata:s,payment_intent_data:{metadata:s}}}i(ut,"buildOrderSessionParams");async function dr(e,...t){let r=t.length===3,[o,n,s,a]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=a[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",f=m?void 0:be(d,u);await s.getUser(o);let h=Ce(u.metadata??{}),S={...h,userId:o,billingConfigKey:c};ee(m?{...S,[$]:""}:S,"metadata");let U=u.allowPromotionCodes??!0,k=u.unitAmount,A=u.productName;if(d.beforeCheckout){let _={...u,userId:o,mode:f?.mode??"payment",priceId:f?.priceId,metadata:u.metadata??{},allowPromotionCodes:U},E=await d.beforeCheckout(o,_,h);if(!E.allowed)throw new Error(E.reason||"Checkout blocked by beforeCheckout hook");f?.dynamic&&E.overrides&&(k=E.overrides.unitAmount??k,A=E.overrides.productName??A)}let R=xe(u.successUrl,"success"),C=xe(u.cancelUrl,"cancel");Z(R,"success"),Z(C,"cancel");let g;if(d.type==="StripeOrder"){if(!Pe(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await re(w=>n.retrieveTaxRate(w),d.tax.taxRateIds,c);let _=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:h});Te(_,c);let E=_.session;if(E?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await re(w=>n.retrieveTaxRate(w),E.taxRateIds,c)}if(E?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let p=ut(d,_,{successUrl:R,cancelUrl:C,customerEmail:u.customerEmail,metadata:S});te(p),g=await n.createStripeSession(p)}else{let _=!!f?.dynamic&&!!k&&!!A;if(_&&d.maxUnitAmount&&k>d.maxUnitAmount)throw new Error(`Hook-overridden unit amount ${k} exceeds maximum allowed: ${d.maxUnitAmount}`);let E={priceId:f?.priceId,unitAmount:_?k:void 0,productName:_?A:void 0,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:S,allowPromotionCodes:U,successUrl:R,cancelUrl:C,mode:f?.mode};if(Pe(n)){let p=Ae(E);te(p),g=await n.createStripeSession(p)}else g=await n.createCheckoutSession(E)}return{sessionId:g.id,sessionUrl:g.url}}i(dr,"createCheckoutAlgorithm");async function pt(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},a={...n,subscription:s};await r.setCustomUserClaims(e,a)}i(pt,"updateUserSubscription");function oe(){if(process.env.FUNCTION_NAME||process.env.FIREBASE_CONFIG)return!0;let e=!!process.env.FIREBASE_PROJECT_ID,t=!!process.env.FIREBASE_CLIENT_EMAIL,r=!!process.env.FIREBASE_PRIVATE_KEY;return e&&t&&r}i(oe,"isFirestoreConfigured");async function yr(){if(!oe())return!1;try{let{getFirebaseAdminFirestore:e}=await import("./server-S2IMFOY7.js");return await e().collection("_health_check").limit(1).get(),!0}catch(e){return console.warn("[Firestore] Not available:",e instanceof Error?e.message:String(e)),!1}}i(yr,"isFirestoreAvailable");var v=class extends Error{static{i(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},x=4200*1e3,K=720*60*60*1e3;function O(){return crypto.randomUUID()}i(O,"newOwnerToken");var lt=`
|
|
23
|
-
CREATE TABLE IF NOT EXISTS public.webhook_events (
|
|
24
|
-
event_id TEXT PRIMARY KEY,
|
|
25
|
-
status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
|
|
26
|
-
owner_token UUID NOT NULL,
|
|
27
|
-
reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
28
|
-
processed_at TIMESTAMPTZ
|
|
29
|
-
);
|
|
30
|
-
|
|
31
|
-
-- Only service_role accesses this table
|
|
32
|
-
ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
|
|
33
|
-
|
|
34
|
-
CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
|
|
35
|
-
ON public.webhook_events (processed_at);
|
|
36
|
-
|
|
37
|
-
-- The functions below run as the caller (SECURITY INVOKER) and refuse every
|
|
38
|
-
-- role but service_role. EXECUTE is deliberately not revoked: on Supabase
|
|
39
|
-
-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
|
|
40
|
-
-- crashes the backend (signal 11), which restarts every connection.
|
|
41
|
-
CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
|
|
42
|
-
RETURNS VOID
|
|
43
|
-
LANGUAGE plpgsql
|
|
44
|
-
SET search_path = public
|
|
45
|
-
AS $$
|
|
46
|
-
BEGIN
|
|
47
|
-
IF current_user IS DISTINCT FROM 'service_role' THEN
|
|
48
|
-
RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
|
|
49
|
-
USING ERRCODE = 'insufficient_privilege';
|
|
50
|
-
END IF;
|
|
51
|
-
END;
|
|
52
|
-
$$;
|
|
53
|
-
|
|
54
|
-
-- Atomic reservation. Returns:
|
|
55
|
-
-- 'reserved' the caller now owns the event under p_owner_token
|
|
56
|
-
-- 'processed' the event was already processed (skip, answer 2xx)
|
|
57
|
-
-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
|
|
58
|
-
-- A 'processing' row older than the lease is retaken (abandoned worker).
|
|
59
|
-
CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
|
|
60
|
-
p_event_id TEXT,
|
|
61
|
-
p_owner_token UUID,
|
|
62
|
-
p_lease_seconds INT
|
|
63
|
-
)
|
|
64
|
-
RETURNS TEXT
|
|
65
|
-
LANGUAGE plpgsql
|
|
66
|
-
SET search_path = public
|
|
67
|
-
AS $$
|
|
68
|
-
DECLARE
|
|
69
|
-
v_status TEXT;
|
|
70
|
-
BEGIN
|
|
71
|
-
PERFORM public.webhook_events_assert_service_role();
|
|
72
|
-
|
|
73
|
-
INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
|
|
74
|
-
VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
|
|
75
|
-
ON CONFLICT (event_id) DO UPDATE
|
|
76
|
-
SET owner_token = EXCLUDED.owner_token,
|
|
77
|
-
reserved_at = clock_timestamp()
|
|
78
|
-
WHERE webhook_events.status = 'processing'
|
|
79
|
-
AND webhook_events.reserved_at
|
|
80
|
-
< clock_timestamp() - make_interval(secs => p_lease_seconds);
|
|
81
|
-
IF FOUND THEN
|
|
82
|
-
RETURN 'reserved';
|
|
83
|
-
END IF;
|
|
84
|
-
|
|
85
|
-
SELECT status INTO v_status
|
|
86
|
-
FROM public.webhook_events
|
|
87
|
-
WHERE event_id = p_event_id;
|
|
88
|
-
IF v_status = 'processed' THEN
|
|
89
|
-
RETURN 'processed';
|
|
90
|
-
END IF;
|
|
91
|
-
-- Live lease, or the row was released in between: Stripe retries either way
|
|
92
|
-
RETURN 'in_progress';
|
|
93
|
-
END;
|
|
94
|
-
$$;
|
|
95
|
-
|
|
96
|
-
-- Mark a reservation processed. Returns false when p_owner_token no longer owns
|
|
97
|
-
-- the row (lease retaken, released, or deleted). Repeating it for the same
|
|
98
|
-
-- owner is a no-op that returns true.
|
|
99
|
-
CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
|
|
100
|
-
p_event_id TEXT,
|
|
101
|
-
p_owner_token UUID
|
|
102
|
-
)
|
|
103
|
-
RETURNS BOOLEAN
|
|
104
|
-
LANGUAGE plpgsql
|
|
105
|
-
SET search_path = public
|
|
106
|
-
AS $$
|
|
107
|
-
BEGIN
|
|
108
|
-
PERFORM public.webhook_events_assert_service_role();
|
|
109
|
-
|
|
110
|
-
UPDATE public.webhook_events
|
|
111
|
-
SET status = 'processed',
|
|
112
|
-
processed_at = COALESCE(processed_at, clock_timestamp())
|
|
113
|
-
WHERE event_id = p_event_id
|
|
114
|
-
AND owner_token = p_owner_token;
|
|
115
|
-
RETURN FOUND;
|
|
116
|
-
END;
|
|
117
|
-
$$;
|
|
118
|
-
|
|
119
|
-
-- Drop a reservation after a processing failure. Returns false when
|
|
120
|
-
-- p_owner_token does not own a 'processing' row (nothing is deleted).
|
|
121
|
-
CREATE OR REPLACE FUNCTION public.webhook_event_release(
|
|
122
|
-
p_event_id TEXT,
|
|
123
|
-
p_owner_token UUID
|
|
124
|
-
)
|
|
125
|
-
RETURNS BOOLEAN
|
|
126
|
-
LANGUAGE plpgsql
|
|
127
|
-
SET search_path = public
|
|
128
|
-
AS $$
|
|
129
|
-
BEGIN
|
|
130
|
-
PERFORM public.webhook_events_assert_service_role();
|
|
131
|
-
|
|
132
|
-
DELETE FROM public.webhook_events
|
|
133
|
-
WHERE event_id = p_event_id
|
|
134
|
-
AND owner_token = p_owner_token
|
|
135
|
-
AND status = 'processing';
|
|
136
|
-
RETURN FOUND;
|
|
137
|
-
END;
|
|
138
|
-
$$;
|
|
139
|
-
|
|
140
|
-
-- Enable pg_cron extension (if not already enabled)
|
|
141
|
-
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
142
|
-
|
|
143
|
-
-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
|
|
144
|
-
-- Stripe retries an event for up to 3 days, so older rows are never read again.
|
|
145
|
-
SELECT cron.schedule(
|
|
146
|
-
'cleanup-webhook-events',
|
|
147
|
-
'0 5 * * *',
|
|
148
|
-
$$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
|
|
149
|
-
);
|
|
150
|
-
`,mt=T(["reserved","processed","in_progress"]),Oe=de();function ft(e){let t=i(async(r,o,n)=>{let{data:s,error:a}=await e.rpc(r,o);if(a)throw y(a);let c=P(n,s);if(!c.success)throw y(new Error(`${r} returned an unexpected result: ${JSON.stringify(s)}`));return c.output},"call");return{async reserve(r){let o=O(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:x/1e3},mt);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Oe))throw new v(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Oe)}}}i(ft,"createSupabaseIdempotencyStore");var Ne="webhook_idempotency";function ht(){let e=new Map,t=i(async r=>{let o=e.get(r),n=Date.now();if(o?.status==="processed")return{state:"processed"};if(o&&n-o.at<x)return{state:"in_progress"};let s=O();return e.set(r,{status:"processing",ownerToken:s,at:n}),{state:"reserved",ownerToken:s}},"reserve");return{reserve:t,async checkAndReserve(r){return(await t(r)).state!=="reserved"},async markProcessed(r,o){let n=e.get(r);if(o!==void 0&&n?.ownerToken!==o)throw new v(r);e.set(r,{status:"processed",ownerToken:o??n?.ownerToken??O(),at:Date.now()})},async release(r,o){let n=e.get(r);return n?.status!=="processing"||n.ownerToken!==o?!1:(e.delete(r),!0)},async isProcessed(r){return e.get(r)?.status==="processed"}}}i(ht,"createInMemoryIdempotencyStore");var yt=me([H(),fe(ue(e=>typeof e=="object"&&e!==null&&typeof e.toMillis=="function","expiresAt must be a Firestore Timestamp or a number"),ce(e=>e.toMillis()))]),Et=pe({status:L(T(["processing","processed"])),ownerToken:L(le()),reservedAt:L(H()),expiresAt:L(yt)});function q(e,t){let r=P(Et,t);if(!r.success)throw new Error(`Malformed ${Ne}/${e}: ${r.issues.map(o=>o.message).join("; ")}`);return r.output}i(q,"parseEventDoc");function gt(){let e=null,t=i(async()=>{e||(e=await import("./server-S2IMFOY7.js"));let o=e.getFirebaseAdminFirestore();return{firestore:o,Timestamp:e.Timestamp,refOf:i(n=>o.collection(Ne).doc(n),"refOf")}},"load"),r=i(async o=>{let{firestore:n,Timestamp:s,refOf:a}=await t(),c=a(o);try{return await n.runTransaction(async u=>{let d=await u.get(c),m=Date.now();if(d.exists){let h=q(o,d.data());if(h.status==="processing"){if(m-(h.reservedAt??0)<x)return{state:"in_progress"}}else if((h.expiresAt??0)>=m)return{state:"processed"}}let f=O();return u.set(c,{eventId:o,status:"processing",ownerToken:f,reservedAt:m,expiresAt:s.fromMillis(m+K)}),{state:"reserved",ownerToken:f}})}catch(u){throw y(u)}},"reserve");return{reserve:r,async checkAndReserve(o){return(await r(o)).state!=="reserved"},async markProcessed(o,n){let{firestore:s,Timestamp:a,refOf:c}=await t(),u=c(o),d=Date.now(),m={eventId:o,status:"processed",processedAt:d,expiresAt:a.fromMillis(d+K)};try{if(n===void 0){await u.set(m);return}await s.runTransaction(async f=>{let h=await f.get(u);if((h.exists?q(o,h.data()):null)?.ownerToken!==n)throw new v(o);f.set(u,{...m,ownerToken:n})})}catch(f){throw f instanceof v?f:y(f)}},async release(o,n){let{firestore:s,refOf:a}=await t(),c=a(o);try{return await s.runTransaction(async u=>{let d=await u.get(c);if(!d.exists)return!1;let m=q(o,d.data());return m.status!=="processing"||m.ownerToken!==n?!1:(u.delete(c),!0)})}catch(u){throw y(u)}},async isProcessed(o){let{refOf:n}=await t();try{let s=await n(o).get();if(!s.exists)return!1;let a=q(o,s.data());return a.status!=="processing"&&(a.expiresAt??0)>=Date.now()}catch(s){throw y(s)}}}}i(gt,"createFirestoreIdempotencyStore");var N=null;function Ue(){return N||(oe()?N=gt():(console.warn("[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store."),N=ht()),N)}i(Ue,"createIdempotencyStore");function Cr(){N=null}i(Cr,"resetIdempotencyStore");async function Me(e,t,r,o,n){let s={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){l.info("[Webhook] Purchase awaiting async payment",{...s,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw y(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await Le(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await Le(t,r,o,n);return;case"checkout.session.async_payment_failed":l.warn("[Webhook] Async purchase payment failed, nothing granted",{...s,operation:"purchase_payment_failed"});return;case"checkout.session.expired":l.debug("[Webhook] Checkout session expired",s);return}}i(Me,"handleTierCheckoutEvent");async function Le(e,t,r,o){let{userId:n,billingConfigKey:s}=e.metadata||{};if(!n||!s)throw y(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${s}`));let a=t[s];if(!a)throw y(new Error(`Unknown billing config key: ${s}`));if(l.info("[Webhook] Processing purchase",{userId:n,configKey:s,type:a.type,operation:"purchase_processing"}),a.type==="StripePayment"){if(!o)throw y(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:M.ACTIVE,subscriptionEnd:D(a.duration),customerId:e.customer},o),a.onPurchaseSuccess)try{await a.onPurchaseSuccess(n,e.metadata||{})}catch(c){l.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(a.type==="StripeSubscription"){if(!o)throw y(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:M.ACTIVE,subscriptionEnd:D(a.duration),subscriptionId:e.subscription,customerId:e.customer},o),a.onSubscriptionCreated)try{await a.onSubscriptionCreated(n,e.metadata||{})}catch(c){l.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}l.info("[Webhook] Purchase processed",{userId:n,configKey:s,operation:"purchase_processed"})}i(Le,"grantCheckoutPurchase");async function $e(e,t,r,o,n){let s=e.subscription;if(!s)return;let a=await o.subscriptions.retrieve(s),{userId:c,billingConfigKey:u}=a.metadata||{};if(!c||!u){l.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:s,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw y(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:M.ACTIVE,subscriptionEnd:D(d.duration),subscriptionId:s,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,a.metadata||{})}catch(m){l.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}l.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}i($e,"handleInvoicePaymentSucceeded");async function De(e,t,r,o){let{userId:n,billingConfigKey:s}=e.metadata||{};if(!n||!s)return;let a=t[s];if(!(!a||a.type!=="StripeSubscription")){if(!o)throw y(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:ye.FREE,status:M.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),a.onSubscriptionCancelled)try{await a.onSubscriptionCancelled(n,e.metadata||{})}catch(c){l.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}l.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:s,operation:"subscription_cancelled"})}}i(De,"handleSubscriptionDeleted");async function Fe(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){l.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){l.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(s){l.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(s){l.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}l.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}i(Fe,"handlePaymentFailed");var _t=3,wt=200;async function Hr(e,t,r,o,n,s,a,c=Ue()){try{Ee(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);l.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return l.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw l.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new b(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:f}=m;a||l.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await kt(d,u,s,o,a)}catch(h){throw l.error("[Webhook] Event processing failed, releasing reservation",{error:h instanceof Error?h:new Error(String(h)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await vt(c,d.id,f),h}return await St(c,d.id,f),{success:!0,message:"Webhook processed"}}catch(u){throw y(u)}}i(Hr,"processWebhook");async function vt(e,t,r){try{await e.release(t,r)||l.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){l.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}i(vt,"releaseReservation");async function St(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let s=n instanceof Error?n:new Error(String(n));if(n instanceof v)throw l.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:s,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=_t)throw l.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:s,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;l.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:s.message}),await new Promise(a=>setTimeout(a,wt*o))}}i(St,"markProcessedWithRetry");async function kt(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await It(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await $e(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await De(e.data.object,t,r,n);break;case"invoice.payment_failed":await Fe(e.data.object,t);break;default:l.debug("[Webhook] Unhandled event type",{type:e.type})}}i(kt,"routeEvent");async function It(e,t,r,o,n,s,a,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await Ie(e,t,r,o,u,d,a);return}await Me(e,o,n,s,c)}i(It,"handleCheckoutSessionEvent");export{y as a,ge as b,Tt as c,Ke as d,Pt as e,je as f,Ve as g,xt as h,X as i,Je as j,Ze as k,et as l,tt as m,te as n,Se as o,z as p,$ as q,W as r,nt as s,st as t,Ie as u,dr as v,pt as w,oe as x,yr as y,v as z,x as A,K as B,lt as C,ft as D,ht as E,gt as F,Ue as G,Cr as H,Hr as I};
|
|
151
|
-
//# sourceMappingURL=chunk-2JL3GDTO.js.map
|