@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
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../src/shared/metadata.ts", "../../src/shared/crud/bulkCore.ts", "../../src/shared/email/createEmailRoute.ts", "../../src/shared/email/resendProvider.ts"],
|
|
4
|
-
"sourcesContent": ["// packages/functions/src/shared/metadata.ts\n\n/**\n * @fileoverview Document metadata utilities for functions\n * @description Server-safe metadata creation and update utilities\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n/**\n * Creates metadata for a new document.\n * @param userId - The ID of the user creating the document\n * @returns An object with creation and update timestamps and user IDs\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createMetadata(userId: string) {\n const now = new Date().toISOString();\n return {\n createdAt: now,\n updatedAt: now,\n createdById: userId,\n updatedById: userId,\n };\n}\n\n/**\n * Creates update metadata for an existing document.\n * @param userId - The ID of the user updating the document\n * @returns An object with update timestamp and user ID\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function updateMetadata(userId: string) {\n return {\n updatedAt: new Date().toISOString(),\n updatedById: userId,\n };\n}\n", "// packages/functions/src/shared/crud/bulkCore.ts\n\n/**\n * @fileoverview Shared bulk CRUD orchestration core.\n * @description Target-agnostic orchestrator that owns the bulk policy\n * (wire validation, collision detection, per-bucket ACL, per-row schema\n * validation, id minting, metadata stamping, audit, response validation).\n * Target storage is delegated to a caller-supplied `transact` callback \u2014\n * this lets Firestore admin, Supabase RPC, Vercel firebase-admin, future\n * GraphQL and future REST-CRUD server aids share one source of truth for\n * correctness without pulling any platform-specific dependencies here.\n *\n * This module is server-only (`shared/` but never imported from `client/`\n * or `common/`) and designed to stay portable across Node and Deno \u2014 it\n * does not import `fs`, `net`, `firebase-admin`, `supabase-js`, etc.\n *\n * @version 0.1.0\n * @since 0.7.0\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport {\n BulkCollisionError,\n BulkRequestSchema,\n BulkResponseSchema,\n detectBulkCollisions,\n DoNotDevError,\n hasRoleAccess,\n DEFAULT_STATUS_VALUE,\n} from '@donotdev/core/server';\nimport type {\n BulkRequest,\n BulkResponse,\n EntityAccessConfig,\n UserRole,\n} from '@donotdev/core/server';\n\n// =============================================================================\n// Public types\n// =============================================================================\n\n/**\n * Valibot schema alias accepted by {@link executeBulk}. Kept loose (`any` on\n * the parsed output) so callers can pass entity-specific schemas generated by\n * `createSchemas()` without fighting variance.\n */\nexport type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;\n\n/**\n * A prepared insert row passed to the caller-supplied `transact` callback.\n * When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted\n * value; otherwise it carries whatever id (if any) the client supplied and\n * the storage layer is expected to mint its own.\n */\nexport interface PreparedInsert {\n /** Minted insert id, or the empty string when the target mints its own. */\n id: string;\n /** Fully stamped row ready for storage. */\n row: Record<string, unknown>;\n}\n\n/**\n * A prepared update passed to `transact`.\n */\nexport interface PreparedUpdate {\n /** Target row id. */\n id: string;\n /** Fully stamped patch ready for storage. */\n patch: Record<string, unknown>;\n}\n\n/**\n * Payload handed to the caller-supplied `transact` callback. All three\n * arrays preserve input order and only include non-empty buckets' work.\n */\nexport interface PreparedBulk {\n inserts: PreparedInsert[];\n updates: PreparedUpdate[];\n deletes: string[];\n}\n\n/**\n * Parameters for {@link executeBulk}.\n *\n * @template TRow - Row type recorded for documentation; runtime is opaque.\n */\nexport interface ExecuteBulkParams<TRow = unknown> {\n /** Collection / table name. Passed through to audit + transact as metadata. */\n collection: string;\n /** Raw wire payload to orchestrate. Parsed with {@link BulkRequestSchema}. */\n ops: BulkRequest;\n /** Valibot schema validating each insert row. */\n createSchema: BulkRowSchema;\n /** Valibot schema validating each insert row when status === 'draft'. */\n draftCreateSchema?: BulkRowSchema;\n /** Valibot schema validating each update patch. */\n updateSchema: BulkRowSchema;\n /** Per-bucket required roles. Missing entries are treated as \"no bucket allowed\". */\n access: EntityAccessConfig;\n /** Authenticated caller id (for metadata + audit). */\n uid: string;\n /** Caller's role (for per-bucket ACL). */\n userRole: UserRole;\n /**\n * Target-specific storage. Invoked exactly once when the bulk carries at\n * least one op. Must run all three buckets inside one atomic transaction\n * (writeBatch, runTransaction, Postgres RPC wrapping BEGIN/COMMIT, etc.)\n * and return ids per bucket in input order.\n *\n * The returned shape is validated against `BulkResponseSchema` before\n * being returned to the caller.\n */\n transact: (prepared: PreparedBulk) => Promise<BulkResponse>;\n /**\n * Optional id minting. When provided, every insert is stamped with a\n * freshly-minted id before `transact` runs. When omitted, `id` on each\n * {@link PreparedInsert} is the empty string and the storage layer is\n * expected to mint its own ids (Supabase RPC, GraphQL server, etc.).\n */\n mintInsertId?: () => string;\n /**\n * Optional hook to stamp platform-specific metadata on every insert row\n * (timestamps, createdById, defaults, field-name mapping). Called once per\n * insert row, in input order.\n */\n stampInsertMetadata?: (\n row: Record<string, unknown>,\n uid: string\n ) => Record<string, unknown>;\n /**\n * Optional hook to stamp platform-specific metadata on every update patch.\n */\n stampUpdateMetadata?: (\n patch: Record<string, unknown>,\n uid: string\n ) => Record<string, unknown>;\n /**\n * Optional audit hook. Fires exactly once when `transact` succeeds, with the\n * three op counts. Never fires for empty bulks or rejected validations \u2014\n * matches the \"one audit entry\" contract from `BULK_CRUD_TODO.md` \u00A74.\n */\n audit?: (\n event: string,\n payload: {\n counts: { inserts: number; updates: number; deletes: number };\n }\n ) => void;\n /**\n * Optional rate-limit bookkeeping key. `executeBulk` does NOT perform\n * rate-limit enforcement itself \u2014 the surrounding base-function wrapper\n * already charges one hit at entry. This field is forwarded to `audit()`\n * callers that want to correlate telemetry.\n */\n rateLimitKey?: string;\n}\n\n// =============================================================================\n// Core orchestrator\n// =============================================================================\n\n/**\n * Empty response returned for a no-op bulk. Frozen so accidental mutation\n * from a caller blows up at dev time instead of poisoning the next call.\n */\nconst EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({\n insertedIds: [],\n updatedIds: [],\n deletedIds: [],\n}) as BulkResponse;\n\n/**\n * Run a bulk CRUD operation against a caller-supplied storage target.\n *\n * **Order of operations** (every step fails loud \u2014 no fallbacks, no partial\n * writes):\n *\n * 1. Parse `ops` with {@link BulkRequestSchema}. Invalid shape \u2192 throws.\n * 2. Collision detection via {@link detectBulkCollisions}. Collision \u2192\n * throws {@link BulkCollisionError}.\n * 3. Empty short-circuit \u2014 if no op carries work, returns a zeroed\n * {@link BulkResponse} without invoking `transact` or `audit`.\n * 4. Per-bucket ACL \u2014 for each populated bucket, asserts the caller's role\n * clears the corresponding `access.{create|update|delete}`. A missing\n * role on a populated bucket is a configuration error and is rejected.\n * 5. Per-row validation \u2014 inserts against `createSchema`, updates against\n * `updateSchema`. The first failure throws a `DoNotDevError` prefixed\n * with `inserts[i]` or `updates[i]` so callers can pinpoint the row.\n * 6. Id minting \u2014 if `mintInsertId` is supplied, every insert gets a fresh\n * id stamped onto its {@link PreparedInsert}. Otherwise `id` is `\"\"` and\n * the storage layer mints its own.\n * 7. Metadata stamping \u2014 `stampInsertMetadata` / `stampUpdateMetadata` run\n * per row / per patch if provided.\n * 8. `transact(prepared)` runs exactly once. Must be atomic. Throws\n * propagate unchanged so the caller's error handler can classify them.\n * 9. Response-shape validation via {@link BulkResponseSchema}. A non-conforming\n * target response throws `DoNotDevError(internal)`.\n * 10. `audit()` fires once with the three op counts.\n *\n * **Not this function's job:** rate-limiting, authentication, HTTP status\n * mapping, target-specific connection pooling, retry policy. All of those\n * belong to the surrounding handler wrapper.\n *\n * @template TRow - Row type (documentation only).\n * @param params - See {@link ExecuteBulkParams}.\n * @returns The validated {@link BulkResponse} from the target.\n *\n * @throws {BulkCollisionError} When the payload contains the same id in\n * two mutually-exclusive buckets.\n * @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row\n * validation failure, or collision (wrapped for callers that only rethrow\n * `DoNotDevError`).\n * @throws {DoNotDevError} `permission-denied` when the caller's role cannot\n * satisfy a populated bucket's access requirement.\n * @throws {DoNotDevError} `internal` when the `transact` return value fails\n * {@link BulkResponseSchema}.\n *\n * @example\n * ```typescript\n * import { executeBulk } from '@donotdev/functions/shared';\n * import { BulkResponseSchema } from '@donotdev/core/server';\n *\n * const response = await executeBulk({\n * collection: 'events',\n * ops: req.body,\n * createSchema,\n * updateSchema,\n * access,\n * uid,\n * userRole,\n * mintInsertId: () => crypto.randomUUID(),\n * stampInsertMetadata: (row, uid) => ({\n * ...row,\n * createdById: uid,\n * createdAt: new Date().toISOString(),\n * }),\n * transact: async ({ inserts, updates, deletes }) => {\n * return db.runTransaction(async (tx) => {\n * for (const { id, row } of inserts) tx.set(col.doc(id), row);\n * for (const { id, patch } of updates) tx.update(col.doc(id), patch);\n * for (const id of deletes) tx.delete(col.doc(id));\n * return {\n * insertedIds: inserts.map((i) => i.id),\n * updatedIds: updates.map((u) => u.id),\n * deletedIds: deletes,\n * };\n * });\n * },\n * audit: (event, { counts }) => logger.info(event, counts),\n * });\n * ```\n *\n * @version 0.1.0\n * @since 0.7.0\n * @author AMBROISE PARK Consulting\n */\nexport async function executeBulk<TRow = unknown>(\n params: ExecuteBulkParams<TRow>\n): Promise<BulkResponse> {\n const {\n collection,\n ops,\n createSchema,\n draftCreateSchema,\n updateSchema,\n access,\n uid,\n userRole,\n transact,\n mintInsertId,\n stampInsertMetadata,\n stampUpdateMetadata,\n audit,\n } = params;\n\n // 1. Wire-schema validation. Guarantees the three buckets are arrays of\n // the right shape; per-field entity validation happens in step 5.\n const parsed = v.safeParse(BulkRequestSchema, ops);\n if (!parsed.success) {\n const messages = parsed.issues\n .map(\n (issue) =>\n `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Bulk payload validation failed: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: parsed.issues } }\n );\n }\n const request: BulkRequest = parsed.output;\n\n const inserts = request.inserts ?? [];\n const updates = request.updates ?? [];\n const deletes = request.deletes ?? [];\n\n // 2. Collision detection. Rejects ambiguous intents BEFORE any further\n // work so a rate-limit hit + HTTP round-trip never buys a partial\n // validation pass only to fail later.\n const collision = detectBulkCollisions(request);\n if (collision.where !== null) {\n throw new BulkCollisionError(collision.collisions, collision.where);\n }\n\n // 3. Empty bulk short-circuit. Per `BULK_CRUD_TODO.md` \u00A78 this never\n // touches the storage layer, never fires audit, and returns a frozen\n // empty response shared across calls (safe \u2014 consumers never mutate).\n if (inserts.length === 0 && updates.length === 0 && deletes.length === 0) {\n return EMPTY_BULK_RESPONSE;\n }\n\n // 4. Per-bucket ACL. The surrounding base-function wrapper already cleared\n // the weakest role; we re-check each populated bucket so mixed-ACL\n // entities reject precisely. A populated bucket with no configured\n // role is a config error \u2014 fail loud rather than silently allow.\n if (inserts.length > 0) {\n if (!access.create) {\n throw new DoNotDevError(\n `Bulk insert requested on ${collection} but no create role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.create)) {\n throw new DoNotDevError(\n `Access denied for bulk insert on ${collection}. Required: ${access.create}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n if (updates.length > 0) {\n if (!access.update) {\n throw new DoNotDevError(\n `Bulk update requested on ${collection} but no update role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.update)) {\n throw new DoNotDevError(\n `Access denied for bulk update on ${collection}. Required: ${access.update}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n if (deletes.length > 0) {\n if (!access.delete) {\n throw new DoNotDevError(\n `Bulk delete requested on ${collection} but no delete role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.delete)) {\n throw new DoNotDevError(\n `Access denied for bulk delete on ${collection}. Required: ${access.delete}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n\n // 5. Per-row validation. First failure wins \u2014 prefixed with its bucket\n // index so callers can point at the offending row.\n for (let i = 0; i < inserts.length; i++) {\n const row = inserts[i]!;\n const rowObj = row as unknown as Record<string, unknown>;\n const status =\n (rowObj.status as string | undefined) ?? DEFAULT_STATUS_VALUE;\n const isDraft = status === 'draft';\n const schemaToUse =\n isDraft && draftCreateSchema ? draftCreateSchema : createSchema;\n // Only inject default `status` when validating against the draft schema.\n // This avoids breaking createSchema-only tests/entities that don't define\n // `status` in their schema shape (valibot's `v.object` is strict by\n // default).\n const payloadForValidation =\n isDraft && draftCreateSchema ? { ...rowObj, status } : rowObj;\n validateRow(payloadForValidation, schemaToUse, `inserts[${i}]`);\n }\n for (let i = 0; i < updates.length; i++) {\n validateRow(updates[i]!.patch, updateSchema, `updates[${i}]`);\n }\n\n // 6. Id minting (if provided). Minting at this layer means `transact`\n // receives stable ids \u2014 crucial for Firestore's retry-able transaction\n // callbacks where the callback body may run more than once.\n const preparedInserts: PreparedInsert[] = inserts.map((row) => {\n const rowRecord = row as unknown as Record<string, unknown>;\n // Always ensure status is present for storage + downstream schema\n // stamping. Validation may have used `draftCreateSchema` to relax\n // required-field enforcement, but storage should still persist a\n // concrete status value.\n const status =\n (rowRecord.status as string | undefined) ?? DEFAULT_STATUS_VALUE;\n const id = mintInsertId ? mintInsertId() : '';\n const stamped = stampInsertMetadata\n ? stampInsertMetadata({ ...rowRecord, status }, uid)\n : ({ ...rowRecord, status } as Record<string, unknown>);\n return { id, row: stamped };\n });\n\n // 7. Update metadata stamping.\n const preparedUpdates: PreparedUpdate[] = updates.map((u) => ({\n id: u.id,\n patch: stampUpdateMetadata\n ? stampUpdateMetadata(u.patch as Record<string, unknown>, uid)\n : (u.patch as Record<string, unknown>),\n }));\n\n // 8. Atomic dispatch. Propagates any `transact` error verbatim \u2014 the\n // surrounding handler wrapper classifies into HTTP / callable codes.\n const raw = await transact({\n inserts: preparedInserts,\n updates: preparedUpdates,\n deletes: [...deletes],\n });\n\n // 9. Response-shape validation at the wire boundary. Drift between a\n // target's return shape and `BulkResponseSchema` would silently corrupt\n // clients that zip ids back onto optimistic entries \u2014 fail loud.\n const responseParse = v.safeParse(BulkResponseSchema, raw);\n if (!responseParse.success) {\n throw new DoNotDevError(\n `Bulk transact() returned an unexpected shape for ${collection}`,\n 'internal'\n );\n }\n\n // 10. One audit entry, counts only (never row ids \u2014 anomaly detection\n // fires on the bulk count per contract \u00A74).\n if (audit) {\n audit(`crud.bulk.${collection}`, {\n counts: {\n inserts: preparedInserts.length,\n updates: preparedUpdates.length,\n deletes: deletes.length,\n },\n });\n }\n\n return responseParse.output;\n}\n\n// =============================================================================\n// Internal helpers\n// =============================================================================\n\n/**\n * Validate a row against a Valibot schema and rethrow a `DoNotDevError`\n * prefixed with the bucket position so callers can point at the offending\n * row. Keeps the hot path free of try/catch overhead when no schema is\n * supplied.\n *\n * @param value - Row or patch to validate.\n * @param schema - Valibot schema.\n * @param locator - Human-readable pointer such as `inserts[2]`.\n *\n * @example\n * ```typescript\n * validateRow(inserts[i], createSchema, `inserts[${i}]`);\n * ```\n *\n * @internal\n */\nfunction validateRow(\n value: unknown,\n schema: BulkRowSchema,\n locator: string\n): void {\n const parsed = v.safeParse(schema, value);\n if (parsed.success) return;\n\n const messages = parsed.issues\n .map(\n (issue) =>\n `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Validation failed on ${locator}: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: parsed.issues } }\n );\n}\n", "// packages/functions/src/shared/email/createEmailRoute.ts\n\n/**\n * @fileoverview Email Route Handler\n * @description Platform-agnostic handler for email send requests.\n * Validates request, resolves template, renders with locale, sends via provider.\n *\n * @version 0.1.0\n * @since 0.1.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type {\n EmailRouteConfig,\n SendEmailRequest,\n SendEmailResponse,\n} from '@donotdev/core/server';\nimport { validateSendEmailRequest } from '@donotdev/core/server';\n\nimport type { EmailProviderAdapter } from './provider.js';\n\n/**\n * Handle an email send request.\n * Validates input, resolves the template from the registry, renders with locale, and sends.\n *\n * @param request - Email send request (templateId, to, data, locale)\n * @param config - Email route configuration (provider, templates, defaultFrom)\n * @param provider - Email provider adapter (Resend, etc.)\n * @returns Send result with success status and messageId\n *\n * @example\n * ```typescript\n * const result = await handleEmailRequest(\n * { templateId: 'order-confirmation', to: 'user@example.com', data: { orderId: '123' }, locale: 'fr' },\n * emailConfig,\n * resendProvider\n * );\n * ```\n */\nexport async function handleEmailRequest(\n request: SendEmailRequest,\n config: EmailRouteConfig,\n provider: EmailProviderAdapter\n): Promise<SendEmailResponse> {\n // Validate request\n const validation = validateSendEmailRequest(request);\n if (!validation.success) {\n return {\n success: false,\n error: `Invalid email request: ${validation.issues?.map((i) => i.message).join(', ')}`,\n };\n }\n\n // Resolve template\n const template = config.templates[request.templateId];\n if (!template) {\n return {\n success: false,\n error: `Template not found: ${request.templateId}`,\n };\n }\n\n // Render template with locale\n const locale = request.locale || 'fr';\n const subject = template.subject(request.data as any, locale);\n const html = template.html(request.data as any, locale);\n\n // Send via provider\n const result = await provider.send({\n from: request.from || config.defaultFrom,\n to: request.to,\n subject,\n html,\n replyTo: request.replyTo || config.replyTo,\n });\n\n return {\n success: true,\n messageId: result.messageId,\n };\n}\n", "// packages/functions/src/shared/email/resendProvider.ts\n\n/**\n * @fileoverview Resend Email Provider\n * @description Zero-dependency Resend implementation using raw fetch.\n *\n * @version 0.1.0\n * @since 0.1.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type { EmailProviderAdapter } from './provider.js';\n\nconst RESEND_API_URL = 'https://api.resend.com/emails';\n\n/**\n * Create a Resend email provider adapter.\n *\n * @param apiKey - Resend API key\n * @returns EmailProviderAdapter implementation\n *\n * @example\n * ```typescript\n * const provider = createResendProvider(Deno.env.get('RESEND_API_KEY')!);\n * await provider.send({ from: 'noreply@app.com', to: 'user@example.com', subject: 'Hello', html: '<p>Hi</p>' });\n * ```\n */\nexport function createResendProvider(apiKey: string): EmailProviderAdapter {\n if (!apiKey) {\n throw new Error('Resend API key is required');\n }\n\n return {\n async send({ from, to, subject, html, replyTo }) {\n const body: Record<string, string> = { from, to, subject, html };\n if (replyTo) body.reply_to = replyTo;\n\n const response = await fetch(RESEND_API_URL, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n throw new Error(`Resend API error (${response.status}): ${errorText}`);\n }\n\n const result = await response.json();\n return { messageId: result.id };\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "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",
|
|
6
|
-
"names": ["createMetadata", "userId", "now", "__name", "updateMetadata", "EMPTY_BULK_RESPONSE", "executeBulk", "params", "collection", "ops", "createSchema", "draftCreateSchema", "updateSchema", "access", "uid", "userRole", "transact", "mintInsertId", "stampInsertMetadata", "stampUpdateMetadata", "audit", "parsed", "safeParse", "BulkRequestSchema", "messages", "issue", "p", "DoNotDevError", "request", "inserts", "updates", "deletes", "collision", "detectBulkCollisions", "BulkCollisionError", "hasRoleAccess", "i", "rowObj", "status", "DEFAULT_STATUS_VALUE", "isDraft", "schemaToUse", "payloadForValidation", "validateRow", "preparedInserts", "row", "rowRecord", "id", "stamped", "preparedUpdates", "u", "raw", "responseParse", "BulkResponseSchema", "__name", "value", "schema", "locator", "handleEmailRequest", "request", "config", "provider", "validation", "validateSendEmailRequest", "i", "template", "locale", "subject", "html", "__name", "RESEND_API_URL", "createResendProvider", "apiKey", "from", "to", "subject", "html", "replyTo", "body", "response", "errorText", "__name"]
|
|
7
|
-
}
|
|
@@ -1,21 +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
|
-
//# sourceMappingURL=chunk-FSLGZD7A.js.map
|
|
@@ -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 Ee,F as M,H as ye,L as b,V,W as G,_ as D,a as se,b as H,c as ie,d as ae,k as ce,o as de,p as ue,q as j,r as pe,s as L,t as C,v as le,x as me}from"./chunk-TMHBP3HB.js";import{a as l}from"./chunk-NP2AN2TV.js";import{a as i}from"./chunk-AYY7UXNI.js";function E(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(E,"handleError");var ge=C(["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-7HDAP5DL.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 Ct(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(Ct,"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 He(e,t){try{return t==="supabase"?await je(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(He,"verifyToken");async function je(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(je,"verifySupabaseToken");async function Ve(e,t){let r=qe(e.headers.authorization),{uid:o}=await He(r,t);return o}i(Ve,"verifyAuthToken");var Pt=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),T=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 T({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 T(_);let y=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:y.length>0?y: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(H).find(n=>n.id===e)?.defaultModel??H.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 Te(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(Te,"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 Ce(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(Ce,"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 cr(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=Te(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},y=await d.beforeCheckout(o,_,h);if(!y.allowed)throw new Error(y.reason||"Checkout blocked by beforeCheckout hook");f?.dynamic&&y.overrides&&(k=y.overrides.unitAmount??k,A=y.overrides.productName??A)}let R=xe(u.successUrl,"success"),T=xe(u.cancelUrl,"cancel");Z(R,"success"),Z(T,"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});Ce(_,c);let y=_.session;if(y?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await re(w=>n.retrieveTaxRate(w),y.taxRateIds,c)}if(y?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let p=ut(d,_,{successUrl:R,cancelUrl:T,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 y={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:T,mode:f?.mode};if(Pe(n)){let p=Ae(y);te(p),g=await n.createStripeSession(p)}else g=await n.createCheckoutSession(y)}return{sessionId:g.id,sessionUrl:g.url}}i(cr,"createCheckoutAlgorithm");async function pr(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(pr,"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 fr(){if(!oe())return!1;try{let{getFirebaseAdminFirestore:e}=await import("./server-7HDAP5DL.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(fr,"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 pt=`
|
|
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
|
-
`,lt=C(["reserved","processed","in_progress"]),Oe=de();function mt(e){let t=i(async(r,o,n)=>{let{data:s,error:a}=await e.rpc(r,o);if(a)throw E(a);let c=P(n,s);if(!c.success)throw E(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},lt);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(mt,"createSupabaseIdempotencyStore");var Ne="webhook_idempotency";function ft(){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(ft,"createInMemoryIdempotencyStore");var ht=me([j(),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(C(["processing","processed"])),ownerToken:L(le()),reservedAt:L(j()),expiresAt:L(ht)});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 yt(){let e=null,t=i(async()=>{e||(e=await import("./server-7HDAP5DL.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 E(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:E(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 E(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 E(s)}}}}i(yt,"createFirestoreIdempotencyStore");var N=null;function Ue(){return N||(oe()?N=yt():(console.warn("[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store."),N=ft()),N)}i(Ue,"createIdempotencyStore");function Ar(){N=null}i(Ar,"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 E(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 E(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${s}`));let a=t[s];if(!a)throw E(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 E(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 E(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 E(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 E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:Ee.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 gt=3,_t=200;async function qr(e,t,r,o,n,s,a,c=Ue()){try{ye(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 St(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 wt(c,d.id,f),h}return await vt(c,d.id,f),{success:!0,message:"Webhook processed"}}catch(u){throw E(u)}}i(qr,"processWebhook");async function wt(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(wt,"releaseReservation");async function vt(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>=gt)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,_t*o))}}i(vt,"markProcessedWithRetry");async function St(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 kt(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(St,"routeEvent");async function kt(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(kt,"handleCheckoutSessionEvent");export{E as a,ge as b,Tt as c,Ke as d,Ct as e,He as f,Ve as g,Pt 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,cr as v,pr as w,oe as x,fr as y,v as z,x as A,K as B,pt as C,mt as D,ft as E,yt as F,Ue as G,Ar as H,qr as I};
|
|
151
|
-
//# sourceMappingURL=chunk-GVLSPWDD.js.map
|