@donotdev/functions 0.2.0 → 0.2.2
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/README.md +1 -1
- package/lib/chunks/{chunk-JTAGPPPL.js → chunk-2A4FPYNB.js} +2 -2
- package/lib/chunks/chunk-2IFFIUFV.js +23 -0
- package/lib/chunks/{chunk-RM7DV6IQ.js.map → chunk-2IFFIUFV.js.map} +3 -3
- package/lib/chunks/chunk-FQSQGOBN.js +22 -0
- package/lib/chunks/chunk-FQSQGOBN.js.map +7 -0
- package/lib/chunks/chunk-G4FO76EA.js +22 -0
- package/lib/chunks/{chunk-5DTPEM64.js.map → chunk-G4FO76EA.js.map} +3 -3
- package/lib/chunks/{chunk-QJAU2MWV.js → chunk-LSM5Y2E5.js} +2 -2
- package/lib/chunks/{chunk-QJAU2MWV.js.map → chunk-LSM5Y2E5.js.map} +3 -3
- package/lib/chunks/{chunk-4U7QQWYG.js → chunk-M4JV2JCF.js} +2 -2
- package/lib/chunks/chunk-OZX5ZG44.js +22 -0
- package/lib/chunks/chunk-OZX5ZG44.js.map +7 -0
- package/lib/chunks/{chunk-IFOYVSPU.js → chunk-PJCJ5H2O.js} +2 -2
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/chunk-UYI56E6Q.js +151 -0
- package/lib/chunks/chunk-UYI56E6Q.js.map +7 -0
- package/lib/chunks/chunk-ZVHC2CAV.js +22 -0
- package/lib/chunks/chunk-ZVHC2CAV.js.map +7 -0
- package/lib/chunks/{monitoring-AGCSU3FI.js → monitoring-UIDJS2KA.js} +2 -2
- package/lib/chunks/{rateLimiter-6KO7AIZP.js → rateLimiter-WNWHI3B4.js} +2 -2
- package/lib/chunks/server-RYGEBS2B.js +22 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
- package/lib/firebase/baseFunction.d.ts +0 -0
- package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +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 +2 -2
- 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 +1 -1
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +0 -0
- package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
- package/lib/firebase/oauth/getConnections.d.ts +0 -0
- package/lib/firebase/oauth/githubAccess.d.ts +0 -0
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +0 -5
- 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/checkoutPrice.d.ts +3 -6
- package/lib/shared/billing/createCheckout.d.ts +3 -3
- 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 +4 -35
- package/lib/shared/billing/idempotencyContract.d.ts +0 -20
- 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 +1 -5
- 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 -126
- 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/baseFunction.ts +3 -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/index.d.ts +0 -12
- package/src/firebase/billing/index.ts +0 -3
- package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
- package/src/firebase/billing/webhookHandler.ts +2 -2
- package/src/firebase/index.ts +0 -1
- package/src/firebase/oauth/disconnect.ts +2 -2
- package/src/firebase/oauth/exchangeToken.ts +2 -2
- package/src/firebase/oauth/getConnections.ts +2 -2
- package/src/firebase/oauth/githubAccess.ts +4 -4
- package/src/firebase/oauth/refreshToken.ts +2 -2
- package/src/firebase/registerCrudFunctions.ts +0 -19
- package/src/shared/__tests__/idempotency.test.ts +0 -32
- 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 -26
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
- package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -38
- package/src/shared/billing/checkoutPrice.ts +7 -42
- package/src/shared/billing/createCheckout.ts +3 -19
- package/src/shared/billing/firestoreIdempotency.ts +170 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +1 -1
- package/src/shared/billing/idempotency.ts +8 -225
- package/src/shared/billing/idempotencyContract.ts +0 -21
- 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/auth.ts +1 -6
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils.ts +0 -208
- 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-5DTPEM64.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-BUP7SXPV.js.map +0 -7
- 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 +0 -23
- 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-UH4L3EF3.js.map +0 -7
- 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 +0 -22
- 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-4TVLH2W2.js.map → chunk-2A4FPYNB.js.map} +0 -0
- /package/lib/chunks/{chunk-4U7QQWYG.js.map → chunk-M4JV2JCF.js.map} +0 -0
- /package/lib/chunks/{chunk-7LT32OWE.js.map → chunk-PJCJ5H2O.js.map} +0 -0
- /package/lib/chunks/{chunk-FSLGZD7A.js.map → monitoring-UIDJS2KA.js.map} +0 -0
- /package/lib/chunks/{monitoring-AGCSU3FI.js.map → rateLimiter-WNWHI3B4.js.map} +0 -0
- /package/lib/chunks/{monitoring-PVQMFL34.js.map → server-RYGEBS2B.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/utils/internal/auth.ts", "../../src/shared/billing/firestoreIdempotency.ts", "../../src/shared/billing/idempotency.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/utils/internal/auth.ts\n\n/**\n * @fileoverview Authentication utility functions\n * @description Provider-agnostic functions for user authentication and authorization.\n * Uses IServerAuthAdapter from provider registry when configured, falls back to Firebase Admin SDK.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type { NextApiRequest } from 'next';\nimport * as v from 'valibot';\n\nimport { DoNotDevError, hasProvider, getProvider } from '@donotdev/core/server';\n\n/**\n * Auth backends a server function can be explicitly configured with.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const AuthBackendSchema = v.picklist(['firebase', 'supabase']);\n\n/** Auth provider type for explicit configuration */\nexport type AuthProvider = v.InferOutput<typeof AuthBackendSchema>;\n\n/**\n * Validate an auth backend at runtime. Values typed as `AuthProvider` can\n * still arrive as arbitrary strings from JS or env-driven config, and an\n * unknown value must never silently run as Firebase.\n *\n * @param backend - Value to validate\n * @returns The validated backend\n * @throws DoNotDevError (`invalid-argument`) naming the allowed values\n *\n * @example\n * ```typescript\n * const backend = parseAuthBackend(process.env.AUTH_BACKEND); // 'firebase' | 'supabase'\n * ```\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function parseAuthBackend(backend: unknown): AuthProvider {\n const result = v.safeParse(AuthBackendSchema, backend);\n if (!result.success) {\n const allowed = AuthBackendSchema.options.map((o) => `'${o}'`).join(', ');\n throw new DoNotDevError(\n `Invalid backend ${JSON.stringify(backend)}: expected one of ${allowed}`,\n 'invalid-argument'\n );\n }\n return result.output;\n}\n\n// IMPORTANT: Don't call getAuth() at module load - breaks Firebase deployment\n\n/**\n * Firebase Admin Auth, loaded on first use. `firebase-admin` is an optional\n * peer: Supabase deployments never load it.\n */\nasync function getFirebaseAuth() {\n const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');\n return getFirebaseAdminAuth();\n}\n\n/**\n * Validates that user is authenticated\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function assertAuthenticated(uid: string | undefined): string {\n // G62: Validate uid is a non-empty string \u2014 reject non-string values at runtime\n if (!uid || typeof uid !== 'string') {\n throw new Error('Authentication required');\n }\n return uid;\n}\n\n/**\n * Validates that user has admin privileges.\n * Uses IServerAuthAdapter when configured, falls back to Firebase Admin SDK.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function assertAdmin(uid: string): Promise<string> {\n assertAuthenticated(uid);\n\n try {\n let claims: Record<string, unknown> = {};\n\n if (hasProvider('serverAuth')) {\n const user = await getProvider('serverAuth').getUser(uid);\n claims = (user?.customClaims as Record<string, unknown>) ?? {};\n } else {\n // Legacy Firebase path\n const user = await (await getFirebaseAuth()).getUser(uid);\n claims = user.customClaims ?? {};\n }\n\n // W8: Unified role-check logic consistent with shared/utils.ts:assertAdmin.\n // Check role string first (standard), then legacy boolean flags.\n const role = claims.role;\n const isAdmin =\n role === 'admin' ||\n role === 'super' ||\n claims.isAdmin === true ||\n claims.isSuper === true;\n\n if (!isAdmin) {\n throw new Error('Admin privileges required');\n }\n\n return uid;\n } catch (error) {\n // C4: Re-throw permission-denied as-is so callers can distinguish it from\n // infrastructure failures. Only wrap genuine unexpected errors.\n if (\n error instanceof Error &&\n error.message === 'Admin privileges required'\n ) {\n throw error;\n }\n throw new Error('Failed to verify admin status');\n }\n}\n\n/**\n * Extract Bearer token from authorization header.\n *\n * @version 0.1.0\n * @since 0.5.0\n * @author AMBROISE PARK Consulting\n */\nfunction extractBearerToken(authHeader: string | undefined): string {\n if (!authHeader || !authHeader.startsWith('Bearer ')) {\n throw new Error('Missing or invalid authorization header');\n }\n\n const token = authHeader.split('Bearer ')[1];\n\n if (!token) {\n throw new Error('Missing token in authorization header');\n }\n\n return token;\n}\n\n/**\n * Verify a Bearer token using the specified auth provider.\n * Returns `{ uid: string }` on success, throws on failure.\n *\n * Provider resolution order:\n * 1. Explicit `provider` parameter ('firebase' | 'supabase')\n * 2. Provider registry (IServerAuthAdapter via `hasProvider('serverAuth')`)\n * 3. Firebase Admin SDK fallback\n *\n * @param token - Raw JWT token (without \"Bearer \" prefix)\n * @param provider - Optional explicit auth provider\n * @returns Object with verified user's uid\n *\n * @version 0.1.0\n * @since 0.5.0\n * @author AMBROISE PARK Consulting\n */\nexport async function verifyToken(\n token: string,\n provider?: AuthProvider\n): Promise<{ uid: string }> {\n try {\n // Explicit provider\n if (provider === 'supabase') {\n return await verifySupabaseToken(token);\n }\n\n if (provider === 'firebase') {\n const decodedToken = await (await getFirebaseAuth()).verifyIdToken(token);\n return { uid: decodedToken.uid };\n }\n\n // Auto-detect: provider registry first, then Firebase fallback\n if (hasProvider('serverAuth')) {\n const verified = await getProvider('serverAuth').verifyToken(token);\n return { uid: verified.uid };\n }\n\n // Legacy Firebase path\n const decodedToken = await (await getFirebaseAuth()).verifyIdToken(token);\n return { uid: decodedToken.uid };\n } catch (error) {\n throw new Error('Invalid or expired token');\n }\n}\n\n/**\n * Verify a Supabase JWT token using the Supabase admin client.\n * Requires SUPABASE_URL and SUPABASE_SECRET_KEY (or SUPABASE_SERVICE_ROLE_KEY) env vars.\n *\n * @version 0.1.0\n * @since 0.5.0\n * @author AMBROISE PARK Consulting\n */\nasync function verifySupabaseToken(token: string): Promise<{ uid: string }> {\n // Lazy import to avoid pulling in @supabase/supabase-js when using Firebase\n const { createClient } = await import('@supabase/supabase-js');\n\n const supabaseUrl = process.env.SUPABASE_URL;\n const secretKey =\n process.env.SUPABASE_SECRET_KEY || process.env.SUPABASE_SERVICE_ROLE_KEY;\n\n if (!supabaseUrl || !secretKey) {\n throw new Error(\n 'Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables'\n );\n }\n\n const supabaseAdmin = createClient(supabaseUrl, secretKey, {\n auth: { autoRefreshToken: false, persistSession: false },\n });\n\n const {\n data: { user },\n error,\n } = await supabaseAdmin.auth.getUser(token);\n\n if (error || !user) {\n throw new Error('Invalid or expired token');\n }\n\n return { uid: user.id };\n}\n\n/**\n * Verifies auth token from request.\n * Uses IServerAuthAdapter when configured, falls back to Firebase Admin SDK.\n *\n * @param req - Next.js API request\n * @param provider - Optional explicit auth provider ('firebase' | 'supabase')\n * @returns Verified user's uid\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function verifyAuthToken(\n req: NextApiRequest,\n provider?: AuthProvider\n): Promise<string> {\n const token = extractBearerToken(req.headers.authorization);\n const { uid } = await verifyToken(token, provider);\n return uid;\n}\n", "// packages/functions/src/shared/billing/firestoreIdempotency.ts\n\n/**\n * @fileoverview Firestore webhook idempotency store\n * @description `webhook_idempotency` collection, transactional reservations.\n * Used by the Firebase and Vercel (Firestore backend) webhook entry points.\n * Re-exported from `idempotency.ts`. Loads `@donotdev/firebase/server` on\n * first use only.\n *\n * @version 0.2.1\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport { handleError } from '../errorHandling.js';\nimport {\n RESERVATION_LEASE_MS,\n ReservationLostError,\n WEBHOOK_EVENT_RETENTION_MS,\n newOwnerToken,\n} from './idempotencyContract.js';\nimport type {\n IdempotencyStore,\n ReservationResult,\n} from './idempotencyContract.js';\n\n/** Firestore collection holding webhook event reservations (name kept from 0.1.x). */\nconst FIRESTORE_COLLECTION = 'webhook_idempotency';\n\n/** Millisecond reading of an `expiresAt` value: Timestamp (0.2.x) or number (0.1.x). */\nconst ExpiresAtSchema = v.union([\n v.number(),\n v.pipe(\n v.custom<{ toMillis(): number }>(\n (value) =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { toMillis?: unknown }).toMillis === 'function',\n 'expiresAt must be a Firestore Timestamp or a number'\n ),\n v.transform((timestamp) => timestamp.toMillis())\n ),\n]);\n\n/**\n * Stored reservation document. 0.1.x documents carry no `status` and mean processed.\n */\nconst FirestoreEventDocSchema = v.object({\n status: v.optional(v.picklist(['processing', 'processed'])),\n ownerToken: v.optional(v.string()),\n reservedAt: v.optional(v.number()),\n expiresAt: v.optional(ExpiresAtSchema),\n});\n\nfunction parseEventDoc(eventId: string, data: unknown) {\n const result = v.safeParse(FirestoreEventDocSchema, data);\n if (!result.success) {\n throw new Error(\n `Malformed ${FIRESTORE_COLLECTION}/${eventId}: ${result.issues.map((issue) => issue.message).join('; ')}`\n );\n }\n return result.output;\n}\n\n/**\n * Firestore-backed store (transactions). Collection: `webhook_idempotency`.\n *\n * `expiresAt` is a Firestore Timestamp {@link WEBHOOK_EVENT_RETENTION_MS} after\n * the last write: enable a TTL policy on `webhook_idempotency.expiresAt` so\n * Firestore deletes old documents.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function createFirestoreIdempotencyStore(): IdempotencyStore {\n let firebase: typeof import('@donotdev/firebase/server') | null = null;\n const load = async () => {\n if (!firebase) firebase = await import('@donotdev/firebase/server');\n const firestore = firebase.getFirebaseAdminFirestore();\n return {\n firestore,\n Timestamp: firebase.Timestamp,\n refOf: (eventId: string) =>\n firestore.collection(FIRESTORE_COLLECTION).doc(eventId),\n };\n };\n\n const reserve = async (eventId: string): Promise<ReservationResult> => {\n const { firestore, Timestamp, refOf } = await load();\n const ref = refOf(eventId);\n try {\n return await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref);\n const now = Date.now();\n if (snapshot.exists) {\n const data = parseEventDoc(eventId, snapshot.data());\n if (data.status === 'processing') {\n if (now - (data.reservedAt ?? 0) < RESERVATION_LEASE_MS) {\n return { state: 'in_progress' } as const;\n }\n } else if ((data.expiresAt ?? 0) >= now) {\n return { state: 'processed' } as const;\n }\n }\n const ownerToken = newOwnerToken();\n tx.set(ref, {\n eventId,\n status: 'processing',\n ownerToken,\n reservedAt: now,\n expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),\n });\n return { state: 'reserved', ownerToken } as const;\n });\n } catch (error) {\n throw handleError(error);\n }\n };\n\n return {\n reserve,\n async markProcessed(eventId, ownerToken) {\n const { firestore, Timestamp, refOf } = await load();\n const ref = refOf(eventId);\n const now = Date.now();\n const processed = {\n eventId,\n status: 'processed',\n processedAt: now,\n expiresAt: Timestamp.fromMillis(now + WEBHOOK_EVENT_RETENTION_MS),\n };\n try {\n await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref);\n const data = snapshot.exists\n ? parseEventDoc(eventId, snapshot.data())\n : null;\n if (data?.ownerToken !== ownerToken) {\n throw new ReservationLostError(eventId);\n }\n tx.set(ref, { ...processed, ownerToken });\n });\n } catch (error) {\n if (error instanceof ReservationLostError) throw error;\n throw handleError(error);\n }\n },\n async release(eventId, ownerToken) {\n const { firestore, refOf } = await load();\n const ref = refOf(eventId);\n try {\n return await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref);\n if (!snapshot.exists) return false;\n const data = parseEventDoc(eventId, snapshot.data());\n if (data.status !== 'processing' || data.ownerToken !== ownerToken) {\n return false;\n }\n tx.delete(ref);\n return true;\n });\n } catch (error) {\n throw handleError(error);\n }\n },\n };\n}\n", "// packages/functions/src/shared/billing/idempotency.ts\n\n/**\n * @fileoverview Webhook idempotency stores\n * @description Durable, atomic event reservation for Stripe webhooks. Every\n * webhook entry point passes the store that matches its backend: Firestore\n * (Firebase, Vercel: `firestoreIdempotency.ts`) or Postgres (Supabase:\n * `supabaseIdempotency.ts`). There is no implicit fallback. This module\n * aggregates the stores; backend entry points import their own store file.\n *\n * Lifecycle per event: `reserve` \u2192 process \u2192 `markProcessed(ownerToken)`, or\n * `release(ownerToken)` when processing failed (so the provider's retry is\n * processed). Only the owner of a reservation may change it. A reservation\n * whose worker died is retaken after {@link RESERVATION_LEASE_MS}.\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport {\n RESERVATION_LEASE_MS,\n ReservationLostError,\n newOwnerToken,\n} from './idempotencyContract.js';\nimport type {\n IdempotencyStore,\n ReservationResult,\n} from './idempotencyContract.js';\n\nexport {\n RESERVATION_LEASE_MS,\n ReservationLostError,\n WEBHOOK_EVENT_RETENTION_MS,\n} from './idempotencyContract.js';\nexport type {\n IdempotencyStore,\n ReservationResult,\n} from './idempotencyContract.js';\nexport { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';\n\n// =============================================================================\n// In-memory (tests only)\n// =============================================================================\n\n/**\n * In-memory store. Single process only: for tests, never for a deployed webhook.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function createInMemoryIdempotencyStore(): IdempotencyStore {\n const events = new Map<\n string,\n { status: 'processing' | 'processed'; ownerToken: string; at: number }\n >();\n const reserve = async (eventId: string): Promise<ReservationResult> => {\n const entry = events.get(eventId);\n const now = Date.now();\n if (entry?.status === 'processed') return { state: 'processed' };\n if (entry && now - entry.at < RESERVATION_LEASE_MS) {\n return { state: 'in_progress' };\n }\n const ownerToken = newOwnerToken();\n events.set(eventId, { status: 'processing', ownerToken, at: now });\n return { state: 'reserved', ownerToken };\n };\n return {\n reserve,\n async markProcessed(eventId, ownerToken) {\n const entry = events.get(eventId);\n if (entry?.ownerToken !== ownerToken) {\n throw new ReservationLostError(eventId);\n }\n events.set(eventId, {\n status: 'processed',\n ownerToken,\n at: Date.now(),\n });\n },\n async release(eventId, ownerToken) {\n const entry = events.get(eventId);\n if (entry?.status !== 'processing' || entry.ownerToken !== ownerToken) {\n return false;\n }\n events.delete(eventId);\n return true;\n },\n };\n}\n\nexport {\n WEBHOOK_EVENTS_SQL,\n createSupabaseIdempotencyStore,\n} from './supabaseIdempotency.js';\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;wOAwBO,IAAMA,EAAsBC,EAAS,CAAC,WAAY,UAAU,CAAC,EAuB7D,SAASC,EAAiBC,EAAgC,CAC/D,IAAMC,EAAWC,EAAUL,EAAmBG,CAAO,EACrD,GAAI,CAACC,EAAO,QAAS,CACnB,IAAME,EAAUN,EAAkB,QAAQ,IAAKO,GAAM,IAAIA,CAAC,GAAG,EAAE,KAAK,IAAI,EACxE,MAAM,IAAIC,EACR,mBAAmB,KAAK,UAAUL,CAAO,CAAC,qBAAqBG,CAAO,GACtE,kBACF,CACF,CACA,OAAOF,EAAO,MAChB,CAVgBK,EAAAP,EAAA,oBAkBhB,eAAeQ,GAAkB,CAC/B,GAAM,CAAE,qBAAAC,CAAqB,EAAI,KAAM,QAAO,sBAA2B,EACzE,OAAOA,EAAqB,CAC9B,CAHeF,EAAAC,EAAA,mBAYR,SAASE,EAAoBC,EAAiC,CAEnE,GAAI,CAACA,GAAO,OAAOA,GAAQ,SACzB,MAAM,IAAI,MAAM,yBAAyB,EAE3C,OAAOA,CACT,CANgBJ,EAAAG,EAAA,uBAgBhB,eAAsBE,EAAYD,EAA8B,CAC9DD,EAAoBC,CAAG,EAEvB,GAAI,CACF,IAAIE,EAAkC,CAAC,EAEnCC,EAAY,YAAY,EAE1BD,GADa,MAAME,EAAY,YAAY,EAAE,QAAQJ,CAAG,IACxC,cAA4C,CAAC,EAI7DE,GADa,MAAO,MAAML,EAAgB,GAAG,QAAQG,CAAG,GAC1C,cAAgB,CAAC,EAKjC,IAAMK,EAAOH,EAAO,KAOpB,GAAI,EALFG,IAAS,SACTA,IAAS,SACTH,EAAO,UAAY,IACnBA,EAAO,UAAY,IAGnB,MAAM,IAAI,MAAM,2BAA2B,EAG7C,OAAOF,CACT,OAASM,EAAO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IE,EAAS,CAClB,OAAQ,YACR,WAAAI,EACA,GAAI,KAAK,IAAI,CACf,CAAC,CACH,EACA,MAAM,QAAQJ,EAASI,EAAY,CACjC,IAAMH,EAAQH,EAAO,IAAIE,CAAO,EAChC,OAAIC,GAAO,SAAW,cAAgBA,EAAM,aAAeG,EAClD,IAETN,EAAO,OAAOE,CAAO,EACd,GACT,CACF,CACF,CAtCgBD,EAAAF,GAAA",
|
|
6
|
+
"names": ["AuthBackendSchema", "picklist", "parseAuthBackend", "backend", "result", "safeParse", "allowed", "o", "DoNotDevError", "__name", "getFirebaseAuth", "getFirebaseAdminAuth", "assertAuthenticated", "uid", "assertAdmin", "claims", "hasProvider", "getProvider", "role", "error", "extractBearerToken", "authHeader", "token", "verifyToken", "provider", "verifySupabaseToken", "createClient", "supabaseUrl", "secretKey", "supabaseAdmin", "user", "verifyAuthToken", "req", "FIRESTORE_COLLECTION", "ExpiresAtSchema", "union", "number", "pipe", "custom", "value", "transform", "timestamp", "FirestoreEventDocSchema", "object", "optional", "picklist", "string", "parseEventDoc", "eventId", "data", "result", "safeParse", "issue", "__name", "createFirestoreIdempotencyStore", "firebase", "load", "firestore", "Timestamp", "refOf", "ref", "tx", "snapshot", "now", "RESERVATION_LEASE_MS", "ownerToken", "newOwnerToken", "WEBHOOK_EVENT_RETENTION_MS", "error", "handleError", "processed", "ReservationLostError", "createInMemoryIdempotencyStore", "events", "__name", "eventId", "entry", "now", "RESERVATION_LEASE_MS", "ownerToken", "newOwnerToken", "ReservationLostError"]
|
|
7
|
+
}
|
|
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{a as l}from"./chunk-
|
|
22
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
import{a as l}from"./chunk-PWAGW4R6.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-RYGEBS2B.js");return i()}o(u,"getFirestore");var s=new Map;async function p(i,e){let a=Date.now(),n=s.get(i);if(n?.blockUntil&&a<n.blockUntil)return{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)};n&&a>=n.windowStart+e.windowMs&&s.delete(i);let t=s.get(i)||{attempts:0,windowStart:a,blockUntil:null};return t.attempts>=e.maxAttempts?(t.blockUntil=a+e.blockDurationMs,s.set(i,t),l.warn("Rate limit exceeded",{key:i,attempts:t.attempts,blockUntil:new Date(t.blockUntil)}),{allowed:!1,remaining:0,resetAt:new Date(t.blockUntil),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)}):(t.attempts+=1,s.set(i,t),{allowed:!0,remaining:e.maxAttempts-t.attempts,resetAt:new Date(t.windowStart+e.windowMs),blockRemainingSeconds:null})}o(p,"checkRateLimit");async function R(i,e){let a=await u(),n=a.collection("rateLimits").doc(i);try{let t=Date.now(),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return await a.runTransaction(async c=>{let d=await c.get(n);if(!d.exists){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}let r=d.data();if(r.blockUntil&&t<r.blockUntil){m={allowed:!1,remaining:0,resetAt:new Date(r.blockUntil),blockRemainingSeconds:Math.ceil((r.blockUntil-t)/1e3)};return}if(t>=r.windowStart+e.windowMs){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}if(r.attempts>=e.maxAttempts){let w=t+e.blockDurationMs;c.update(n,{blockUntil:w,lastUpdated:t}),l.warn("Rate limit exceeded (Firestore)",{key:i,attempts:r.attempts,blockUntil:new Date(w)}),m={allowed:!1,remaining:0,resetAt:new Date(w),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)};return}c.update(n,{attempts:r.attempts+1,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-(r.attempts+1),resetAt:new Date(r.windowStart+e.windowMs),blockRemainingSeconds:null}}),m}catch(t){return l.error("Rate limit check failed",{key:i,error:t instanceof Error?t.message:String(t)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}o(R,"checkRateLimitWithFirestore");function k(i){s.delete(i),l.info("Rate limit reset",{key:i})}o(k,"resetRateLimit");async function g(i){let a=(await u()).collection("rateLimits").doc(i);try{await a.delete(),l.info("Rate limit reset (Firestore)",{key:i})}catch(n){l.error("Failed to reset rate limit",{key:i,error:n instanceof Error?n.message:String(n)})}}o(g,"resetRateLimitInFirestore");function A(i,e){let a=Date.now(),n=s.get(i);return n?n.blockUntil&&a<n.blockUntil?{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)}:a>=n.windowStart+e.windowMs?{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}:{allowed:n.attempts<e.maxAttempts,remaining:Math.max(0,e.maxAttempts-n.attempts),resetAt:new Date(n.windowStart+e.windowMs),blockRemainingSeconds:null}:{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}}o(A,"getRateLimitStatus");var S={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};export{p as a,R as b,k as c,g as d,A as e,S as f};
|
|
22
|
+
//# sourceMappingURL=chunk-PJCJ5H2O.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
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 g}from"./chunk-AYY7UXNI.js";var y=typeof process<"u"&&!!process.versions?.node,a=!1,i=null,c=!1;async function l(){if(!c)try{let e=process.env.SENTRY_DSN;if(e){let{init:r,captureException:n,captureMessage:t}=await import("@sentry/node");r({dsn:e,environment:"production"}),i={captureException:n,captureMessage:t},a=!0}}catch{a=!1}finally{c=!0}}g(l,"initializeSentry");var d=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.FATAL=4]="FATAL",o))(d||{}),f={debug(e,r){this.log(0,e,r)},info(e,r){this.log(1,e,r)},warn(e,r){this.log(2,e,r)},async error(e,r){if(this.log(3,e,r),c||await l(),a&&i)try{r?.error instanceof Error?i.captureException(r.error):i.captureMessage(e,"error")}catch(n){console.error("Sentry error:",n)}},async fatal(e,r){if(this.log(4,e,r),c||await l(),a&&i)try{r?.error instanceof Error?i.captureException(r.error):i.captureMessage(e,"fatal")}catch(n){console.error("Sentry error:",n)}},log(e,r,n){let t=new Date().toISOString(),R={level:e,message:r,timestamp:t,context:n,error:n?.error,metadata:{...y?{pid:process.pid,nodeVersion:process.version,platform:process.platform}:{},...n?.metadata}},o=d[e],s=n?` ${JSON.stringify(n)}`:"";switch(e){case 0:console.debug(`[${t}] [DEBUG] ${r}${s}`);break;case 1:console.info(`[${t}] [INFO] ${r}${s}`);break;case 2:console.warn(`[${t}] [WARN] ${r}${s}`);break;case 3:console.error(`[${t}] [ERROR] ${r}${s}`);break;case 4:console.error(`[${t}] [FATAL] ${r}${s}`);break}},isSentryEnabled(){return a},getLevel(){return 0}};export{f as a};
|
|
22
|
+
//# sourceMappingURL=chunk-PWAGW4R6.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/logger.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/logger.ts\n\n/**\n * @fileoverview Server-side logging utility with Sentry integration\n * @description Structured logging for server environments with Sentry integration\n *\n * Sentry Integration:\n * - Uses @sentry/node for backend error tracking\n * - Automatically detects if Sentry is installed\n * - Works with or without Sentry (graceful degradation)\n * - Consumer must install @sentry/node and set SENTRY_DSN env var\n *\n * Usage:\n * ```typescript\n * import { logger } from '../shared/logger.js';\n *\n * logger.info('Server started', { port: 3000 });\n * logger.error('Database connection failed', { error: err });\n * ```\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n// Node-only metadata (pid, version) is added when running on Node; Deno runtimes\n// (Supabase Edge) log without it. Server-only by package: @donotdev/functions is\n// never imported by client code, so no runtime browser check (Supabase Edge\n// defines `window`, which made such a check throw on every edge function).\nconst _isNodeEnv = typeof process !== 'undefined' && !!process.versions?.node;\n\nlet sentryEnabled = false;\nlet sentryClient: any = null;\n\n// Initialize Sentry lazily to avoid Firebase Functions issues\nlet sentryInitialized = false;\n\n/**\n * Initialize Sentry if not already done\n * Called lazily to avoid Firebase Functions issues\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nasync function initializeSentry(): Promise<void> {\n if (sentryInitialized) return;\n\n try {\n // Check if Sentry is available (consumer must install @sentry/node)\n const sentryDsn = process.env.SENTRY_DSN;\n if (sentryDsn) {\n // Dynamic import to avoid build errors if @sentry/node is not installed\n const { init, captureException, captureMessage } =\n await import('@sentry/node');\n\n init({\n dsn: sentryDsn,\n environment: process.env.NODE_ENV || 'development',\n });\n\n sentryClient = { captureException, captureMessage };\n sentryEnabled = true;\n }\n } catch (error) {\n // Sentry not available, continue without it\n sentryEnabled = false;\n } finally {\n sentryInitialized = true;\n }\n}\n\n/**\n * Log levels for structured logging\n */\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n FATAL = 4,\n}\n\n/**\n * Log entry interface for structured logging\n */\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: string;\n context?: Record<string, any>;\n error?: Error;\n metadata?: Record<string, any>;\n}\n\n/**\n * Server-side logger with Sentry integration\n *\n * Features:\n * - Structured logging with context\n * - Automatic Sentry error reporting\n * - Performance monitoring\n * - Request correlation\n *\n * @example\n * ```typescript\n * import { logger } from '../shared/logger.js';\n *\n * // Basic logging\n * logger.info('Server started', { port: 3000 });\n *\n * // Error logging with Sentry\n * logger.error('Database error', { error: err, query: 'SELECT * FROM users' });\n *\n * // Performance logging\n * logger.info('Request completed', {\n * duration: 150,\n * status: 200,\n * path: '/api/users'\n * });\n * ```\n */\nexport const logger = {\n /**\n * Log debug information\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n debug(message: string, context?: Record<string, any>): void {\n this.log(LogLevel.DEBUG, message, context);\n },\n\n /**\n * Log informational messages\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n info(message: string, context?: Record<string, any>): void {\n this.log(LogLevel.INFO, message, context);\n },\n\n /**\n * Log warning messages\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n warn(message: string, context?: Record<string, any>): void {\n this.log(LogLevel.WARN, message, context);\n },\n\n /**\n * Log error messages with Sentry integration\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async error(message: string, context?: Record<string, any>): Promise<void> {\n this.log(LogLevel.ERROR, message, context);\n\n // Initialize Sentry lazily if needed\n if (!sentryInitialized) {\n await initializeSentry();\n }\n\n // Send to Sentry if available\n if (sentryEnabled && sentryClient) {\n try {\n if (context?.error instanceof Error) {\n sentryClient.captureException(context.error);\n } else {\n sentryClient.captureMessage(message, 'error');\n }\n } catch (sentryError) {\n // Don't let Sentry errors break logging\n console.error('Sentry error:', sentryError);\n }\n }\n },\n\n /**\n * Log fatal errors with Sentry integration\n * @param message - Log message\n * @param context - Additional context data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async fatal(message: string, context?: Record<string, any>): Promise<void> {\n this.log(LogLevel.FATAL, message, context);\n\n // Initialize Sentry lazily if needed\n if (!sentryInitialized) {\n await initializeSentry();\n }\n\n // Send to Sentry if available\n if (sentryEnabled && sentryClient) {\n try {\n if (context?.error instanceof Error) {\n sentryClient.captureException(context.error);\n } else {\n sentryClient.captureMessage(message, 'fatal');\n }\n } catch (sentryError) {\n // Don't let Sentry errors break logging\n console.error('Sentry error:', sentryError);\n }\n }\n },\n\n /**\n * Core logging method\n * @param level - Log level\n * @param message - Log message\n * @param context - Additional context data\n *\n * @security Callers MUST NOT pass secrets (tokens, passwords, API keys) in context. Context is logged in plaintext.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n log(level: LogLevel, message: string, context?: Record<string, any>): void {\n const timestamp = new Date().toISOString();\n const logEntry: LogEntry = {\n level,\n message,\n timestamp,\n context,\n error: context?.error,\n metadata: {\n ...(_isNodeEnv\n ? {\n pid: process.pid,\n nodeVersion: process.version,\n platform: process.platform,\n }\n : {}),\n ...context?.metadata,\n },\n };\n\n // Format log entry for console output\n const levelName = LogLevel[level];\n const contextStr = context ? ` ${JSON.stringify(context)}` : '';\n\n // Use appropriate console method based on level\n switch (level) {\n case LogLevel.DEBUG:\n console.debug(`[${timestamp}] [DEBUG] ${message}${contextStr}`);\n break;\n case LogLevel.INFO:\n console.info(`[${timestamp}] [INFO] ${message}${contextStr}`);\n break;\n case LogLevel.WARN:\n console.warn(`[${timestamp}] [WARN] ${message}${contextStr}`);\n break;\n case LogLevel.ERROR:\n console.error(`[${timestamp}] [ERROR] ${message}${contextStr}`);\n break;\n case LogLevel.FATAL:\n console.error(`[${timestamp}] [FATAL] ${message}${contextStr}`);\n break;\n }\n },\n\n /**\n * Check if Sentry is enabled\n * @returns True if Sentry is available and configured\n */\n isSentryEnabled(): boolean {\n return sentryEnabled;\n },\n\n /**\n * Get current log level (always DEBUG for server)\n * @returns Current log level\n */\n getLevel(): LogLevel {\n return LogLevel.DEBUG;\n },\n};\n\n/**\n * Create a child logger with additional context\n * @param context - Additional context to include in all logs\n * @returns Child logger instance\n */\nexport function createChildLogger(context: Record<string, any>) {\n return {\n debug: (message: string, additionalContext?: Record<string, any>) => {\n logger.debug(message, { ...context, ...additionalContext });\n },\n info: (message: string, additionalContext?: Record<string, any>) => {\n logger.info(message, { ...context, ...additionalContext });\n },\n warn: (message: string, additionalContext?: Record<string, any>) => {\n logger.warn(message, { ...context, ...additionalContext });\n },\n error: async (message: string, additionalContext?: Record<string, any>) => {\n await logger.error(message, { ...context, ...additionalContext });\n },\n fatal: async (message: string, additionalContext?: Record<string, any>) => {\n await logger.fatal(message, { ...context, ...additionalContext });\n },\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;wCA6BA,IAAMA,EAAa,OAAO,QAAY,KAAe,CAAC,CAAC,QAAQ,UAAU,KAErEC,EAAgB,GAChBC,EAAoB,KAGpBC,EAAoB,GAUxB,eAAeC,GAAkC,CAC/C,GAAI,CAAAD,EAEJ,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AAa,eAAeU,EAAS,OAAO,CAEhD,OAASE,EAAa,CAEpB,QAAQ,MAAM,gBAAiBA,CAAW,CAC5C,CAEJ,EAcA,IAAIC,EAAiBH,EAAiBC,EAAqC,CACzE,IAAMG,EAAY,IAAI,KAAK,EAAE,YAAY,EACnCC,EAAqB,CACzB,MAAAF,EACA,QAAAH,EACA,UAAAI,EACA,QAAAH,EACA,MAAOA,GAAS,MAChB,SAAU,CACR,GAAIb,EACA,CACE,IAAK,QAAQ,IACb,YAAa,QAAQ,QACrB,SAAU,QAAQ,QACpB,EACA,CAAC,EACL,GAAGa,GAAS,QACd,CACF,EAGMK,EAAYR,EAASK,CAAK,EAC1BI,EAAaN,EAAU,IAAI,KAAK,UAAUA,CAAO,CAAC,GAAK,GAG7D,OAAQE,EAAO,CACb,IAAK,GACH,QAAQ,MAAM,IAAIC,CAAS,aAAaJ,CAAO,GAAGO,CAAU,EAAE,EAC9D,MACF,IAAK,GACH,QAAQ,KAAK,IAAIH,CAAS,YAAYJ,CAAO,GAAGO,CAAU,EAAE,EAC5D,MACF,IAAK,GACH,QAAQ,KAAK,IAAIH,CAAS,YAAYJ,CAAO,GAAGO,CAAU,EAAE,EAC5D,MACF,IAAK,GACH,QAAQ,MAAM,IAAIH,CAAS,aAAaJ,CAAO,GAAGO,CAAU,EAAE,EAC9D,MACF,IAAK,GACH,QAAQ,MAAM,IAAIH,CAAS,aAAaJ,CAAO,GAAGO,CAAU,EAAE,EAC9D,KACJ,CACF,EAMA,iBAA2B,CACzB,OAAOlB,CACT,EAMA,UAAqB,CACnB,MAAO,EACT,CACF",
|
|
6
|
+
"names": ["_isNodeEnv", "sentryEnabled", "sentryClient", "sentryInitialized", "initializeSentry", "sentryDsn", "init", "captureException", "captureMessage", "__name", "LogLevel", "logger", "message", "context", "sentryError", "level", "timestamp", "logEntry", "levelName", "contextStr"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
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{B as ee,D as te,E as re,F as A,H as oe,L as P,_ as O,a as Y,b as $,c as z,d as J,o as Z,t as Q}from"./chunk-G4FO76EA.js";import{a as p}from"./chunk-PWAGW4R6.js";import{a}from"./chunk-AYY7UXNI.js";function h(e){let t,r,o;if(e instanceof P)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 P(r,t,o?{details:o}:void 0)}a(h,"handleError");function M(e,t,r=z){let o=J[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,i=e.completionTokens/1e6*o.completionPer1M,s=n+i;return{providerCost:s,billedCost:s*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:i}}}a(M,"calculateCost");async function Ce(e,t){let o={anthropic:a(async()=>{let{createAnthropic:s}=await import("@ai-sdk/anthropic");return c=>s({apiKey:c})(t)},"anthropic"),openai:a(async()=>{let{createOpenAI:s}=await import("@ai-sdk/openai");return c=>s({apiKey:c})(t)},"openai"),google:a(async()=>{let{createGoogle:s}=await import("@ai-sdk/google");return c=>s({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=xe(e);return(await o())(n)}a(Ce,"resolveModel");var Re={maxRequests:30,windowMs:6e4},S=null;async function Te(){if(S)return S;let e=U("UPSTASH_REDIS_REST_URL"),t=U("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),S={check:a(async()=>{},"check")},S;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),i=new Map;return S={check:a(async(s,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=i.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),i.set(u,d)),!(await d.limit(s)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},S}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),S={check:a(async()=>{},"check")},S}}a(Te,"getRateLimiter");function Ae(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[i,s]of Object.entries(o))n[i]=e.tool({description:s.description,inputSchema:e.jsonSchema(s.parameters)});return n}a(Ae,"resolveTools");function D(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}a(D,"toAIUsage");async function Pe(e,t,r){let o=te(e);if(!o.success)return N(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",i=Y[n],s=e.model||t.model||i?.default||"claude-sonnet-4-20250514";if(i){let l=i.models;if(!l.includes(s))return N(`Model '${s}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await Te()).check(r.userId,t.rateLimitConfig||Re)}catch(l){return N(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await Ce(n,s)}catch(l){return N(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
|
|
22
|
+
`):void 0),m=e.messages.filter(l=>l.role!=="system").map(l=>({role:l.role,content:l.content})),f=e.maxTokens||t.maxTokens||4096,_=e.temperature??t.temperature??.7,y=r.requestId||crypto.randomUUID(),b=await import("ai"),{streamText:C,generateText:R,toUIMessageStream:I,createUIMessageStreamResponse:g}=b,E=Ae(b,e.tools,t.tools),T=a(async l=>{if(!r.onCostRecord)return;let k=t.cost?.markup??4,X=M(l,s,k),ve={userId:r.userId,model:s,provider:n,usage:l,providerCost:X.providerCost,billedCost:X.billedCost,markup:k,timestamp:new Date().toISOString(),requestId:y};r.onCostRecord(ve).catch(be=>{console.error("[AI] Failed to record cost:",be)})},"recordCost");if(e.stream!==!1){let l=C({model:c,messages:m,instructions:d,maxOutputTokens:f,temperature:_,tools:E,onEnd:a(async({usage:k})=>{await T(D(k))},"onEnd")});return g({stream:I({stream:l.stream,messageMetadata:a(({part:k})=>k.type==="finish"?{usage:D(k.totalUsage)}:void 0,"messageMetadata")})})}let w=await R({model:c,messages:m,instructions:d,maxOutputTokens:f,temperature:_,tools:E}),V=D(w.usage);await T(V);let G=w.toolCalls.map(l=>({id:l.toolCallId,name:l.toolName,args:l.input}));return new Response(JSON.stringify({message:{role:"assistant",content:w.text},usage:V,finishReason:w.finishReason,toolCalls:G.length>0?G:void 0,model:s,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}a(Pe,"handleAIRequest");function N(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}a(N,"jsonError");function U(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}a(U,"getEnv");function xe(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=U(r);if(n)return n}let o=U("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}a(xe,"getAIApiKey");function ne(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}a(ne,"getEnv");function Oe(e,t){if(t){let n=ne(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=ne(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values($).find(n=>n.id===e)?.defaultModel??$.STANDARD.defaultModel)}a(Oe,"resolveModelForTier");function Ne(e){let t=Le(e),r=$e(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:ie(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:ie(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"}}a(Ne,"classifyAIError");function Ue(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}}a(Ue,"mapClassifiedToHTTP");function Le(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}}a(Le,"extractStatus");function $e(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}a($e,"extractMessage");function ie(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}}}}a(ie,"extractRetryAfter");var se="2025-02-24.acacia";var F=se,x="orderId",L="productId";function B(e){return e===null?null:typeof e=="string"?e:e.id}a(B,"idOf");function ae(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}a(ae,"toAddress");function Me(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:B(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?ae(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:ae(r.address)}:null,invoiceId:B(e.invoice),paymentIntentId:B(e.payment_intent),metadata:e.metadata??{}}}a(Me,"toCheckoutSessionSnapshot");async function De(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,i=n&&typeof n!="string"&&!n.deleted?n.metadata[L]:void 0;if(!i)throw new Error(`Line item ${o.id} of session ${t} has no ${L} product metadata`);r.push({productId:i,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}a(De,"listPaidLineItems");async function ce(e,t,r,o,n,i,s){if(!r||r.slice(0,10)<F.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[x]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${F} 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=${F}), 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[x];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=Me(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let y=await De(s,o.id);await i.onOrderPaid(f,y,m),p.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":p.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":i.onOrderPaymentFailed&&await i.onOrderPaymentFailed(f,m),p.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":i.onOrderExpired&&await i.onOrderExpired(f,m),p.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}a(ce,"handleOrderSessionEvent");function de(e,t){let{billingConfigKey:r,priceId:o}=t,[n]=t.lineItems;if(t.lineItems.length!==1||!n||n.productId!==r||n.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let i=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,mode:i}}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,mode:i}}a(de,"resolvePricePlan");function ue(e){let t=e.mode||"payment";return{mode:t,line_items:[{price:e.priceId,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}}}}a(ue,"toStripeSessionParams");var Fe={maxKeys:50,maxKeyLength:40,maxValueLength:500};function q(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"}`)}}a(q,"validateCheckoutUrl");function le(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}a(le,"sanitizeMetadata");function K(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=Fe,i=Object.entries(e);if(i.length>r)throw new Error(`${t}: ${i.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[s,c]of i){if(s.length>o)throw new Error(`${t}: metadata key '${s}' is too long (max ${o} characters)`);if(/[[\]]/.test(s))throw new Error(`${t}: metadata key '${s}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${s}' is too long (max ${n} characters)`)}}a(K,"assertStripeMetadata");function H(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&&K(o,r)}a(H,"assertCheckoutSessionMetadata");function me(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&&qe(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}`)}}a(me,"assertResolvedOrder");var Be={minSeconds:1800,maxSeconds:1440*60},pe=5e3,We=["card","sepa_debit"];function qe(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:i,invoiceFooter:s}=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(!We.includes(c))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${c}'`)}if(i!==void 0){let{minSeconds:c,maxSeconds:u}=Be;if(!Number.isInteger(i)||i<r+c||i>r+u)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${i}`)}if(s!==void 0&&(s.length===0||s.length>pe))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${pe} characters`)}a(qe,"assertResolvedOrderSession");var W=new Map;async function j(e,t,r){for(let o of t){let n=W.get(o);if(n||(n=e(o).then(i=>i.inclusive),W.set(o,n),n.catch(()=>W.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).`)}}a(j,"assertExclusiveTaxRates");function fe(e){return"createStripeSession"in e}a(fe,"isSessionProvider");function he(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}`}a(he,"resolveRedirectUrl");function Ke(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,i={...r.metadata,[x]:t.orderId};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(s=>({price_data:{currency:e.currency,unit_amount:s.unitAmount,tax_behavior:"exclusive",product_data:{name:s.name,...s.description&&{description:s.description},metadata:{[L]:s.productId}}},quantity:s.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(s=>({shipping_rate:s}))}},customer_creation:e.customerCreation,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:i,...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:i,payment_intent_data:{metadata:i}}}a(Ke,"buildOrderSessionParams");async function At(e,...t){let r=t.length===3,[o,n,i,s]=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=s[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",f=m?void 0:de(d,u);await i.getUser(o);let _=le(u.metadata??{}),y={..._,userId:o,billingConfigKey:c};K(m?{...y,[x]:""}:y,"metadata");let b=u.allowPromotionCodes??!0;if(d.beforeCheckout){let g={...u,userId:o,mode:f?.mode??"payment",priceId:f?.priceId,metadata:u.metadata??{},allowPromotionCodes:b},E=await d.beforeCheckout(o,g,_);if(!E.allowed)throw new Error(E.reason||"Checkout blocked by beforeCheckout hook")}let C=he(u.successUrl,"success"),R=he(u.cancelUrl,"cancel");q(C,"success"),q(R,"cancel");let I;if(d.type==="StripeOrder"){if(!fe(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await j(w=>n.retrieveTaxRate(w),d.tax.taxRateIds,c);let g=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:_});me(g,c);let E=g.session;if(E?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await j(w=>n.retrieveTaxRate(w),E.taxRateIds,c)}if(E?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let T=Ke(d,g,{successUrl:C,cancelUrl:R,customerEmail:u.customerEmail,metadata:y});H(T),I=await n.createStripeSession(T)}else{let g={priceId:f?.priceId,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:y,allowPromotionCodes:b,successUrl:C,cancelUrl:R,mode:f?.mode};if(fe(n)){let E=ue(g);H(E),I=await n.createStripeSession(E)}else I=await n.createCheckoutSession(g)}return{sessionId:I.id,sessionUrl:I.url}}a(At,"createCheckoutAlgorithm");async function Ot(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 i={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},s={...n,subscription:i};await r.setCustomUserClaims(e,s)}a(Ot,"updateUserSubscription");var v=class extends Error{static{a(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}},_e=4200*1e3,Lt=720*60*60*1e3;function Ee(){return crypto.randomUUID()}a(Ee,"newOwnerToken");async function ye(e,t,r,o,n){let i={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"){p.info("[Webhook] Purchase awaiting async payment",{...i,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw h(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await ge(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await ge(t,r,o,n);return;case"checkout.session.async_payment_failed":p.warn("[Webhook] Async purchase payment failed, nothing granted",{...i,operation:"purchase_payment_failed"});return;case"checkout.session.expired":p.debug("[Webhook] Checkout session expired",i);return}}a(ye,"handleTierCheckoutEvent");async function ge(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)throw h(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${i}`));let s=t[i];if(!s)throw h(new Error(`Unknown billing config key: ${i}`));if(p.info("[Webhook] Processing purchase",{userId:n,configKey:i,type:s.type,operation:"purchase_processing"}),s.type==="StripePayment"){if(!o)throw h(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:s.tier,status:A.ACTIVE,subscriptionEnd:O(s.duration),customerId:e.customer},o),s.onPurchaseSuccess)try{await s.onPurchaseSuccess(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(s.type==="StripeSubscription"){if(!o)throw h(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:s.tier,status:A.ACTIVE,subscriptionEnd:O(s.duration),subscriptionId:e.subscription,customerId:e.customer},o),s.onSubscriptionCreated)try{await s.onSubscriptionCreated(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}p.info("[Webhook] Purchase processed",{userId:n,configKey:i,operation:"purchase_processed"})}a(ge,"grantCheckoutPurchase");async function we(e,t,r,o,n){let i=e.subscription;if(!i)return;let s=await o.subscriptions.retrieve(i),{userId:c,billingConfigKey:u}=s.metadata||{};if(!c||!u){p.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:i,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw h(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:A.ACTIVE,subscriptionEnd:O(d.duration),subscriptionId:i,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,s.metadata||{})}catch(m){p.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}p.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}a(we,"handleInvoicePaymentSucceeded");async function Se(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)return;let s=t[i];if(!(!s||s.type!=="StripeSubscription")){if(!o)throw h(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:re.FREE,status:A.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),s.onSubscriptionCancelled)try{await s.onSubscriptionCancelled(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}p.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:i,operation:"subscription_cancelled"})}}a(Se,"handleSubscriptionDeleted");async function Ie(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){p.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){p.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(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}p.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}a(Ie,"handlePaymentFailed");var He=3,je=200;async function Yt(e,t,r,o,n,i,s,c){try{oe(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);p.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 p.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw p.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new P(`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;s||p.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await Xe(d,u,i,o,s)}catch(_){throw p.error("[Webhook] Event processing failed, releasing reservation",{error:_ instanceof Error?_:new Error(String(_)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await Ve(c,d.id,f),_}return await Ge(c,d.id,f),{success:!0,message:"Webhook processed"}}catch(u){throw h(u)}}a(Yt,"processWebhook");async function Ve(e,t,r){try{await e.release(t,r)||p.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){p.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}a(Ve,"releaseReservation");async function Ge(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let i=n instanceof Error?n:new Error(String(n));if(n instanceof v)throw p.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:i,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=He)throw p.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:i,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;p.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:i.message}),await new Promise(s=>setTimeout(s,je*o))}}a(Ge,"markProcessedWithRetry");async function Xe(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 Ye(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await we(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await Se(e.data.object,t,r,n);break;case"invoice.payment_failed":await Ie(e.data.object,t);break;default:p.debug("[Webhook] Unhandled event type",{type:e.type})}}a(Xe,"routeEvent");async function Ye(e,t,r,o,n,i,s,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await ce(e,t,r,o,u,d,s);return}await ye(e,o,n,i,c)}a(Ye,"handleCheckoutSessionEvent");var tr=`
|
|
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
|
+
`,ze=Q(["reserved","processed","in_progress"]),ke=Z();function rr(e){let t=a(async(r,o,n)=>{let{data:i,error:s}=await e.rpc(r,o);if(s)throw h(s);let c=ee(n,i);if(!c.success)throw h(new Error(`${r} returned an unexpected result: ${JSON.stringify(i)}`));return c.output},"call");return{async reserve(r){let o=Ee(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:_e/1e3},ze);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},ke))throw new v(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},ke)}}}a(rr,"createSupabaseIdempotencyStore");export{h as a,M as b,Pe as c,Oe as d,Ne as e,Ue as f,H as g,se as h,F as i,x as j,L as k,Me as l,De as m,ce as n,At as o,Ot as p,v as q,_e as r,Lt as s,Ee as t,Yt as u,tr as v,rr as w};
|
|
151
|
+
//# sourceMappingURL=chunk-UYI56E6Q.js.map
|