@donotdev/functions 0.2.2 → 0.3.0
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-522YXGDA.js +23 -0
- package/lib/chunks/chunk-522YXGDA.js.map +7 -0
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
- package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/chunk-OKRR7ST5.js +22 -0
- package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils.d.ts +13 -10
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -9
- package/lib/supabase/crud/entityStore.d.ts +67 -14
- package/lib/supabase/crud/update.d.ts +7 -10
- package/lib/supabase/index.d.ts +5 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +33 -1
- package/src/firebase/auth/setCustomClaims.ts +6 -0
- package/src/firebase/baseFunction.ts +5 -2
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +37 -19
- package/src/firebase/crud/bulk.ts +30 -10
- package/src/firebase/crud/create.ts +40 -26
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +12 -14
- package/src/firebase/crud/list.ts +23 -12
- package/src/firebase/crud/update.ts +49 -25
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -0
- package/src/firebase/oauth/getConnections.ts +1 -1
- package/src/firebase/oauth/githubAccess.ts +3 -0
- package/src/firebase/oauth/refreshToken.ts +1 -0
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +56 -11
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +112 -82
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/logger.ts +37 -38
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +4 -42
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +50 -0
- package/src/supabase/crud/create.ts +27 -33
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +107 -18
- package/src/supabase/crud/get.ts +5 -13
- package/src/supabase/crud/list.ts +28 -21
- package/src/supabase/crud/update.ts +29 -24
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +8 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +34 -6
- package/src/vercel/api/crud/create.ts +22 -21
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +10 -8
- package/src/vercel/api/crud/list.ts +10 -8
- package/src/vercel/api/crud/update.ts +25 -20
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
- package/lib/chunks/chunk-2IFFIUFV.js +0 -23
- package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
- package/lib/chunks/chunk-FQSQGOBN.js +0 -22
- package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
- package/lib/chunks/chunk-G4FO76EA.js +0 -22
- package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
- package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
- package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
- package/lib/chunks/chunk-M4JV2JCF.js +0 -22
- package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
- package/lib/chunks/chunk-OZX5ZG44.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-UYI56E6Q.js +0 -151
- package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
- package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
- package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -192
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/github.ts", "../../src/shared/utils/validation.ts", "../../src/shared/utils/schemaValidation.ts", "../../src/shared/utils/firebaseHelpers.ts", "../../src/shared/utils/vercelHelpers.ts", "../../src/shared/utils/external/date.ts", "../../src/shared/utils/external/references.ts", "../../src/shared/utils/external/subscription.ts", "../../src/shared/utils/internal/firebase.ts", "../../src/shared/utils/internal/idempotency.ts", "../../src/shared/utils/internal/validation.ts", "../../src/shared/oauth/exchangeToken.ts", "../../src/shared/oauth/grantAccess.ts", "../../src/shared/firebase.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/github.ts\n\n/**\n * @fileoverview GitHub API Service for functions\n * @description Server-safe GitHub API utilities for repository management\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\n/** Configuration for authenticating with the GitHub API. */\nexport interface GitHubApiConfig {\n accessToken: string;\n baseUrl?: string;\n}\n\n/** GitHub user profile returned by the API. */\nexport interface GitHubUser {\n id: number;\n login: string;\n email: string;\n name?: string;\n avatar_url: string;\n}\n\n/** GitHub repository metadata returned by the API. */\nexport interface GitHubRepository {\n id: number;\n name: string;\n full_name: string;\n private: boolean;\n owner: {\n login: string;\n id: number;\n };\n}\n\n/** Request payload for adding a collaborator to a GitHub repository. */\nexport interface AddCollaboratorRequest {\n owner: string;\n repo: string;\n username: string;\n permission?: 'pull' | 'triage' | 'push' | 'maintain' | 'admin';\n}\n\n/** Error response structure from the GitHub API. */\nexport interface GitHubApiError {\n message: string;\n documentation_url?: string;\n status?: number;\n}\n\n/** Error body shape returned by the GitHub API on non-2xx responses (untrusted). */\nconst GitHubErrorBodySchema = v.object({\n message: v.optional(v.string()),\n documentation_url: v.optional(v.string()),\n});\n\n/** Pattern for valid GitHub usernames, org names, repo names, and team slugs */\nconst SAFE_GITHUB_NAME = /^[a-zA-Z0-9_.-]+$/;\n\n/** Validate a GitHub name (username, owner, repo, team slug) against path injection */\nfunction validateGitHubName(name: string, label: string): void {\n if (!SAFE_GITHUB_NAME.test(name)) {\n throw new Error(\n `Invalid ${label}: must contain only alphanumeric, hyphens, underscores, and dots`\n );\n }\n}\n\n/**\n * GitHub API Service for server-side operations\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport class GitHubApiService {\n private config: GitHubApiConfig;\n\n constructor(config: GitHubApiConfig) {\n this.config = {\n baseUrl: 'https://api.github.com',\n ...config,\n };\n }\n\n /**\n * Get the current authenticated user\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async getCurrentUser(): Promise<GitHubUser> {\n const response = await this.request<GitHubUser>('/user');\n return response;\n }\n\n /**\n * Get user repositories\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async getUserRepositories(username?: string): Promise<GitHubRepository[]> {\n if (username) {\n validateGitHubName(username, 'username');\n }\n const endpoint = username ? `/users/${username}/repos` : '/user/repos';\n const response = await this.request<GitHubRepository[]>(endpoint);\n return response;\n }\n\n /**\n * Add a collaborator to a repository\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async addCollaborator(request: AddCollaboratorRequest): Promise<boolean> {\n validateGitHubName(request.owner, 'owner');\n validateGitHubName(request.repo, 'repo');\n validateGitHubName(request.username, 'username');\n try {\n await this.request(\n `/repos/${request.owner}/${request.repo}/collaborators/${request.username}`,\n {\n method: 'PUT',\n body: JSON.stringify({\n permission: request.permission || 'push',\n }),\n }\n );\n return true;\n } catch (error) {\n console.error('Failed to add collaborator:', error);\n return false;\n }\n }\n\n /**\n * Check if a user is a collaborator on a repository\n * Uses GitHub's direct API endpoint for efficiency\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async isCollaborator(\n owner: string,\n repo: string,\n username: string\n ): Promise<boolean> {\n validateGitHubName(owner, 'owner');\n validateGitHubName(repo, 'repo');\n validateGitHubName(username, 'username');\n try {\n // GitHub returns 204 if user is collaborator, 404 if not\n await this.request(`/repos/${owner}/${repo}/collaborators/${username}`, {\n method: 'GET',\n });\n return true;\n } catch (error) {\n if (error instanceof Error && error.message.includes('404')) {\n return false;\n }\n console.error('Failed to check collaborator status:', error);\n return false;\n }\n }\n\n /**\n * Remove a collaborator from a repository\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async removeCollaborator(\n owner: string,\n repo: string,\n username: string\n ): Promise<boolean> {\n validateGitHubName(owner, 'owner');\n validateGitHubName(repo, 'repo');\n validateGitHubName(username, 'username');\n try {\n await this.request(`/repos/${owner}/${repo}/collaborators/${username}`, {\n method: 'DELETE',\n });\n return true;\n } catch (error) {\n console.error('Failed to remove collaborator:', error);\n return false;\n }\n }\n\n /**\n * Add a user to an organization team\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async addTeamMember(\n org: string,\n teamSlug: string,\n username: string,\n role: 'member' | 'maintainer' = 'member'\n ): Promise<boolean> {\n validateGitHubName(org, 'org');\n validateGitHubName(teamSlug, 'teamSlug');\n validateGitHubName(username, 'username');\n try {\n await this.request(\n `/orgs/${org}/teams/${teamSlug}/memberships/${username}`,\n {\n method: 'PUT',\n body: JSON.stringify({ role }),\n }\n );\n return true;\n } catch (error) {\n console.error('Failed to add team member:', error);\n return false;\n }\n }\n\n /**\n * Remove a user from an organization team\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async removeTeamMember(\n org: string,\n teamSlug: string,\n username: string\n ): Promise<boolean> {\n validateGitHubName(org, 'org');\n validateGitHubName(teamSlug, 'teamSlug');\n validateGitHubName(username, 'username');\n try {\n await this.request(\n `/orgs/${org}/teams/${teamSlug}/memberships/${username}`,\n {\n method: 'DELETE',\n }\n );\n return true;\n } catch (error) {\n console.error('Failed to remove team member:', error);\n return false;\n }\n }\n\n /**\n * Check if a user is a member of an organization team\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n async isTeamMember(\n org: string,\n teamSlug: string,\n username: string\n ): Promise<boolean> {\n validateGitHubName(org, 'org');\n validateGitHubName(teamSlug, 'teamSlug');\n validateGitHubName(username, 'username');\n try {\n await this.request(\n `/orgs/${org}/teams/${teamSlug}/memberships/${username}`,\n {\n method: 'GET',\n }\n );\n return true;\n } catch (error) {\n if (error instanceof Error && error.message.includes('404')) {\n return false;\n }\n console.error('Failed to check team membership:', error);\n return false;\n }\n }\n\n /**\n * Make an authenticated request to the GitHub API\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.config.baseUrl}${endpoint}`;\n\n const response = await fetch(url, {\n ...options,\n headers: {\n Authorization: `Bearer ${this.config.accessToken}`,\n Accept: 'application/vnd.github.v3+json',\n 'User-Agent': 'DoNotDev-Functions',\n 'Content-Type': 'application/json',\n ...options.headers,\n },\n });\n\n if (!response.ok) {\n const errorBody: unknown = await response.json().catch(() => ({}));\n const parsed = v.safeParse(GitHubErrorBodySchema, errorBody);\n const errorData = parsed.success ? parsed.output : {};\n const error: GitHubApiError = {\n message:\n errorData.message ||\n `HTTP ${response.status}: ${response.statusText}`,\n documentation_url: errorData.documentation_url,\n status: response.status,\n };\n throw new Error(`GitHub API Error: ${error.message}`);\n }\n\n return response.json() as Promise<T>;\n }\n}\n\n/**\n * Create a GitHub API service instance\n */\nexport function createGitHubApiService(accessToken: string): GitHubApiService {\n return new GitHubApiService({ accessToken });\n}\n", "// packages/functions/src/shared/utils/validation.ts\n\n/**\n * @fileoverview Enhanced validation utilities\n * @description Comprehensive validation functions for Stripe operations\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { logger } from 'firebase-functions/v2';\nimport * as v from 'valibot';\n\n/**\n * Validation schemas for Stripe operations\n */\nexport const StripeValidationSchemas = {\n webhookEvent: v.object({\n id: v.pipe(v.string(), v.minLength(1, 'Event ID is required')),\n type: v.pipe(v.string(), v.minLength(1, 'Event type is required')),\n data: v.object({\n object: v.any(),\n }),\n created: v.pipe(v.number(), v.minValue(0, 'Valid timestamp required')),\n }),\n\n purchaseRequest: v.object({\n userId: v.pipe(v.string(), v.minLength(1, 'User ID is required')),\n productType: v.pipe(v.string(), v.minLength(1, 'Product type is required')),\n githubUsername: v.optional(\n v.pipe(\n v.string(),\n v.regex(\n /^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,\n 'Invalid GitHub username'\n )\n )\n ),\n sessionId: v.pipe(v.string(), v.minLength(1, 'Session ID is required')),\n amount: v.optional(\n v.pipe(v.number(), v.minValue(0, 'Amount must be positive'))\n ),\n currency: v.optional(\n v.pipe(v.string(), v.length(3, 'Currency must be 3 characters'))\n ),\n }),\n};\n\n/**\n * Validation result interface\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport interface ValidationResult {\n isValid: boolean;\n errors: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n data?: any;\n}\n\n/**\n * Validate webhook event\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function validateWebhookEvent(data: any): ValidationResult {\n try {\n const validatedData = v.parse(StripeValidationSchemas.webhookEvent, data);\n return {\n isValid: true,\n data: validatedData,\n errors: [],\n };\n } catch (error) {\n if (v.isValiError(error)) {\n const errors = error.issues.map(\n (err) =>\n `${err.path?.map((p) => p.key).join('.') || ''}: ${err.message}`\n );\n logger.warn('Webhook event validation failed', { errors, data });\n return {\n isValid: false,\n errors,\n };\n }\n return {\n isValid: false,\n errors: ['Unknown validation error'],\n };\n }\n}\n\n/**\n * Validate purchase request\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function validatePurchaseRequest(data: any): ValidationResult {\n try {\n const validatedData = v.parse(\n StripeValidationSchemas.purchaseRequest,\n data\n );\n return {\n isValid: true,\n data: validatedData,\n errors: [],\n };\n } catch (error) {\n if (v.isValiError(error)) {\n const errors = error.issues.map(\n (err) =>\n `${err.path?.map((p) => p.key).join('.') || ''}: ${err.message}`\n );\n logger.warn('Purchase request validation failed', { errors, data });\n return {\n isValid: false,\n errors,\n };\n }\n return {\n isValid: false,\n errors: ['Unknown validation error'],\n };\n }\n}\n\n/**\n * Validate GitHub username format\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateGitHubUsername(username: string): boolean {\n const githubUsernameRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/;\n return githubUsernameRegex.test(username);\n}\n\n/**\n * Validate email format\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Validate price ID format (Stripe price IDs start with 'price_')\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripePriceId(priceId: string): boolean {\n return priceId.startsWith('price_') && priceId.length > 6;\n}\n\n/**\n * Validate session ID format (Stripe session IDs start with 'cs_')\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripeSessionId(sessionId: string): boolean {\n return sessionId.startsWith('cs_') && sessionId.length > 3;\n}\n\n/**\n * Validate URL format\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateUrl(url: string, name: string = 'URL'): string {\n try {\n const parsedUrl = new URL(url);\n\n if (!['http:', 'https:'].includes(parsedUrl.protocol)) {\n throw new Error(`Invalid protocol: ${parsedUrl.protocol}`);\n }\n\n return url;\n } catch (error) {\n throw new Error(\n `Invalid ${name}: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`\n );\n }\n}\n\n/**\n * Validate and sanitize metadata object\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateMetadata(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n metadata: Record<string, any>\n): Record<string, string> {\n const sanitized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value !== 'string') {\n throw new Error(\n `Metadata value for key '${key}' must be a string, got ${typeof value}`\n );\n }\n\n const sanitizedValue = value\n .replace(/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi, '')\n .replace(/javascript:/gi, '')\n .replace(/on\\w+\\s*=/gi, '');\n\n if (sanitizedValue.length > 1000) {\n throw new Error(\n `Metadata value for key '${key}' is too long (max 1000 characters)`\n );\n }\n\n if (key.length > 100) {\n throw new Error(`Metadata key '${key}' is too long (max 100 characters)`);\n }\n\n sanitized[key] = sanitizedValue;\n }\n\n return sanitized;\n}\n", "// packages/functions/src/shared/utils/schemaValidation.ts\n\n/**\n * @fileoverview DRY utilities for schema validation across all functions\n * @description Provides reusable patterns for Firebase and Vercel functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type { CallableRequest } from 'firebase-functions/v2/https';\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport * as v from 'valibot';\n\n/**\n * Validates request data using a schema with custom override support\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateRequestData<T>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n data: any,\n defaultSchema: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>,\n customSchema?: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>\n): { success: true; data: T } | { success: false; error: string } {\n const schema = customSchema || defaultSchema;\n const validationResult = v.safeParse(schema, data);\n\n if (!validationResult.success) {\n return {\n success: false,\n error: `Validation failed: ${validationResult.issues.map((e) => e.message).join(', ')}`,\n };\n }\n\n return {\n success: true,\n data: validationResult.output,\n };\n}\n\n/**\n * Firebase function wrapper that adds schema validation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function withSchemaValidation<TRequest, TResponse>(\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n request: CallableRequest<TRequest>,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n return async (\n request: CallableRequest<TRequest>,\n customSchema?: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>\n ): Promise<TResponse> => {\n const validation = validateRequestData(\n request.data,\n defaultSchema,\n customSchema\n );\n\n if (!validation.success) {\n throw new Error(validation.error);\n }\n\n return await handler(request, validation.data);\n };\n}\n\n/**\n * Vercel function wrapper that adds schema validation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function withVercelSchemaValidation<TRequest, TResponse>(\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n req: NextApiRequest,\n res: NextApiResponse,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n return async (\n req: NextApiRequest,\n res: NextApiResponse,\n customSchema?: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>\n ): Promise<TResponse> => {\n const validation = validateRequestData(\n req.body,\n defaultSchema,\n customSchema\n );\n\n if (!validation.success) {\n return res.status(400).json({\n error: validation.error,\n }) as TResponse;\n }\n\n return await handler(req, res, validation.data);\n };\n}\n\n/**\n * Creates both standard and custom schema versions of a Firebase function\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createFirebaseFunction<TRequest, TResponse>(\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n request: CallableRequest<TRequest>,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n const internalHandler = withSchemaValidation(defaultSchema, handler);\n\n return {\n // Standard function (no custom schema)\n standard: (request: CallableRequest<TRequest>) => internalHandler(request),\n\n // Custom schema function\n withSchema: (\n request: CallableRequest<TRequest>,\n customSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>\n ) => internalHandler(request, customSchema),\n };\n}\n\n/**\n * Creates a Vercel function with schema validation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createVercelFunction<TRequest, TResponse>(\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n req: NextApiRequest,\n res: NextApiResponse,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n return withVercelSchemaValidation(defaultSchema, handler);\n}\n", "// packages/functions/src/shared/utils/firebaseHelpers.ts\n\n/**\n * @fileoverview DRY helpers for Firebase functions with schema validation\n * @description Provides reusable patterns for Firebase onCall functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { onCall } from 'firebase-functions/v2/https';\nimport type { CallableRequest } from 'firebase-functions/v2/https';\nimport type * as v from 'valibot';\n\nimport { withSchemaValidation } from './schemaValidation.js';\n\n/**\n * Creates a Firebase onCall function with schema validation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createFirebaseCallable<TRequest, TResponse>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n config: any,\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n request: CallableRequest<TRequest>,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n const internalHandler = withSchemaValidation(defaultSchema, handler);\n\n return {\n // Standard onCall function\n onCall: onCall(config, async (request: CallableRequest<TRequest>) => {\n return await internalHandler(request);\n }),\n\n // Custom schema function\n withSchema: async (\n request: CallableRequest<TRequest>,\n customSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>\n ) => {\n return await internalHandler(request, customSchema);\n },\n };\n}\n\n/**\n * Creates both onCall and withSchema exports for a Firebase function\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createFirebaseFunctionExports<TRequest, TResponse>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n config: any,\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n request: CallableRequest<TRequest>,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n const { onCall: onCallFunction, withSchema } = createFirebaseCallable(\n config,\n defaultSchema,\n handler\n );\n\n return {\n // Main export (onCall)\n [handler.name || 'mainFunction']: onCallFunction,\n\n // Custom schema export\n [`${handler.name || 'mainFunction'}WithSchema`]: withSchema,\n };\n}\n", "// packages/functions/src/shared/utils/vercelHelpers.ts\n\n/**\n * @fileoverview DRY helpers for Vercel API functions with schema validation\n * @description Provides reusable patterns for Vercel API routes\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport type * as v from 'valibot';\n\nimport {\n withVercelSchemaValidation,\n validateRequestData,\n} from './schemaValidation.js';\n\n/**\n * Creates a Vercel API handler with schema validation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createVercelHandler<TRequest, TResponse>(\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n req: NextApiRequest,\n res: NextApiResponse,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n return withVercelSchemaValidation(defaultSchema, handler);\n}\n\n/**\n * Creates a Vercel API handler with method validation and schema validation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createVercelApiHandler<TRequest, TResponse>(\n method: string,\n defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,\n handler: (\n req: NextApiRequest,\n res: NextApiResponse,\n validatedData: TRequest\n ) => Promise<TResponse>\n) {\n return async (\n req: NextApiRequest,\n res: NextApiResponse,\n customSchema?: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>\n ): Promise<TResponse> => {\n if (req.method !== method) {\n return res.status(405).json({ error: 'Method not allowed' }) as TResponse;\n }\n\n const validation = validateRequestData(\n req.body,\n defaultSchema,\n customSchema\n );\n\n if (!validation.success) {\n return res.status(400).json({\n error: validation.error,\n }) as TResponse;\n }\n\n return await handler(req, res, validation.data as TRequest);\n };\n}\n", "// packages/functions/src/shared/utils/external/date.ts\n\n/**\n * @fileoverview Date utility functions for functions package\n * @description Self-contained date conversion utilities for server-side functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { Timestamp } from '@donotdev/firebase/server';\n\n/**\n * Represents a date value in various formats accepted by Firebase.\n * Can be a JavaScript Date, a Firestore Timestamp, or an ISO 8601 string.\n */\nexport type DateValue = Date | FirestoreTimestamp | string;\n\n/**\n * Interface mimicking Firebase Timestamp for type compatibility\n */\nexport interface FirestoreTimestamp {\n seconds: number;\n nanoseconds: number;\n toDate(): Date;\n toMillis(): number;\n isEqual(other: FirestoreTimestamp): boolean;\n valueOf(): string;\n}\n\n/**\n * Converts various date formats to ISO string\n * Handles Date, FirestoreTimestamp, and string inputs\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function toISOString(date: DateValue): string {\n if (date instanceof Date) {\n return date.toISOString();\n }\n if (typeof date === 'object' && date !== null && 'toDate' in date) {\n if (typeof date.toDate === 'function') {\n return date.toDate().toISOString();\n }\n }\n\n // Handle string dates\n if (typeof date === 'string') {\n const parsed = new Date(date);\n if (isNaN(parsed.getTime())) {\n throw new Error('Invalid date format');\n }\n return parsed.toISOString();\n }\n\n // Fallback for any other type\n // why: unreachable for typed callers; keeps the runtime path for untyped values (numbers, plain objects)\n const parsed = new Date(date as unknown as string);\n if (isNaN(parsed.getTime())) {\n throw new Error('Invalid date format');\n }\n\n return parsed.toISOString();\n}\n\n/**\n * Add months to a date with proper edge case handling\n * Fixes issues like Jan 31 + 1 month = March 3 (should be Feb 28/29)\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nfunction addMonths(date: Date, months: number): Date {\n const result = new Date(date);\n const originalDate = result.getDate();\n\n result.setMonth(result.getMonth() + months);\n\n if (result.getDate() !== originalDate) {\n result.setDate(0);\n }\n\n return result;\n}\n\n/**\n * Add years to a date with proper edge case handling\n * Fixes issues like Feb 29 + 1 year in non-leap year\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nfunction addYears(date: Date, years: number): Date {\n const result = new Date(date);\n const originalDate = result.getDate();\n\n result.setFullYear(result.getFullYear() + years);\n\n if (result.getDate() !== originalDate) {\n result.setDate(0);\n }\n\n return result;\n}\n\n/**\n * Calculate subscription end date with proper edge case handling\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n * @param duration - Duration string (e.g., '1month', '3months', '1year', 'lifetime')\n * @param startDate - Start date (defaults to now)\n * @returns ISO string of end date (required for Firestore compatibility)\n */\nexport function calculateSubscriptionEndDate(\n duration: string,\n startDate: Date = new Date()\n): string {\n if (duration === 'lifetime') {\n return '2099-12-31T23:59:59.000Z';\n }\n\n let endDate: Date;\n\n if (duration === '1month') {\n endDate = addMonths(startDate, 1);\n } else if (duration === '3months') {\n endDate = addMonths(startDate, 3);\n } else if (duration === '6months') {\n endDate = addMonths(startDate, 6);\n } else if (duration === '1year') {\n endDate = addYears(startDate, 1);\n } else if (duration === '2years') {\n endDate = addYears(startDate, 2);\n } else {\n endDate = addMonths(startDate, 1);\n }\n\n return endDate.toISOString();\n}\n", "// packages/functions/src/shared/utils/external/references.ts\n\n/**\n * @fileoverview Reference checking utilities\n * @description Functions for checking document references before deletion\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { getFirebaseAdminFirestore } from '@donotdev/firebase/server';\n\n/**\n * Finds all documents that reference the given document ID\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function findReferences(\n collection: string,\n documentId: string\n): Promise<Array<{ id: string; collection: string; field: string }>> {\n const references: Array<{ id: string; collection: string; field: string }> =\n [];\n\n // This is a simplified implementation\n // In a real app, you'd need to check all collections that might reference this document\n // For now, we'll return an empty array (no references found)\n\n return references;\n}\n", "// packages/functions/src/shared/utils/external/subscription.ts\n\n/**\n * @fileoverview Subscription utility functions\n * @description Functions for managing user subscriptions and billing\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type { SubscriptionClaims } from '@donotdev/core/server';\nimport {\n getFirebaseAdminAuth,\n getFirebaseAdminFirestore,\n} from '@donotdev/firebase/server';\n\n/**\n * Maps Stripe price ID to subscription tier\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getTierFromPriceId(priceId: string): string {\n const tierMapping: Record<string, string> = {\n // Monthly subscriptions\n price_pro_monthly: 'pro',\n price_ai_monthly: 'ai',\n\n // Yearly subscriptions\n price_pro_yearly: 'pro',\n price_ai_yearly: 'ai',\n\n // Add your actual Stripe price IDs here\n };\n\n return tierMapping[priceId] || 'free';\n}\n\n/**\n * Cancels user subscription and resets to free tier\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n firebaseUid: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n subscription: any\n): Promise<void> {\n if (!firebaseUid) {\n throw new Error('Firebase UID is required to cancel subscription');\n }\n\n const subscriptionClaims: SubscriptionClaims = {\n tier: 'free',\n subscriptionId: null,\n customerId: subscription.customer,\n status: 'canceled',\n subscriptionEnd: null,\n cancelAtPeriodEnd: false,\n updatedAt: new Date().toISOString(),\n };\n\n try {\n const auth = getFirebaseAdminAuth();\n const db = getFirebaseAdminFirestore();\n\n // Read existing claims and merge to avoid overwriting other claims\n const user = await auth.getUser(firebaseUid);\n const currentClaims = user.customClaims || {};\n\n // Update Firebase Auth custom claims\n await auth.setCustomUserClaims(firebaseUid, {\n ...currentClaims,\n subscription: subscriptionClaims,\n });\n\n // Update Firestore\n await db\n .collection('subscriptions')\n .doc(firebaseUid)\n .update({\n ...subscriptionClaims,\n updatedAt: new Date().toISOString(),\n });\n\n console.log(`Subscription canceled for user ${firebaseUid}:`, {\n subscriptionId: subscription.id,\n });\n } catch (error) {\n console.error('Failed to cancel user subscription:', error);\n throw new Error('Failed to cancel user subscription');\n }\n}\n\n/**\n * Gets user's current subscription from Firebase\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function getUserSubscription(\n firebaseUid: string\n): Promise<SubscriptionClaims | null> {\n try {\n const auth = getFirebaseAdminAuth();\n const user = await auth.getUser(firebaseUid);\n return (user.customClaims?.subscription as SubscriptionClaims) || null;\n } catch (error) {\n console.error('Failed to get user subscription:', error);\n return null;\n }\n}\n", "// packages/functions/src/shared/utils/internal/firebase.ts\n\n/**\n * @fileoverview Firebase initialization utilities\n * @description Re-exports provider functions for DRY access\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { getFirebaseAdminApp } from '@donotdev/firebase/server';\n\n/**\n * Initialize Firebase Admin based on environment\n * Uses provider which handles both Firebase Functions and Vercel\n */\nexport async function initializeFirebaseAdmin() {\n return await getFirebaseAdminApp();\n}\n", "// packages/functions/src/shared/utils/internal/idempotency.ts\n\n/**\n * @fileoverview Idempotency utilities for functions\n * @description Provides idempotency checking and storage for function calls\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { logger } from 'firebase-functions/v2';\n\nimport { getFirebaseAdminFirestore } from '@donotdev/firebase/server';\n\n/** Stored result of a previously processed idempotent operation. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport interface IdempotencyResult<T = any> {\n result: T;\n processedAt: string;\n processedBy: string;\n}\n\n/**\n * Check if an operation has already been processed (idempotency check)\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport async function checkIdempotency<T = any>(\n key: string,\n operation: string\n): Promise<T | null> {\n const db = getFirebaseAdminFirestore();\n try {\n const idempotencyRef = db\n .collection('idempotency')\n .doc(`${operation}_${key}`);\n const idempotencyDoc = await idempotencyRef.get();\n\n if (idempotencyDoc.exists) {\n const data = idempotencyDoc.data() as IdempotencyResult<T>;\n logger.info('Operation already processed (idempotency)', {\n key,\n operation,\n processedAt: data.processedAt,\n processedBy: data.processedBy,\n });\n return data.result;\n }\n\n return null;\n } catch (error) {\n logger.error('Idempotency check failed', {\n key,\n operation,\n error: error instanceof Error ? error.message : String(error),\n });\n // Fail closed \u2014 duplicate processing is worse than a transient failure\n throw new Error(\n `Idempotency check failed for ${operation}/${key}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n\n/**\n * Store the result of an operation for idempotency\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport async function storeIdempotencyResult<T = any>(\n key: string,\n operation: string,\n result: T,\n processedBy: string\n): Promise<void> {\n try {\n const db = getFirebaseAdminFirestore();\n const idempotencyRef = db\n .collection('idempotency')\n .doc(`${operation}_${key}`);\n await idempotencyRef.set({\n result,\n processedAt: new Date().toISOString(),\n processedBy,\n });\n\n logger.info('Idempotency result stored', {\n key,\n operation,\n processedBy,\n });\n } catch (error) {\n logger.error('Failed to store idempotency result', {\n key,\n operation,\n processedBy,\n error: error instanceof Error ? error.message : String(error),\n });\n // Don't throw - idempotency storage failure shouldn't break the operation\n }\n}\n", "// packages/functions/src/shared/utils/internal/validation.ts\n\n/**\n * @fileoverview Validation utility functions\n * @description Functions for validating environment and data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport { DoNotDevError } from '@donotdev/core/server';\n\n/**\n * Safely parses JSON with error handling\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function safeJsonParse<T = any>(json: string): T | null {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\n/**\n * Validates a Firestore collection name from client-supplied schema.\n *\n * W22: Vercel CRUD handlers accept `schema` (including collection name) from\n * the client. This is a known design limitation. As a defense-in-depth measure,\n * reject collection names that could be used for path traversal or access to\n * internal collections.\n *\n * @param name - Collection name to validate\n * @throws Error if the name is unsafe\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateCollectionName(name: string): void {\n if (!name || typeof name !== 'string') {\n throw new Error('Collection name is required');\n }\n if (name.includes('/') || name.includes('..') || name.startsWith('_')) {\n throw new Error(\n 'Invalid collection name: must not contain \"/\", \"..\", or start with \"_\"'\n );\n }\n}\n\n/**\n * Validates document data against an optional Valibot schema.\n *\n * W1: Previous stub ignored the schema parameter entirely. Now performs\n * actual schema validation when a schema is provided.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function validateDocument(data: any, schema?: any): void {\n // G63: Throw DoNotDevError instead of plain Error for consistent error handling\n if (!data || typeof data !== 'object') {\n throw new DoNotDevError('Invalid document data', 'invalid-argument');\n }\n\n if (Array.isArray(data)) {\n throw new DoNotDevError(\n 'Document data cannot be an array',\n 'invalid-argument'\n );\n }\n\n // W1: Perform schema validation when a Valibot schema is supplied.\n if (schema) {\n const result = v.safeParse(schema, data);\n if (!result.success) {\n const messages = result.issues\n .map(\n (issue) =>\n `${issue.path?.map((p: { key: string }) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Validation failed: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: result.issues } }\n );\n }\n }\n}\n", "// packages/functions/src/shared/oauth/exchangeToken.ts\n\n/**\n * @fileoverview OAuth Token Exchange Algorithm\n * @description Platform-agnostic algorithm for exchanging OAuth codes for tokens\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type {\n ExchangeTokenRequest,\n TokenResponse,\n} from '@donotdev/core/server';\n\n/** Platform-agnostic provider for exchanging OAuth authorization codes for tokens. */\nexport interface OAuthProvider {\n exchangeCodeForToken(params: {\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n }): Promise<TokenResponse>;\n}\n\n/**\n * Exchange OAuth code for token\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function exchangeTokenAlgorithm(\n request: ExchangeTokenRequest,\n oauthProvider: OAuthProvider\n): Promise<TokenResponse> {\n const { code, redirectUri, codeVerifier } = request;\n\n // Exchange code for token\n const tokenResponse = await oauthProvider.exchangeCodeForToken({\n code,\n redirectUri,\n codeVerifier,\n });\n\n return tokenResponse;\n}\n", "// packages/functions/src/shared/oauth/grantAccess.ts\n\n/**\n * @fileoverview Grant OAuth Access Algorithm\n * @description Platform-agnostic algorithm for granting OAuth access\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n/** Platform-agnostic provider for granting OAuth access to a user. */\nexport interface OAuthGrantProvider {\n grantAccess(params: {\n userId: string;\n provider: string;\n accessToken: string;\n refreshToken?: string;\n }): Promise<{ success: boolean; message: string }>;\n}\n\n/**\n * Grant OAuth access to user\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function grantAccessAlgorithm(\n userId: string,\n provider: string,\n accessToken: string,\n refreshToken: string | undefined,\n oauthProvider: OAuthGrantProvider\n): Promise<{ success: boolean; message: string }> {\n const result = await oauthProvider.grantAccess({\n userId,\n provider,\n accessToken,\n refreshToken,\n });\n\n return result;\n}\n", "// packages/functions/src/shared/firebase.ts\n\n/**\n * @fileoverview Firebase data transformation utilities for functions\n * @description Server-safe functions for converting data between Firebase and application formats\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type { DateValue, FirestoreTimestamp } from '@donotdev/core/server';\n\n/**\n * Create a server-safe version of the Timestamp creation\n * @param date - The Date object to convert\n * @returns A representation of the timestamp\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createTimestamp(date: Date): FirestoreTimestamp {\n return {\n seconds: Math.floor(date.getTime() / 1000),\n nanoseconds: (date.getTime() % 1000) * 1000000,\n toDate: () => new Date(date),\n toMillis: () => date.getTime(),\n isEqual: (other: FirestoreTimestamp) =>\n other.seconds === Math.floor(date.getTime() / 1000) &&\n other.nanoseconds === (date.getTime() % 1000) * 1000000,\n valueOf: () =>\n `Timestamp(seconds=${Math.floor(date.getTime() / 1000)}, nanoseconds=${(date.getTime() % 1000) * 1000000})`,\n };\n}\n\n/**\n * Converts a Date or ISO string to a Firestore Timestamp.\n * @param date - The date to convert (string or Date)\n * @returns The Firestore Timestamp\n * @throws Error if the date is invalid\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function toTimestamp(date: string | Date): FirestoreTimestamp {\n try {\n if (typeof date === 'string') {\n const parsed = new Date(date);\n if (isNaN(parsed.getTime())) {\n throw new Error(`Invalid date string format: ${date}`);\n }\n return createTimestamp(parsed);\n }\n if (date instanceof Date) {\n if (isNaN(date.getTime())) {\n throw new Error('Invalid Date object');\n }\n return createTimestamp(date);\n }\n throw new Error('Date must be a string or Date object');\n } catch (error) {\n throw new Error(\n `Failed to convert to timestamp: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n}\n\n/**\n * Converts a Firestore Timestamp to an ISO string.\n * @param timestamp - The Firestore Timestamp\n * @returns The ISO string representation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function toISOString(timestamp: FirestoreTimestamp): string {\n return timestamp.toDate().toISOString();\n}\n\n/**\n * Checks if a value is a Firestore Timestamp.\n * @param value - The value to check\n * @returns True if the value is a Timestamp\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function isTimestamp(value: any): value is FirestoreTimestamp {\n return (\n value &&\n typeof value === 'object' &&\n typeof value.seconds === 'number' &&\n typeof value.nanoseconds === 'number' &&\n typeof value.toDate === 'function' &&\n typeof value.toMillis === 'function'\n );\n}\n\n/**\n * Whether a value looks like a Firestore DocumentSnapshot (id, ref, data()).\n */\nfunction isDocumentSnapshotLike(value: object): value is {\n id: unknown;\n ref: unknown;\n // why: Firestore DocumentSnapshot.data() contract; the return is not checked at runtime\n data: () => Record<string, unknown> | undefined;\n} {\n return (\n 'id' in value &&\n 'ref' in value &&\n 'data' in value &&\n typeof value.data === 'function'\n );\n}\n\n/**\n * Recursively transforms Firestore data to application format by converting Timestamps to ISO strings.\n * @param data - The data to transform\n * @param includeDocumentIds - Whether to include document IDs\n * @returns The transformed data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function transformFirestoreData<T = any>(\n data: T,\n includeDocumentIds: boolean = false\n): T {\n if (!data) return data;\n\n // Handle Firestore document with ID\n if (\n includeDocumentIds &&\n typeof data === 'object' &&\n data !== null &&\n isDocumentSnapshotLike(data)\n ) {\n const doc = data;\n const documentData = doc.data();\n return {\n id: doc.id,\n ...transformFirestoreData(documentData),\n } as T;\n }\n\n // Handle arrays\n if (Array.isArray(data)) {\n return data.map((item) => transformFirestoreData(item)) as unknown as T;\n }\n\n // Handle Timestamps\n if (isTimestamp(data)) {\n return toISOString(data) as unknown as T;\n }\n\n // Handle objects recursively\n if (typeof data === 'object' && data !== null) {\n const transformed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n transformed[key] = transformFirestoreData(value);\n }\n return transformed as T;\n }\n\n // Return primitive values unchanged\n return data;\n}\n\n/**\n * Recursively prepares data for Firestore by converting Date objects to ISO strings.\n * ISO strings are kept as-is (no conversion needed).\n * @param data - The data to prepare\n * @param removeFields - Optional array of field names to remove\n * @returns The prepared data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\nexport function prepareForFirestore<T = any>(\n data: T,\n removeFields: string[] = []\n): T {\n if (!data) return data;\n\n // Handle arrays\n if (Array.isArray(data)) {\n return data.map((item) =>\n prepareForFirestore(item, removeFields)\n ) as unknown as T;\n }\n\n // Handle objects recursively\n if (typeof data === 'object' && data !== null) {\n const prepared: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n // Skip fields that should be removed\n if (removeFields.includes(key)) {\n continue;\n }\n\n // Handle Date objects - convert to ISO string\n if (value instanceof Date) {\n prepared[key] = value.toISOString();\n }\n // ISO strings stay as strings - no conversion needed\n // Handle nested objects and arrays\n else {\n prepared[key] = prepareForFirestore(value, removeFields);\n }\n }\n return prepared as T;\n }\n\n // Handle Date objects at root level - convert to ISO string\n if (data instanceof Date) {\n return data.toISOString() as unknown as T;\n }\n\n // ISO strings stay as strings - no conversion needed\n\n // Return primitive values unchanged\n return data;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;iOAwDA,IAAMA,EAA0BC,EAAO,CACrC,QAAWC,EAAWC,EAAO,CAAC,EAC9B,kBAAqBD,EAAWC,EAAO,CAAC,CAC1C,CAAC,EAGKC,EAAmB,oBAGzB,SAASC,EAAmBC,EAAcC,EAAqB,CAC7D,GAAI,CAACH,EAAiB,KAAKE,CAAI,EAC7B,MAAM,IAAI,MACR,WAAWC,CAAK,kEAClB,CAEJ,CANSC,EAAAH,EAAA,sBAeF,IAAMI,EAAN,KAAuB,CAhF9B,MAgF8B,CAAAD,EAAA,yBACpB,OAER,YAAYE,EAAyB,CACnC,KAAK,OAAS,CACZ,QAAS,yBACT,GAAGA,CACL,CACF,CASA,MAAM,gBAAsC,CAE1C,OADiB,MAAM,KAAK,QAAoB,OAAO,CAEzD,CASA,MAAM,oBAAoBC,EAAgD,CACpEA,GACFN,EAAmBM,EAAU,UAAU,EAEzC,IAAMC,EAAWD,EAAW,UAAUA,CAAQ,SAAW,cAEzD,OADiB,MAAM,KAAK,QAA4BC,CAAQ,CAElE,CASA,MAAM,gBAAgBC,EAAmD,CACvER,EAAmBQ,EAAQ,MAAO,OAAO,EACzCR,EAAmBQ,EAAQ,KAAM,MAAM,EACvCR,EAAmBQ,EAAQ,SAAU,UAAU,EAC/C,GAAI,CACF,aAAM,KAAK,QACT,UAAUA,EAAQ,KAAK,IAAIA,EAAQ,IAAI,kBAAkBA,EAAQ,QAAQ,GACzE,CACE,OAAQ,MACR,KAAM,KAAK,UAAU,CACnB,WAAYA,EAAQ,YAAc,MACpC,CAAC,CACH,CACF,EACO,EACT,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AIxD,GAAIR,EAAYI,CAAI,EAClB,OAAON,EAAYM,CAAI,EAIzB,GAAI,OAAOA,GAAS,UAAYA,IAAS,KAAM,CAC7C,IAAMK,EAAuC,CAAC,EAC9C,OAAW,CAACC,EAAKT,CAAK,IAAK,OAAO,QAAQG,CAAI,EAC5CK,EAAYC,CAAG,EAAIP,EAAuBF,CAAK,EAEjD,OAAOQ,CACT,CAGA,OAAOL,CACT,CA1CgBX,EAAAU,EAAA,0BAwDT,SAASQ,EACdP,EACAQ,EAAyB,CAAC,EACvB,CACH,GAAI,CAACR,EAAM,OAAOA,EAGlB,GAAI,MAAM,QAAQA,CAAI,EACpB,OAAOA,EAAK,IAAKI,GACfG,EAAoBH,EAAMI,CAAY,CACxC,EAIF,GAAI,OAAOR,GAAS,UAAYA,IAAS,KAAM,CAC7C,IAAMS,EAAoC,CAAC,EAC3C,OAAW,CAACH,EAAKT,CAAK,IAAK,OAAO,QAAQG,CAAI,EAExCQ,EAAa,SAASF,CAAG,IAKzBT,aAAiB,KACnBY,EAASH,CAAG,EAAIT,EAAM,YAAY,EAKlCY,EAASH,CAAG,EAAIC,EAAoBV,EAAOW,CAAY,GAG3D,OAAOC,CACT,CAGA,OAAIT,aAAgB,KACXA,EAAK,YAAY,EAMnBA,CACT,CA5CgBX,EAAAkB,EAAA",
|
|
6
|
+
"names": ["GitHubErrorBodySchema", "object", "optional", "string", "SAFE_GITHUB_NAME", "validateGitHubName", "name", "label", "__name", "GitHubApiService", "config", "username", "endpoint", "request", "error", "owner", "repo", "org", "teamSlug", "role", "options", "url", "response", "errorBody", "parsed", "safeParse", "errorData", "createGitHubApiService", "accessToken", "logger", "StripeValidationSchemas", "object", "pipe", "string", "minLength", "any", "number", "minValue", "optional", "regex", "length", "validateWebhookEvent", "data", "parse", "error", "isValiError", "errors", "err", "p", "logger", "__name", "validatePurchaseRequest", "validateGitHubUsername", "username", "validateEmail", "email", "validateStripePriceId", "priceId", "validateStripeSessionId", "sessionId", "validateUrl", "url", "name", "parsedUrl", "validateMetadata", "metadata", "sanitized", "key", "value", "sanitizedValue", "validateRequestData", "data", "defaultSchema", "customSchema", "validationResult", "safeParse", "e", "__name", "withSchemaValidation", "handler", "request", "validation", "withVercelSchemaValidation", "req", "res", "createFirebaseFunction", "internalHandler", "createVercelFunction", "onCall", "createFirebaseCallable", "config", "defaultSchema", "handler", "internalHandler", "withSchemaValidation", "onCall", "request", "__name", "customSchema", "createFirebaseFunctionExports", "onCallFunction", "withSchema", "createVercelHandler", "defaultSchema", "handler", "withVercelSchemaValidation", "__name", "createVercelApiHandler", "method", "req", "res", "customSchema", "validation", "validateRequestData", "toISOString", "date", "parsed", "__name", "addMonths", "months", "result", "originalDate", "addYears", "years", "calculateSubscriptionEndDate", "duration", "startDate", "endDate", "findReferences", "collection", "documentId", "__name", "getTierFromPriceId", "priceId", "__name", "cancelUserSubscription", "firebaseUid", "subscription", "subscriptionClaims", "auth", "getFirebaseAdminAuth", "db", "getFirebaseAdminFirestore", "currentClaims", "error", "getUserSubscription", "initializeFirebaseAdmin", "getFirebaseAdminApp", "__name", "logger", "checkIdempotency", "key", "operation", "db", "getFirebaseAdminFirestore", "idempotencyDoc", "data", "logger", "error", "__name", "storeIdempotencyResult", "result", "processedBy", "safeJsonParse", "json", "__name", "validateCollectionName", "name", "validateDocument", "data", "schema", "DoNotDevError", "result", "safeParse", "messages", "issue", "p", "exchangeTokenAlgorithm", "request", "oauthProvider", "code", "redirectUri", "codeVerifier", "__name", "grantAccessAlgorithm", "userId", "provider", "accessToken", "refreshToken", "oauthProvider", "__name", "createTimestamp", "date", "__name", "other", "toTimestamp", "parsed", "error", "toISOString", "timestamp", "isTimestamp", "value", "isDocumentSnapshotLike", "transformFirestoreData", "data", "includeDocumentIds", "doc", "documentData", "item", "transformed", "key", "prepareForFirestore", "removeFields", "prepared"]
|
|
7
|
+
}
|
|
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{a as i}from"./chunk-
|
|
22
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
import{a as i}from"./chunk-W6W4L44F.js";import{a as u}from"./chunk-AYY7UXNI.js";async function d(){let{getFirebaseAdminFirestore:r}=await import("./server-24XGDDO3.js");return r()}u(d,"getFirestore");async function w(r){try{await(await d()).collection("payment_metrics").doc().set({...r,recordedAt:new Date().toISOString()}),i.info("Payment metrics recorded",{operation:r.operation,status:r.status,userId:r.userId})}catch(t){i.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:r})}}u(w,"recordPaymentMetrics");async function b(r=24){try{let t=await d(),e=new Date;e.setHours(e.getHours()-r);let c=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).get();if(c.empty)return{failureRate:0,shouldAlert:!1};let m=c.size,a=c.docs.filter(l=>l.data().status==="failed").length,s=a/m*100,n=s>10;return n&&await y(s,m,a),{failureRate:s,shouldAlert:n}}catch(t){return i.error("Failed to check payment failure rate",{error:t instanceof Error?t.message:String(t)}),{failureRate:0,shouldAlert:!1}}}u(b,"checkPaymentFailureRate");async function S(r=1e4){try{let t=await d(),e=new Date;e.setHours(0,0,0,0);let o=new Date(e);o.setDate(o.getDate()+1);let m=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).where("timestamp","<",o.toISOString()).where("status","==","success").get(),a=0;m.docs.forEach(n=>{let l=n.data();l.amount&&l.currency==="usd"&&(a+=l.amount/100)});let s=a>r;return s&&await p(a,r),{totalVolume:a,shouldAlert:s}}catch(t){return i.error("Failed to check payment volume",{error:t instanceof Error?t.message:String(t)}),{totalVolume:0,shouldAlert:!1}}}u(S,"checkPaymentVolume");async function y(r,t,e){try{await(await d()).collection("payment_alerts").doc().set({type:"payment_failure_rate",severity:"high",message:`Payment failure rate is ${r.toFixed(2)}% (${e}/${t} payments failed)`,data:{failureRate:r,totalPayments:t,failedPayments:e},triggeredAt:new Date().toISOString(),status:"active"}),i.error("PAYMENT FAILURE ALERT TRIGGERED",{failureRate:r,totalPayments:t,failedPayments:e})}catch(o){i.error("Failed to trigger payment failure alert",{error:o instanceof Error?o.message:String(o)})}}u(y,"triggerPaymentFailureAlert");async function p(r,t){try{await(await d()).collection("payment_alerts").doc().set({type:"high_payment_volume",severity:"medium",message:`Daily payment volume exceeded threshold: $${r.toFixed(2)} (threshold: $${t})`,data:{totalVolume:r,threshold:t},triggeredAt:new Date().toISOString(),status:"active"}),i.warn("HIGH PAYMENT VOLUME ALERT TRIGGERED",{totalVolume:r,threshold:t})}catch(e){i.error("Failed to trigger high volume alert",{error:e instanceof Error?e.message:String(e)})}}u(p,"triggerHighVolumeAlert");async function P(r,t){try{let c=await(await d()).collection("payment_metrics").where("timestamp",">=",r.toISOString()).where("timestamp","<=",t.toISOString()).get(),m=0,a=0,s=0,n=0;c.docs.forEach(g=>{let f=g.data();m++,f.status==="success"?(a++,f.amount&&f.currency==="usd"&&(n+=f.amount/100)):f.status==="failed"&&s++});let l=a>0?n/a:0;return{totalPayments:m,successfulPayments:a,failedPayments:s,totalVolume:n,averageAmount:l}}catch(e){return i.error("Failed to get payment metrics summary",{error:e instanceof Error?e.message:String(e)}),{totalPayments:0,successfulPayments:0,failedPayments:0,totalVolume:0,averageAmount:0}}}u(P,"getPaymentMetricsSummary");async function A(r=90,t=30){try{let e=await d(),o=new Date,c=new Date(o);c.setDate(c.getDate()-r);let m=await e.collection("payment_metrics").where("recordedAt","<",c.toISOString()).limit(500).get();if(!m.empty){let n=e.batch();m.docs.forEach(l=>n.delete(l.ref)),await n.commit()}let a=new Date(o);a.setDate(a.getDate()-t);let s=await e.collection("payment_alerts").where("triggeredAt","<",a.toISOString()).limit(500).get();if(!s.empty){let n=e.batch();s.docs.forEach(l=>n.delete(l.ref)),await n.commit()}i.info("Payment metrics cleanup completed",{deletedMetrics:m.size,deletedAlerts:s.size})}catch(e){i.error("Payment metrics cleanup failed",{error:e instanceof Error?e.message:String(e)})}}u(A,"cleanupOldMetrics");export{w as a,b,S as c,P as d,A as e};
|
|
22
|
+
//# sourceMappingURL=chunk-CVYSXC27.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/utils/internal/monitoring.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/utils/internal/monitoring.ts\n\n/**\n * @fileoverview Monitoring and alerting utilities for functions\n * @description Provides metrics collection and alerting for payment operations\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport { logger } from '../../logger.js';\n\n/**\n * Firestore, loaded on first use. `firebase-admin` is an optional peer:\n * Supabase deployments never load it.\n */\nasync function getFirestore() {\n const { getFirebaseAdminFirestore } =\n await import('@donotdev/firebase/server');\n return getFirebaseAdminFirestore();\n}\n\n/**\n * Payment metrics data structure\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport interface PaymentMetrics {\n operation: string;\n userId?: string;\n amount?: number;\n currency?: string;\n status: 'success' | 'failed' | 'pending';\n timestamp: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n metadata?: Record<string, any>;\n}\n\n/**\n * Alert threshold configuration\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport interface AlertThresholds {\n paymentFailureRate: number; // Percentage (0-100)\n paymentVolumeThreshold: number; // Daily volume threshold\n errorRateThreshold: number; // Percentage (0-100)\n}\n\n/**\n * Record payment metrics for monitoring\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function recordPaymentMetrics(\n metrics: PaymentMetrics\n): Promise<void> {\n try {\n const db = await getFirestore();\n const metricsRef = db.collection('payment_metrics').doc();\n await metricsRef.set({\n ...metrics,\n recordedAt: new Date().toISOString(),\n });\n\n logger.info('Payment metrics recorded', {\n operation: metrics.operation,\n status: metrics.status,\n userId: metrics.userId,\n });\n } catch (error) {\n logger.error('Failed to record payment metrics', {\n error: error instanceof Error ? error.message : String(error),\n metrics,\n });\n // Don't throw - metrics failure shouldn't break the operation\n }\n}\n\n/**\n * Check payment failure rate and trigger alerts if needed\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function checkPaymentFailureRate(\n timeWindowHours: number = 24\n): Promise<{ failureRate: number; shouldAlert: boolean }> {\n try {\n const db = await getFirestore();\n const cutoffTime = new Date();\n cutoffTime.setHours(cutoffTime.getHours() - timeWindowHours);\n\n const metricsRef = db.collection('payment_metrics');\n const recentMetrics = await metricsRef\n .where('timestamp', '>=', cutoffTime.toISOString())\n .get();\n\n if (recentMetrics.empty) {\n return { failureRate: 0, shouldAlert: false };\n }\n\n const totalPayments = recentMetrics.size;\n const failedPayments = recentMetrics.docs.filter(\n (doc) => doc.data().status === 'failed'\n ).length;\n\n const failureRate = (failedPayments / totalPayments) * 100;\n const shouldAlert = failureRate > 10; // Alert if failure rate > 10%\n\n if (shouldAlert) {\n await triggerPaymentFailureAlert(\n failureRate,\n totalPayments,\n failedPayments\n );\n }\n\n return { failureRate, shouldAlert };\n } catch (error) {\n logger.error('Failed to check payment failure rate', {\n error: error instanceof Error ? error.message : String(error),\n });\n return { failureRate: 0, shouldAlert: false };\n }\n}\n\n/**\n * Check daily payment volume and trigger alerts if needed\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function checkPaymentVolume(\n volumeThreshold: number = 10000 // $10,000 default threshold\n): Promise<{ totalVolume: number; shouldAlert: boolean }> {\n try {\n const db = await getFirestore();\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n const tomorrow = new Date(today);\n tomorrow.setDate(tomorrow.getDate() + 1);\n\n const metricsRef = db.collection('payment_metrics');\n const todayMetrics = await metricsRef\n .where('timestamp', '>=', today.toISOString())\n .where('timestamp', '<', tomorrow.toISOString())\n .where('status', '==', 'success')\n .get();\n\n let totalVolume = 0;\n todayMetrics.docs.forEach((doc) => {\n const data = doc.data();\n if (data.amount && data.currency === 'usd') {\n totalVolume += data.amount / 100; // Convert cents to dollars\n }\n });\n\n const shouldAlert = totalVolume > volumeThreshold;\n\n if (shouldAlert) {\n await triggerHighVolumeAlert(totalVolume, volumeThreshold);\n }\n\n return { totalVolume, shouldAlert };\n } catch (error) {\n logger.error('Failed to check payment volume', {\n error: error instanceof Error ? error.message : String(error),\n });\n return { totalVolume: 0, shouldAlert: false };\n }\n}\n\n/**\n * Trigger payment failure alert\n */\nasync function triggerPaymentFailureAlert(\n failureRate: number,\n totalPayments: number,\n failedPayments: number\n): Promise<void> {\n try {\n const db = await getFirestore();\n const alertRef = db.collection('payment_alerts').doc();\n await alertRef.set({\n type: 'payment_failure_rate',\n severity: 'high',\n message: `Payment failure rate is ${failureRate.toFixed(2)}% (${failedPayments}/${totalPayments} payments failed)`,\n data: {\n failureRate,\n totalPayments,\n failedPayments,\n },\n triggeredAt: new Date().toISOString(),\n status: 'active',\n });\n\n logger.error('PAYMENT FAILURE ALERT TRIGGERED', {\n failureRate,\n totalPayments,\n failedPayments,\n });\n\n // Here you could integrate with external alerting services like:\n // - Slack webhook\n // - Email service\n // - PagerDuty\n // - Custom notification system\n } catch (error) {\n logger.error('Failed to trigger payment failure alert', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Trigger high volume alert\n */\nasync function triggerHighVolumeAlert(\n totalVolume: number,\n threshold: number\n): Promise<void> {\n try {\n const db = await getFirestore();\n const alertRef = db.collection('payment_alerts').doc();\n await alertRef.set({\n type: 'high_payment_volume',\n severity: 'medium',\n message: `Daily payment volume exceeded threshold: $${totalVolume.toFixed(2)} (threshold: $${threshold})`,\n data: {\n totalVolume,\n threshold,\n },\n triggeredAt: new Date().toISOString(),\n status: 'active',\n });\n\n logger.warn('HIGH PAYMENT VOLUME ALERT TRIGGERED', {\n totalVolume,\n threshold,\n });\n } catch (error) {\n logger.error('Failed to trigger high volume alert', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Get payment metrics summary for a time period\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function getPaymentMetricsSummary(\n startDate: Date,\n endDate: Date\n): Promise<{\n totalPayments: number;\n successfulPayments: number;\n failedPayments: number;\n totalVolume: number;\n averageAmount: number;\n}> {\n try {\n const db = await getFirestore();\n const metricsRef = db.collection('payment_metrics');\n const metrics = await metricsRef\n .where('timestamp', '>=', startDate.toISOString())\n .where('timestamp', '<=', endDate.toISOString())\n .get();\n\n let totalPayments = 0;\n let successfulPayments = 0;\n let failedPayments = 0;\n let totalVolume = 0;\n\n metrics.docs.forEach((doc) => {\n const data = doc.data();\n totalPayments++;\n\n if (data.status === 'success') {\n successfulPayments++;\n if (data.amount && data.currency === 'usd') {\n totalVolume += data.amount / 100; // Convert cents to dollars\n }\n } else if (data.status === 'failed') {\n failedPayments++;\n }\n });\n\n const averageAmount =\n successfulPayments > 0 ? totalVolume / successfulPayments : 0;\n\n return {\n totalPayments,\n successfulPayments,\n failedPayments,\n totalVolume,\n averageAmount,\n };\n } catch (error) {\n logger.error('Failed to get payment metrics summary', {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n totalPayments: 0,\n successfulPayments: 0,\n failedPayments: 0,\n totalVolume: 0,\n averageAmount: 0,\n };\n }\n}\n\n/**\n * Clean up old metrics and alerts (call periodically)\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cleanupOldMetrics(\n metricsRetentionDays: number = 90,\n alertsRetentionDays: number = 30\n): Promise<void> {\n try {\n const db = await getFirestore();\n const now = new Date();\n\n // Clean up old metrics\n const metricsCutoff = new Date(now);\n metricsCutoff.setDate(metricsCutoff.getDate() - metricsRetentionDays);\n\n const oldMetrics = await db\n .collection('payment_metrics')\n .where('recordedAt', '<', metricsCutoff.toISOString())\n .limit(500)\n .get();\n\n if (!oldMetrics.empty) {\n const batch = db.batch();\n oldMetrics.docs.forEach((doc) => batch.delete(doc.ref));\n await batch.commit();\n }\n\n // Clean up old alerts\n const alertsCutoff = new Date(now);\n alertsCutoff.setDate(alertsCutoff.getDate() - alertsRetentionDays);\n\n const oldAlerts = await db\n .collection('payment_alerts')\n .where('triggeredAt', '<', alertsCutoff.toISOString())\n .limit(500)\n .get();\n\n if (!oldAlerts.empty) {\n const batch = db.batch();\n oldAlerts.docs.forEach((doc) => batch.delete(doc.ref));\n await batch.commit();\n }\n\n logger.info('Payment metrics cleanup completed', {\n deletedMetrics: oldMetrics.size,\n deletedAlerts: oldAlerts.size,\n });\n } catch (error) {\n logger.error('Payment metrics cleanup failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;gFAiBA,eAAeA,GAAe,CAC5B,GAAM,CAAE,0BAAAC,CAA0B,EAChC,KAAM,QAAO,sBAA2B,EAC1C,OAAOA,EAA0B,CACnC,CAJeC,EAAAF,EAAA,gBA4Cf,eAAsBG,EACpBC,EACe,CACf,GAAI,CAGF,MAFW,MAAMJ,EAAa,GACR,WAAW,iBAAiB,EAAE,IAAI,EACvC,IAAI,CACnB,GAAGI,EACH,WAAY,IAAI,KAAK,EAAE,YAAY,CACrC,CAAC,EAEDC,EAAO,KAAK,2BAA4B,CACtC,UAAWD,EAAQ,UACnB,OAAQA,EAAQ,OAChB,OAAQA,EAAQ,MAClB,CAAC,CACH,OAASE,EAAO,CACdD,EAAO,MAAM,mCAAoC,CAC/C,MAAOC,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EAC5D,QAAAF,CACF,CAAC,CAEH,CACF,CAvBsBF,EAAAC,EAAA,wBAgCtB,eAAsBI,EACpBC,EAA0B,GAC8B,CACxD,GAAI,CACF,IAAMC,EAAK,MAAMT,EAAa,EACxBU,EAAa,IAAI,KACvBA,EAAW,SAASA,EAA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IAAI,EAEP,GAAI,CAACC,EAAW,MAAO,CACrB,IAAMC,EAAQ7B,EAAG,MAAM,EACvB4B,EAAW,KAAK,QAASvB,GAAQwB,EAAM,OAAOxB,EAAI,GAAG,CAAC,EACtD,MAAMwB,EAAM,OAAO,CACrB,CAGA,IAAMC,EAAe,IAAI,KAAKJ,CAAG,EACjCI,EAAa,QAAQA,EAAa,QAAQ,EAAIL,CAAmB,EAEjE,IAAMM,EAAY,MAAM/B,EACrB,WAAW,gBAAgB,EAC3B,MAAM,cAAe,IAAK8B,EAAa,YAAY,CAAC,EACpD,MAAM,GAAG,EACT,IAAI,EAEP,GAAI,CAACC,EAAU,MAAO,CACpB,IAAMF,EAAQ7B,EAAG,MAAM,EACvB+B,EAAU,KAAK,QAAS1B,GAAQwB,EAAM,OAAOxB,EAAI,GAAG,CAAC,EACrD,MAAMwB,EAAM,OAAO,CACrB,CAEAjC,EAAO,KAAK,oCAAqC,CAC/C,eAAgBgC,EAAW,KAC3B,cAAeG,EAAU,IAC3B,CAAC,CACH,OAASlC,EAAO,CACdD,EAAO,MAAM,iCAAkC,CAC7C,MAAOC,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAC9D,CAAC,CACH,CACF,CAjDsBJ,EAAA8B,EAAA",
|
|
6
|
+
"names": ["getFirestore", "getFirebaseAdminFirestore", "__name", "recordPaymentMetrics", "metrics", "logger", "error", "checkPaymentFailureRate", "timeWindowHours", "db", "cutoffTime", "recentMetrics", "totalPayments", "failedPayments", "doc", "failureRate", "shouldAlert", "triggerPaymentFailureAlert", "checkPaymentVolume", "volumeThreshold", "today", "tomorrow", "todayMetrics", "totalVolume", "data", "triggerHighVolumeAlert", "threshold", "getPaymentMetricsSummary", "startDate", "endDate", "successfulPayments", "averageAmount", "cleanupOldMetrics", "metricsRetentionDays", "alertsRetentionDays", "now", "metricsCutoff", "oldMetrics", "batch", "alertsCutoff", "oldAlerts"]
|
|
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-W6W4L44F.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-24XGDDO3.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-HZM5X5A7.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 r}from"./chunk-AYY7UXNI.js";var Ee={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"};var Ie={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},We={[Ee.PERMISSION_DENIED]:{type:Ie.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[Ee.NOT_FOUND]:{type:Ie.NOT_FOUND,message:"The requested resource was not found"},[Ee.ALREADY_EXISTS]:{type:Ie.ALREADY_EXISTS,message:"The resource already exists"},[Ee.INVALID_ARGUMENT]:{type:Ie.VALIDATION_ERROR,message:"Invalid argument provided"}};function ln(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}r(ln,"hasCaptureStackTrace");var k=class e extends Error{static{r(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=Ee.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.userMessageProvided,this.name=this.constructor.name,ln(Error)&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var $={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Ce={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},oi={[$.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[$.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[$.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}};var si={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},ai=4,ui={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};var we,cn={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Ge(e){return!e&&!we?cn:{lang:e?.lang??we?.lang,message:e?.message,abortEarly:e?.abortEarly??we?.abortEarly,abortPipeEarly:e?.abortPipeEarly??we?.abortPipeEarly}}r(Ge,"getGlobalConfig");var pn;function dn(e){return pn?.get(e)}r(dn,"getGlobalMessage");var fn;function mn(e){return fn?.get(e)}r(mn,"getSchemaMessage");var yn;function gn(e,t){return yn?.get(e)?.get(t)}r(gn,"getSpecificMessage");function te(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}r(te,"_stringify");function x(e,t,n,o,a){let u=a&&"input"in a?a.input:n.value,l=a?.expected??e.expects??null,m=a?.received??te(u),d={kind:e.kind,type:e.type,input:u,expected:l,received:m,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",f=a?.message??e.message??gn(e.reference,d.lang)??(h?mn(d.lang):null)??o.message??dn(d.lang);f!==void 0&&(d.message=typeof f=="function"?f(d):f),h&&(n.typed=!1),n.issues?n.issues.push(d):n.issues=[d]}r(x,"_addIssue");function hn(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}r(hn,"_isSameValueZero");function mt(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}r(mt,"_isValidObjectKey");function Ke(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}r(Ke,"_joinExpects");function A(e){return e["~standard"]={version:1,vendor:"valibot",validate:r(t=>e["~run"]({value:t},Ge()),"validate")},e}r(A,"_standardSchema");var Oe=class extends Error{static{r(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function ci(e){return e instanceof Oe}r(ci,"isValiError");var vn=/^[\w+-]+(?:\.[\w+-]+)*@[\da-zA-Z]+(?:[.-][\da-zA-Z]+)*\.[a-zA-Z]{2,}$/u,pi=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u");var bn=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;function ne(e,t){return{kind:"validation",type:"check",reference:ne,async:!1,expects:null,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement(n.value)&&x(this,"input",n,o),n}}}r(ne,"check");function B(e){return{kind:"validation",type:"email",reference:B,expects:null,async:!1,requirement:vn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&x(this,"email",t,n),t}}}r(B,"email");function q(e){return{kind:"validation",type:"integer",reference:q,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&x(this,"integer",t,n),t}}}r(q,"integer");function de(e){return{kind:"validation",type:"iso_timestamp",reference:de,async:!1,expects:null,requirement:bn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&x(this,"timestamp",t,n),t}}}r(de,"isoTimestamp");function fe(e,t){return{kind:"validation",type:"length",reference:fe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length!==this.requirement&&x(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(fe,"length");function W(e,t){return{kind:"validation",type:"max_length",reference:W,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length>this.requirement&&x(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(W,"maxLength");function V(e,t){return{kind:"validation",type:"max_value",reference:V,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value<=this.requirement)&&x(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(V,"maxValue");function y(e,t){return{kind:"validation",type:"min_length",reference:y,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length<this.requirement&&x(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(y,"minLength");function R(e,t){return{kind:"validation",type:"min_value",reference:R,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value>=this.requirement)&&x(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(R,"minValue");function He(e){return{kind:"transformation",type:"raw_transform",reference:He,async:!1,"~run"(t,n){let o=e({dataset:t,config:n,addIssue:r(a=>x(this,a?.label??"input",t,n,a),"addIssue"),NEVER:null});return t.issues?t.typed=!1:t.value=o,t}}}r(He,"rawTransform");function j(e,t){return{kind:"validation",type:"regex",reference:j,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement.test(n.value)&&x(this,"format",n,o),n}}}r(j,"regex");function En(e){return{kind:"transformation",type:"transform",reference:En,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}r(En,"transform");function D(e){return{kind:"validation",type:"url",reference:D,async:!1,expects:null,requirement(t){try{return URL.canParse?URL.canParse(t):(new URL(t),!0)}catch{return!1}},message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&x(this,"URL",t,n),t}}}r(D,"url");var xn={abortEarly:!0};function yt(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}r(yt,"getFallback");function xe(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}r(xe,"getDefault");function re(){return A({kind:"schema",type:"any",reference:re,expects:"any",async:!1,"~run"(e){return e.typed=!0,e}})}r(re,"any");function g(e,t){return A({kind:"schema",type:"array",reference:g,expects:"Array",async:!1,item:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<a.length;u++){let l=a[u],m=this.item["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,value:l};for(let h of m.issues)h.path?h.path.unshift(d):h.path=[d],n.issues?.push(h);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else x(this,"type",n,o);return n}})}r(g,"array");function S(e){return A({kind:"schema",type:"boolean",reference:S,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:x(this,"type",t,n),t}})}r(S,"boolean");function Sn(e,t){return A({kind:"schema",type:"custom",reference:Sn,expects:"unknown",async:!1,check:e,message:t,"~run"(n,o){return this.check(n.value)?n.typed=!0:x(this,"type",n,o),n}})}r(Sn,"custom");function ze(e){return A({kind:"schema",type:"lazy",reference:ze,expects:"unknown",async:!1,getter:e,"~run"(t,n){return this.getter(t.value)["~run"](t,n)}})}r(ze,"lazy");function I(e,t){return A({kind:"schema",type:"literal",reference:I,expects:te(e),async:!1,literal:e,message:t,"~run"(n,o){return hn(n.value,this.literal)?n.typed=!0:x(this,"type",n,o),n}})}r(I,"literal");function Se(e,t){return A({kind:"schema",type:"loose_object",reference:Se,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=yt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(x(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}if(!n.issues||!o.abortEarly)for(let u in a)mt(a,u)&&!Object.prototype.hasOwnProperty.call(this.entries,u)&&(n.value[u]=a[u])}else x(this,"type",n,o);return n}})}r(Se,"looseObject");function Ye(e){return A({kind:"schema",type:"never",reference:Ye,expects:"never",async:!1,message:e,"~run"(t,n){return x(this,"type",t,n),t}})}r(Ye,"never");function O(e,t){return A({kind:"schema",type:"nullable",reference:O,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===null&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(O,"nullable");function N(e,t){return A({kind:"schema",type:"nullish",reference:N,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(N,"nullish");function E(e){return A({kind:"schema",type:"number",reference:E,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:x(this,"type",t,n),t}})}r(E,"number");function p(e,t){return A({kind:"schema",type:"object",reference:p,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=yt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(x(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}}else x(this,"type",n,o);return n}})}r(p,"object");function s(e,t){return A({kind:"schema",type:"optional",reference:s,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===void 0&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(s,"optional");function v(e,t){return A({kind:"schema",type:"picklist",reference:v,expects:Ke(e.map(te),"|"),async:!1,options:e,message:t,"~run"(n,o){return this.options.includes(n.value)?n.typed=!0:x(this,"type",n,o),n}})}r(v,"picklist");function b(e,t,n){return A({kind:"schema",type:"record",reference:b,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){o.typed=!0,o.value={};for(let l in u)if(mt(u,l)){let m=u[l],d=this.key["~run"]({value:l},a);if(d.issues){let f={type:"object",origin:"key",input:u,key:l,value:m};for(let T of d.issues)T.path=[f],o.issues?.push(T);if(o.issues||(o.issues=d.issues),a.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let f={type:"object",origin:"value",input:u,key:l,value:m};for(let T of h.issues)T.path?T.path.unshift(f):T.path=[f],o.issues?.push(T);if(o.issues||(o.issues=h.issues),a.abortEarly){o.typed=!1;break}}(!d.typed||!h.typed)&&(o.typed=!1),d.typed&&(o.value[d.value]=h.value)}}else x(this,"type",o,a);return o}})}r(b,"record");function i(e){return A({kind:"schema",type:"string",reference:i,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:x(this,"type",t,n),t}})}r(i,"string");function kn(e,t){return A({kind:"schema",type:"tuple",reference:kn,expects:"Array",async:!1,items:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<this.items.length;u++){let l=a[u],m=this.items[u]["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,value:l};for(let h of m.issues)h.path?h.path.unshift(d):h.path=[d],n.issues?.push(h);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else x(this,"type",n,o);return n}})}r(kn,"tuple");function ft(e){let t;if(e)for(let n of e)if(t)for(let o of n.issues)t.push(o);else t=n.issues;return t}r(ft,"_subIssues");function Y(e,t){return A({kind:"schema",type:"union",reference:Y,expects:Ke(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,o){let a,u,l;for(let m of this.options){let d=m["~run"]({value:n.value},o);if(d.typed)if(d.issues)u?u.push(d):u=[d];else{a=d;break}else l?l.push(d):l=[d]}if(a)return a;if(u){if(u.length===1)return u[0];x(this,"type",n,o,{issues:ft(u)}),n.typed=!0}else{if(l?.length===1)return l[0];x(this,"type",n,o,{issues:ft(l)})}return n}})}r(Y,"union");function w(){return A({kind:"schema",type:"unknown",reference:w,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}r(w,"unknown");function ie(e,t,n){return A({kind:"schema",type:"variant",reference:ie,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){let l,m=0,d=this.key,h=[],f=r((T,P)=>{for(let z of T.options){if(z.type==="variant")f(z,new Set(P).add(z.key));else{let J=!0,Q=0;for(let F of P){let pe=z.entries[F];if(F in u?pe["~run"]({typed:!1,value:u[F]},xn).issues:pe.type!=="exact_optional"&&pe.type!=="optional"&&pe.type!=="nullish"){J=!1,d!==F&&(m<Q||m===Q&&F in u&&!(d in u))&&(m=Q,d=F,h=[]),d===F&&h.push(z.entries[F].expects);break}Q++}if(J){let F=z["~run"]({value:u},a);(!l||!l.typed&&F.typed)&&(l=F)}}if(l&&!l.issues)break}},"parseOptions");if(f(this,new Set([this.key])),l)return l;x(this,"type",o,a,{input:u[d],expected:Ke(h,"|"),path:[{type:"object",origin:"value",input:u,key:d,value:u[d]}]})}else x(this,"type",o,a);return o}})}r(ie,"variant");function Xe(e,t,n){let o=e["~run"]({value:t},Ge(n));if(o.issues)throw new Oe(o.issues);return o.value}r(Xe,"parse");function c(...e){return A({...e[0],pipe:e,"~run"(t,n){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=o["~run"](t,n))}return t}})}r(c,"pipe");function M(e,t,n){let o=e["~run"]({value:t},Ge(n));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}r(M,"safeParse");var gt=p({role:v([Ce.USER,Ce.ASSISTANT,Ce.SYSTEM]),content:c(i(),y(1)),id:s(i()),createdAt:s(i())}),Ze=ze(()=>p({type:v(["string","number","boolean","array","object"]),description:s(i()),enum:s(g(i())),items:s(Ze),properties:s(b(i(),Ze)),required:s(g(i()))})),An=p({description:c(i(),y(1)),parameters:p({type:I("object"),properties:b(i(),Ze),required:s(g(i()))})}),Tn=p({id:i(),name:i(),args:b(i(),w())}),Rn=p({messages:c(g(gt),y(1)),provider:s(v([$.ANTHROPIC,$.OPENAI,$.GOOGLE])),model:s(i()),maxTokens:s(c(E(),q(),R(1))),temperature:s(c(E(),R(0),V(2))),systemPrompt:s(i()),stream:s(S()),tools:s(b(i(),An))}),In=p({promptTokens:E(),completionTokens:E(),totalTokens:E()}),yi=p({message:gt,usage:s(In),finishReason:s(i()),toolCalls:s(g(Tn))}),gi=p({provider:v([$.ANTHROPIC,$.OPENAI,$.GOOGLE]),model:s(i()),maxTokens:s(c(E(),q(),R(1))),temperature:s(c(E(),R(0),V(2))),systemPrompt:s(i())});function hi(e){return M(Rn,e)}r(hi,"validateAIChatRequest");var ht={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};var X={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};var Ai={FREE:"free",PRO:"pro",PREMIUM:"premium"};var vt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};var bt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function ke(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}r(ke,"picklistOptions");var Pi=p({id:i(),email:s(O(c(i(),B()))),displayName:s(O(i())),photoURL:s(O(c(i(),D()))),emailVerified:s(S()),lastLoginAt:s(i()),providerData:s(g(p({providerId:i(),uid:i(),email:s(O(c(i(),B()))),displayName:s(O(i())),photoURL:s(O(c(i(),D()))),phoneNumber:s(O(i()))}))),role:s(v(ke(X))),customClaims:s(b(i(),re()))}),me=p({tier:i(),status:i(),subscriptionEnd:O(c(i(),de())),updatedAt:c(i(),de()),isDefault:s(S()),features:s(g(i())),subscriptionId:s(O(i())),customerId:s(O(i())),cancelAtPeriodEnd:s(S())}),Di=p({...me.entries,userId:i(),isActive:s(S())}),_i=p({role:s(v(ke(X))),subscription:s(me),features:s(g(v(ke(vt)))),permissions:s(g(v(ke(bt)))),githubAccess:s(p({username:s(i()),teamAccess:s(g(i())),repoAccess:s(g(i()))}))});var Je={PAYMENT:"payment",SUBSCRIPTION:"subscription"};var Et=100,On=p({productId:c(i(),y(1),W(200)),quantity:c(E(),q(),R(1),V(1e4))}),eo=c(p({billingConfigKey:s(c(i(),y(1))),lineItems:s(c(g(On),y(1,"At least one line item is required"),W(Et,`At most ${Et} line items`))),successUrl:c(i(),D()),cancelUrl:c(i(),D()),customerEmail:s(c(i(),B())),metadata:s(b(i(),i())),allowPromotionCodes:s(S()),userId:s(i()),productId:s(i()),priceId:s(i()),currency:s(c(i(),fe(3,"Currency must be 3-letter ISO code"))),userEmail:s(c(i(),B())),mode:s(v([Je.PAYMENT,Je.SUBSCRIPTION]))}),He(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,a=o.billingConfigKey||o.metadata?.billingConfigKey;return a?{...o,billingConfigKey:a,lineItems:o.lineItems??[{productId:a,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),to=p({sessionId:i(),sessionUrl:O(c(i(),D()))}),Ae=c(i(),y(1),j(/\S/)),Pn=p({sessionId:Ae,billingConfigKey:Ae}),Dn=p({sessionId:Ae,orderId:Ae,billingConfigKey:Ae,sessionStatus:v(["open","complete","expired"]),paymentStatus:v(["paid","unpaid","no_payment_required"])});function no(e){return M(Pn,e)}r(no,"validateVerifyOrderCheckoutRequest");function ro(e){return M(Dn,e)}r(ro,"validateVerifyOrderCheckoutResult");var io=p({...me.entries,userId:i(),subscriptionId:O(i()),customerId:i(),cancelAtPeriodEnd:S()}),oo=p({id:i(),type:i(),data:p({object:re()}),created:c(i(),de())}),so=Se({userId:s(i()),firebaseUid:s(i()),productType:s(i())});var _n=p({type:I("StripePayment"),name:c(i(),y(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),fe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:s(c(i(),y(1,"Stripe price ID is required"))),tier:c(i(),y(1,"Tier is required")),duration:c(i(),y(1,"Duration is required")),allowPromotionCodes:s(S()),metadata:s(b(i(),i()))}),Fn=p({type:I("StripeSubscription"),name:c(i(),y(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),fe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:c(i(),y(1,"Stripe price ID is required")),tier:c(i(),y(1,"Tier is required")),duration:v(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:s(S()),metadata:s(b(i(),i()))}),Nn=ie("type",[_n,Fn]),ao=b(i(),Nn),uo=b(i(),p({name:i(),price:i(),currency:i(),description:s(i()),features:s(g(i())),priceId:s(i()),allowPromotionCodes:s(S())})),xt={name:i(),price:E(),currency:i(),priceId:s(i()),tier:i(),duration:i(),description:s(i()),metadata:s(b(i(),i())),allowPromotionCodes:s(S())},Un=ie("mode",[p({mode:I("manual"),taxRateIds:c(g(c(i(),y(1))),y(1))}),p({mode:I("automatic")})]),St=5,Mn=p({allowedCountries:c(g(c(i(),j(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),y(1)),shippingRateIds:s(c(g(c(i(),y(1))),W(St,`shippingRateIds: at most ${St} (Stripe limit)`)))}),Ln=p({type:I("StripeOrder"),name:i(),currency:c(i(),fe(3)),description:s(i()),metadata:s(b(i(),i())),allowPromotionCodes:s(S()),tax:Un,taxIdCollection:v(["disabled","optional","required"]),billingAddressCollection:v(["auto","required"]),shipping:s(Mn),customerCreation:v(["always","if_required"]),invoiceCreation:S(),paymentMethodConfiguration:s(c(i(),y(1)))}),Bn=b(i(),ie("type",[p({type:I("StripePayment"),...xt}),p({type:I("StripeSubscription"),...xt}),Ln]));function lo(e){return Xe(Bn,e)}r(lo,"validateStripeBackConfig");var bo={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},oe={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"};var G={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},kt=G.available,ye=Object.keys(G);function At(e){let t=ye.filter(n=>G[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}r(At,"onlyStatusThat");var Qe=At("isDefault"),et=At("isRemoved"),Vn=ye.filter(e=>G[e].read!=="guest"),Te=["id","createdAt","updatedAt","createdById","updatedById"],se={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"};var Tt=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var ko={EQ:se.EQ,NEQ:se.NEQ,LT:se.LT,LTE:se.LTE,GT:se.GT,GTE:se.GTE};var Rt=class extends Error{static{r(this,"BulkCollisionError")}collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}};var Po=p({collection:c(i(),y(1,"Collection name is required")),data:b(i(),w()),idempotencyKey:s(i())}),Do=p({collection:c(i(),y(1,"Collection name is required")),id:c(i(),y(1,"Entity ID is required"))}),_o=p({collection:c(i(),y(1,"Collection name is required")),id:c(i(),y(1,"Entity ID is required")),data:b(i(),w()),merge:s(S(),!1)}),Fo=p({collection:c(i(),y(1,"Collection name is required")),id:c(i(),y(1,"Entity ID is required"))}),No=p({collection:c(i(),y(1,"Collection name is required")),limit:s(c(E(),R(1),V(1e3)),1e3),offset:s(c(E(),R(0)),0),orderBy:s(i()),orderDirection:s(v(["asc","desc"]),"desc"),where:s(g(p({field:i(),operator:v(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:w()})))});var $n=p({templateId:c(i(),y(1)),to:c(i(),B()),data:b(i(),w()),locale:s(c(i(),y(2),W(5)),"fr"),from:s(i()),replyTo:s(i())}),zo=p({success:S(),messageId:s(i()),error:s(i())});function Yo(e){return M($n,e)}r(Yo,"validateSendEmailRequest");var It=["pull","push","admin","maintain","triage"];var tt=p({owner:c(i(),y(1,"Repository owner is required")),repo:c(i(),y(1,"Repository name is required"))}),qn=v([...It]),Fs=p({userId:c(i(),y(1,"User ID is required")),githubUsername:c(i(),y(1,"GitHub username is required")),repoConfig:tt,permission:s(qn,"push"),customClaims:s(b(i(),re()))}),Ns=p({userId:c(i(),y(1,"User ID is required")),githubUsername:c(i(),y(1,"GitHub username is required")),repoConfig:tt}),Us=p({userId:c(i(),y(1,"User ID is required")),githubUsername:c(i(),y(1,"GitHub username is required")),repoConfig:tt}),Ms=p({provider:i(),purpose:v(["authentication","api-access"]),code:c(i(),y(1,"Authorization code is required")),redirectUri:c(i(),D("Valid redirect URI is required")),codeVerifier:s(i()),state:s(i()),instance:s(c(i(),D()))}),Ls=p({provider:i(),refreshToken:c(i(),y(1,"Refresh token is required")),redirectUri:c(i(),D("Valid redirect URI is required"))}),Bs=p({provider:i()}),Vs=p({userId:c(i(),y(1,"User ID is required"))});var Ct=p({name:i(),color:i(),icon:i(),customParameters:s(b(i(),i())),button:p({backgroundColor:i(),textColor:i(),borderColor:i(),hoverBackgroundColor:i(),focusOutlineColor:i(),fontWeight:s(i(),"500"),textKey:s(i())})}),Wn=p({...Ct.entries,type:v(["auth","both"]),scopes:s(g(i())),firebaseProviderId:s(i())}),Pe=Y([I(""),c(i(),D())]),Gn=p({authUrl:Pe,tokenUrl:Pe,profileUrl:Pe,revokeUrl:s(Pe)}),Kn=p({authentication:s(g(i())),"api-access":g(i())}),Hn=s(p({pkce:s(S(),!1),codeChallengeMethod:s(v(["S256","plain"]),"S256")})),zn=p({...Ct.entries,type:v(["oauth","both"]),scopes:Kn,endpoints:Gn,capabilities:Hn});var Hs={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},zs=b(i(),Wn),Ys=b(i(),zn);var wt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"};var sa={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:wt.ANALYTICS},marketing:{requiresConsent:wt.MARKETING}};function Ot(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}r(Ot,"detectErrorSource");function K(e){return(t,n)=>{if(t instanceof k)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new k(n||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let a=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(a=e.errorCodeMapping[o]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[o]),u||(u=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new k(n||u,a,{details:l,source:e.errorSource})}}r(K,"createErrorHandler");var De={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var ge={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Yn={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},nt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function Xn(e){return e in nt}r(Xn,"isEntityHookErrorType");var Z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...De},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...De},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(Yn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:r(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:r(e=>{let t={originalError:e};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:De,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ge.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:r(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ge["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ge.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:r(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},Zn=r(e=>e instanceof Oe?new k(ge["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):K(Z.validation)(e),"handleValidationError"),Jn=r(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&Xn(e.type)){let t=nt[e.type]||"unknown";return new k(e.message||ge[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&We[e.code]){let t=We[e.code];if(t){let n=nt[t.type]||"unknown";return new k(t.message||ge[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return K(Z.entity)(e)},"handleEntityError"),Pt={auth:K(Z.auth),oauth:K(Z.oauth),api:K(Z.api),firebase:K(Z.firebase),ui:K(Z.ui),validation:Zn,entity:Jn,unknown:K(Z.unknown)};function _e(e,t,n){return e instanceof k?e:(Pt[t]||Pt.unknown)(e,n)}r(_e,"mapToDoNotDevError");function Dt(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,l])=>{if(typeof l!="function"&&u!=="originalError")try{a.setExtra(u,l)}catch{a.setExtra(u,`[${typeof l}]`)}}),Object.entries(n).forEach(([u,l])=>{if(typeof l!="function")try{a.setExtra(`context.${u}`,l)}catch{a.setExtra(`context.${u}`,`[${typeof l}]`)}}),(e.details?.userId||n.userId)&&a.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}r(Dt,"captureErrorToSentry");function Qn(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}r(Qn,"isDev");function Fe(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:a={},log:u=!0,reportToSentry:l=!0,showNotification:m=!1,severity:d="error"}=n,h=Ot(e),f=e instanceof k?e:_e(e,h,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new k(o,f.code,{details:{...f.details,originalMessage:f.message},source:h,userMessageProvided:!0}):f=new k(f.message,f.code,{details:{...f.details,userMessage:o},source:h,userMessageProvided:!0})),u){let T=Qn()||typeof window<"u"&&window.__DNDEV_DEBUG,P={code:f.code,message:f.message,source:h};switch(d){case"warning":console.warn(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details}:P);break;case"info":console.info(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details}:P);break;case"success":console.log(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details}:P);break;default:console.error(`[DoNotDev] ${f.code}: ${f.message}`,T?{...P,details:f.details,stack:f.stack}:P)}}return l&&Dt(f,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),f}r(Fe,"handleError");function cu(e,t,n,o){let a=o?` ${JSON.stringify(o)}`:"",u=`${t}.${n}(${a})`,l=_e(e,"auth",`${u}: ${er(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&l.code==="unknown"&&e.code!=="unknown"?new k(l.message,l.code,{details:{...l.details,originalCode:e.code},source:l.source}):l}r(cu,"wrapAuthError");function er(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}r(er,"getErrorMessage");var _t={[X.GUEST]:0,[X.USER]:1,[X.ADMIN]:2,[X.SUPER]:3};function ae(e,t){if(!e)return!1;let n=_t[e]??-1,o=_t[t]??1/0;return n>=o}r(ae,"hasRoleAccess");var Ft="__DNDEV_SINGLETONS__";function tr(){if(typeof globalThis<"u"){let e=globalThis,t=e[Ft];if(t)return t;let n=new Map;return e[Ft]=n,n}return new Map}r(tr,"getSingletonRegistry");function rt(e,t){let n=tr();return n.has(e)||n.set(e,t()),n.get(e)}r(rt,"getGlobalSingleton");function gu(e,...t){let n=null,o=!1;return r(function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}},"getInstance")}r(gu,"createSingleton");function Nt(){return rt("providers",()=>({providers:null}))}r(Nt,"getProviderState");function Eu(e){let{providers:t}=Nt();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}r(Eu,"getProvider");function xu(e){return!!Nt().providers?.[e]}r(xu,"hasProvider");function nr(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}r(nr,"hasVisibility");function rr(e){if(nr(e))return e.visibility}r(rr,"getFieldVisibility");function ir(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?ae(t,"admin"):n==="owner"?!1:ae(t,n)}r(ir,"isFieldVisible");function or(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}r(or,"isOwnerVisible");function Ut(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let o=e.entries,a=[],{documentData:u,uid:l,ownership:m}=n??{},d=m&&l!=null&&u&&or(u,l,m);for(let[h,f]of Object.entries(o)){let T=rr(f);if(T==="owner"){d&&a.push(h);continue}ir(T,t)&&a.push(h)}return a}r(Ut,"getVisibleFields");function Cu(e,t,n,o){if(!e)return{};let a=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,u=Ut(t,n,a),l={};for(let m of u)Object.prototype.hasOwnProperty.call(e,m)&&(l[m]=e[m]);return l}r(Cu,"filterVisibleFields");function it(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}r(it,"getListCardFieldNames");var sr=new Set(["http:","https:","mailto:","tel:","blob:"]);function _u(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(sr.has(n.protocol))return t}catch{return t}return""}r(_u,"sanitizeHref");var Mt=ye.map(e=>({value:e,label:`crud:status.${e}`}));var Mu=[...Te,"status"];function Lt(e){return Te.some(t=>t===e)}r(Lt,"isBackendGeneratedField");var Ne={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Mt]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var ot=["text","textarea","richtext","field-array"];function Ue(e){return`${e}I18n`}r(Ue,"i18nFieldName");function Me(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}r(Me,"addMonths");function Bt(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}r(Bt,"addYears");function wc(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=Me(t,1):e==="3months"?n=Me(t,3):e==="6months"?n=Me(t,6):e==="1year"?n=Bt(t,1):e==="2years"?n=Bt(t,2):n=Me(t,1),n.toISOString()}r(wc,"calculateSubscriptionEndDate");function L(e){let t=e?.status;return typeof t=="string"?t:null}r(L,"statusOf");function Be({op:e,status:t,storedStatus:n}){return Le(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}r(Be,"writeSchemaFor");function Vt({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let o=t??n;return o==null||o===n?!1:Le(n,"holdIncomplete")&&!Le(o,"holdIncomplete")}r(Vt,"entersVisibleStatus");function jt(e){return e!=null&&Object.hasOwn(G,e)?G[e]:kt}r(jt,"statusRow");function Le(e,t){return jt(e)[t]}r(Le,"statusCan");function Ve(e,t){let n=jt(e).read;return n==="guest"||ae(t,n)}r(Ve,"statusReadableBy");function st(e){return Object.keys(G).filter(t=>G[t][e])}r(st,"statusesThat");var je=r(e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(y(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(W(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(j(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?c(i(),...t):i()},"textValue"),ur=r(()=>c(i(),B("Invalid email address")),"emailValue"),lr=r(e=>e.validation?.minLength!==void 0?c(i(),y(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):i(),"passwordValue"),cr=r(()=>c(i(),D("Invalid URL")),"urlValue"),he=r(e=>{let t=[];return e.validation?.min!==void 0&&t.push(R(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(V(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?c(E(),...t):E()},"numberValue"),$t=r(()=>S(),"booleanValue"),at=r(()=>c(i(),ne(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),"dateValue"),pr=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,dr=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,fr=/^\d{4}-(?:0[1-9]|1[0-2])$/,mr=r(()=>c(i(),j(pr,"Invalid time format")),"timeValue"),yr=r(()=>c(i(),j(dr,"Invalid week format")),"weekValue"),gr=r(()=>c(i(),j(fr,"Invalid month format")),"monthValue"),Zt=p({url:i(),filename:i(),size:E(),mimeType:N(i()),uploadedAt:N(i())}),qt=r(()=>Zt,"fileValue"),Wt=r(()=>g(Zt),"filesValue"),Jt=p({fullUrl:i(),thumbUrl:i()}),hr=r(()=>Y([i(),Jt]),"pictureValue"),vr=r(()=>g(Y([i(),Jt])),"picturesValue"),br=r(()=>p({lat:E(),lng:E()}),"geopointValue"),Er=r(()=>p({formatted_address:i(),latitude:E(),longitude:E(),street_number:N(i()),route:N(i()),locality:N(i()),administrative_area_level_1:N(i()),administrative_area_level_2:N(i()),country:N(i()),postal_code:N(i())}),"addressValue"),xr=r(()=>b(i(),w()),"mapValue"),Sr=r(()=>g(w()),"arrayValue"),kr=r(()=>g(b(i(),w())),"fieldArrayValue"),ut=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?v(t.map(n=>n.value)):Y([i(),E()])},"selectValue"),Ar=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?g(v(t.map(n=>n.value))):g(i())},"multiselectValue"),Qt=r(()=>c(i(),y(1,"Invalid ID format")),"referenceValue"),lt=r(()=>i(),"stringValue"),Tr=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,Rr=r(e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Tr;return c(i(),j(t,"Invalid phone number"))},"telValue"),Ir=r(e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return c(i(),y(t,`IBAN must be at least ${t} characters`),W(n,`IBAN must not exceed ${n} characters`),j(new RegExp(o),"Invalid IBAN format"))},"ibanValue"),Gt=r(()=>Ye(),"neverValue");function en(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}r(en,"stringSwitchValues");var Cr=r(e=>{let t=en(e);return t?v(t):S()},"switchValue"),Kt=Se({gdprConsent:I(!0),gdprConsentDate:s(i()),gdprConsentVersion:s(i())},"GDPR consent must be given"),wr=r(e=>e.validation?.required?Kt:Y([I(!1),Kt]),"gdprConsentValue"),Or=r(()=>p({amount:E(),currency:s(i()),vatIncluded:s(S()),discountPercent:s(c(E(),R(0),V(100)))}),"priceValue"),tn={text:{schema:je,kind:"text"},textarea:{schema:je,kind:"text"},richtext:{schema:je,kind:"text"},color:{schema:je,kind:"text"},email:{schema:ur,kind:"text"},password:{schema:lr,kind:"text"},url:{schema:cr,kind:"text"},tel:{schema:Rr,kind:"text"},iban:{schema:Ir,kind:"text"},number:{schema:he,kind:"number"},currency:{schema:he,kind:"number"},range:{schema:he,kind:"number"},year:{schema:he,kind:"number"},rating:{schema:he,kind:"number"},duration:{schema:he,kind:"number"},price:{schema:Or,kind:"json"},boolean:{schema:$t,kind:"boolean"},checkbox:{schema:$t,kind:"boolean"},switch:{schema:Cr,kind:r(e=>en(e)?"text":"boolean","kind")},gdprConsent:{schema:wr,kind:"json"},date:{schema:at,kind:"date"},"datetime-local":{schema:at,kind:"timestamp"},timestamp:{schema:at,kind:"timestamp"},time:{schema:mr,kind:"time"},week:{schema:yr,kind:"text"},month:{schema:gr,kind:"text"},file:{schema:qt,kind:"json"},files:{schema:Wt,kind:"json"},document:{schema:qt,kind:"json"},documents:{schema:Wt,kind:"json"},image:{schema:hr,kind:"json"},images:{schema:vr,kind:"json"},geopoint:{schema:br,kind:"json"},address:{schema:Er,kind:"json"},map:{schema:xr,kind:"json"},array:{schema:Sr,kind:"json"},"field-array":{schema:kr,kind:"json"},select:{schema:ut,kind:"text"},radio:{schema:ut,kind:"text"},combobox:{schema:ut,kind:"text"},multiselect:{schema:Ar,kind:"json"},reference:{schema:Qt,kind:"ref"},hidden:{schema:lt,kind:"text"},avatar:{schema:lt,kind:"text"},badge:{schema:lt,kind:"text"},submit:{schema:Gt,kind:"text"},reset:{schema:Gt,kind:"text"}},Pr=new Set(Tt);function Dr(e){return Pr.has(e)}r(Dr,"isBuiltInFieldType");var _r=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),Fr=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),Nr=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),Ur={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function H(e,t){return t in e?Reflect.get(e,t):void 0}r(H,"prop");function Ht(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}r(Ht,"kindOfScalar");function zt(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}r(zt,"commonKind");function $e(e){if(typeof e!="object"||e===null)return;let t=H(e,"type");if(typeof t!="string")return;let n=Mr(e,t),o=H(e,"pipe");if(Array.isArray(o))for(let a of o.slice(1)){if(typeof a!="object"||a===null)continue;let u=H(a,"kind"),l=H(a,"type");if(typeof l=="string"){if(u==="schema")n=$e(a);else if(u==="transformation")Nr.has(l)||(n=void 0);else if(u==="validation"){l==="integer"&&n==="number"&&(n="integer");let m=Ur[l];m&&n==="text"&&(n=m)}}}return n}r($e,"kindOfSchema");function Mr(e,t){if(_r.has(t))return $e(H(e,"wrapped"));if(Fr.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return Ht(H(e,"literal"));case"picklist":case"enum":{let n=H(e,"options");return Array.isArray(n)?zt(n.map(Ht)):void 0}case"union":case"variant":{let n=H(e,"options");if(!Array.isArray(n))return;let o=n.filter(a=>{let u=typeof a=="object"&&a!==null?H(a,"type"):void 0;return u!=="null"&&u!=="undefined"});return zt(o.map($e))}default:return}}r(Mr,"kindOfRoot");function Yt(e,t){let{kind:n}=tn[e];return typeof n=="function"?n(t):n}r(Yt,"builtinKind");function ct(e,t=e.name){let n=e.validation?.reference,o=n?{ref:n}:{},a=e.type,u=Dr(a)?a:void 0,l=e.validation?.schema;if(l){let m=(n?"ref":void 0)??$e(l)??(u?Yt(u,e):void 0);if(!m)throw new Error(`Field '${t}' (custom type '${a}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:l,kind:m,...o}}if(n)return{schema:Qt(),kind:"ref",...o};if(u)return{schema:tn[u].schema(e),kind:Yt(u,e)};throw new Error(`Field '${t}' has custom type '${a}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}r(ct,"resolveFieldValue");function Lr(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}r(Lr,"requirementOf");function Br(e,t){return t.visibility==="hidden"||t.editable===oe.GENERATED||Lt(e)?"never":t.editable===oe.FALSE?"program":t.editable===oe.COMPUTED?"derived":"user"}r(Br,"writeClassOf");function Vr(e,t){return(n,o)=>{if(t!=="user")return!1;let a=e.editable;return a===void 0||a===oe.TRUE?e.visibility!=="technical":a===oe.CREATE_ONLY?o==="create":typeof a=="string"?ae(n,a):!1}}r(Vr,"editableForOf");function jr(e,t,n){let o=Br(e,t);return{value:ct(t,`${n}.${e}`),required:Lr(t),write:o,editableFor:Vr(t,o),visibleAt:t.visibility,...t.i18n===!0&&{companion:Ue(e)}}}r(jr,"describeField");var Xt=new WeakMap;function pt(e){let t=Xt.get(e);if(t)return t;let n={};for(let[a,u]of Object.entries(e.fields))n[a]=jr(a,u,e.name);let o={name:e.name,collection:e.collection,fields:n};return Xt.set(e,o),o}r(pt,"describeEntity");function $r(e,t){return t?c(e,ne(n=>n!=="","Required")):N(e)}r($r,"applyRequired");function ue(e){return $r(ct(e).schema,e.validation?.required)}r(ue,"getSchemaType");function ce(e,t){return Object.assign(e,{visibility:t})}r(ce,"withVisibility");function le(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}r(le,"withMetadata");function qr(e){let t=ue(e);return ce(t,e.visibility)}r(qr,"createFieldSchema");function Wr(e,t){if(!ot.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${ot.join(", ")}.`);let n=ue({...t,validation:{...t.validation,required:!1}});return ce(s(O(b(i(),n))),t.visibility)}r(Wr,"createTranslationsSchema");function ve(e,t){for(let n of Object.keys(e)){let o=t[n];o?.i18n===!0&&(e[Ue(n)]=Wr(n,o))}return e}r(ve,"withTranslations");function dt(e){let t=ue({...e,validation:{...e.validation,required:!1}});return ce(t,e.visibility)}r(dt,"createOptionalFieldSchema");function Gr(e){return e.validation?.required?ce(s(ue(e)),e.visibility):dt(e)}r(Gr,"createUpdateFieldSchema");function rp(e){let t=e.fields,n=pt(e).fields,o=r(C=>n[C]?.write==="never","isWriteExcluded"),a={};for(let[C,U]of Object.entries(t))n[C]?.visibleAt!=="hidden"&&(a[C]=dt(U));let u=le(p(ve({...a},t)),e),l={};for(let[C,U]of Object.entries(t))o(C)||(l[C]=qr(U));let m=le(p(ve({...l},t)),e),d={};for(let[C,U]of Object.entries(t))if(!o(C))if(C==="status"){let ee=v(st("saveIncomplete"));d[C]=ce(ee,U.visibility)}else d[C]=dt(U);let h=le(p(ve({...d},t)),e),f={};for(let[C,U]of Object.entries(t))o(C)||(f[C]=Gr(U));f.id=ce(ue(Ne.id),"technical");let T=le(p(ve({...f},t)),e),P;if(e.listFields&&e.listFields.length>0){let C=["id","status"],U=[...new Set([...C,...e.listFields])];P={};for(let ee of U){let be=a[ee];be&&(P[ee]=be)}}else P=a;let z=le(p(ve({...P},t)),e),J,Q=it(e);if(Q.length>0){let C=["id","status"],U=[...new Set([...C,...Q])];J={};for(let ee of U){let be=a[ee];be&&(J[ee]=be)}}else J=a;let F=le(p(ve({...J},t)),e),pe=le(p({id:ce(ue(Ne.id),"technical")}),e);return{create:m,draft:h,update:T,get:u,list:z,listCard:F,delete:pe}}r(rp,"createSchemas");var Kr=b(i(),w()),Hr=p({id:i(),patch:b(i(),w())}),zr=i(),sp=p({inserts:s(g(Kr)),updates:s(g(Hr)),deletes:s(g(zr))}),Yr=p({insertedIds:g(i()),updatedIds:g(i()),deletedIds:g(i())}),Xr=ie("op",[p({op:I("insert"),index:c(E(),q(),R(0)),id:s(i()),error:i()}),p({op:I("update"),id:i(),index:s(c(E(),q(),R(0))),error:i()}),p({op:I("delete"),id:i(),index:s(c(E(),q(),R(0))),error:i()})]),ap=p({...Yr.entries,failed:s(g(Xr),()=>[])});function up(e){let t=new Set((e.updates??[]).map(l=>l.id)),n=e.deletes??[],o=[];for(let l of n)t.has(l)&&o.push(l);if(o.length>0)return{collisions:o,where:"updates-deletes"};let a=e.inserts??[],u=[];for(let l of a)typeof l.id=="string"&&t.has(l.id)&&u.push(l.id);return u.length>0?{collisions:u,where:"inserts-updates"}:{collisions:[],where:null}}r(up,"detectBulkCollisions");function nn(e){let t=e.entries;if(!t||typeof t!="object")throw new k("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}r(nn,"schemaKeys");function qe(e,t){let n=[e.create,e.draft,e.update].filter(a=>a!==void 0);if(n.some(a=>a.type==="loose_object"))return[];let o=new Set([...n.flatMap(nn),...Te]);return Object.keys(t).filter(a=>!o.has(a))}r(qe,"unknownKeysOf");function rn(e,t){let n={};for(let o of nn(t))n[o]=null;for(let[o,a]of Object.entries(e))a!==void 0&&(n[o]=a);return n}r(rn,"wholeRecord");function Re(e,t,n,o,a){let u=M(t,n);if(!u.success)return{ok:!1,schemaKey:e,issues:[...u.issues],unknownKeys:a};let l=u.output,m={};for(let d of Object.keys(o))d!=="id"&&Object.hasOwn(l,d)&&(m[d]=l[d]);return{ok:!0,schemaKey:e,written:m,unknownKeys:a}}r(Re,"parseWritten");function on(e){return L(e)??Qe}r(on,"createStatus");function Zr(e,t){let n=on(t),o=Be({op:"create",status:n}),a={...t,status:n},u=Re(o,o==="draft"?e.draft:e.create,a,a,qe(e,t));return u.ok?{...u,written:{...u.written,status:n}}:u}r(Zr,"prepareCreate");function sn(e){return L(e)!==et}r(sn,"updateNeedsStored");function an(e,t){let n={op:"update",status:L(e),storedStatus:L(t)};return{schemaKey:Be(n)==="draft"?"draft":"update",whole:Vt(n)}}r(an,"updateCheck");function un(e,{id:t,patch:n,stored:o}){let a=L(n);if(!o&&sn(n))throw new k(`CRUD update rules: row "${t}" needs its stored row (the row's status${a===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:u,whole:l}=an(n,o),m=qe(e,n);if(o&&l)return Re(u,e.update,rn({...o,...n,id:t},e.update),n,m);let d=u==="draft"?{...n,status:L(n)??L(o),id:t}:{...n,id:t};return Re(u,u==="draft"?e.draft:e.update,d,n,m)}r(un,"prepareUpdate");function Jr(e,t){return un(e,{id:t,patch:{status:et}})}r(Jr,"prepareRemove");function Qr(e){return ye.filter(t=>!Ve(t,e))}r(Qr,"hiddenStatusesFor");function ei(e,t){return Ve(L(e),t)}r(ei,"isReadableBy");var Ed=c(i(),ne(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),ti=v(["ephemeral","session","persistent"]),ni=p({title:s(i()),pinnable:s(S()),preferredHeight:s(c(E(),R(0)))}),xd=p({id:c(i(),y(1)),kind:c(i(),y(1)),lifetime:s(ti,"ephemeral"),metadata:s(ni),payload:w()}),Sd=p({widgetId:c(i(),y(1)),action:c(i(),y(1)),payload:w()});export{oi as a,si as b,ai as c,ui as d,ci as e,fe as f,V as g,y as h,R as i,j,En as k,D as l,re as m,g as n,S as o,Sn as p,Se as q,O as r,E as s,p as t,s as u,v,b as w,i as x,kn as y,Y as z,w as A,Xe as B,c as C,M as D,Rn as E,hi as F,ht as G,Ai as H,me as I,eo as J,no as K,ro as L,lo as M,bo as N,Vn as O,Rt as P,$n as Q,Yo as R,k as S,Fs as T,Ns as U,Us as V,Ms as W,Hs as X,Fe as Y,cu as Z,ae as _,gu as $,Eu as aa,xu as ba,ir as ca,Cu as da,it as ea,_u as fa,wc as ga,L as ha,Le as ia,rp as ja,sp as ka,Yr as la,up as ma,on as na,Zr as oa,an as pa,un as qa,Jr as ra,Qr as sa,ei as ta};
|
|
22
|
+
//# sourceMappingURL=chunk-ICNQCRLV.js.map
|