@donotdev/functions 0.2.2 → 0.2.3

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.
Files changed (161) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/chunk-6NXIK35R.js +23 -0
  3. package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
  4. package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
  5. package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-EZKRLLSQ.js.map} +1 -1
  6. package/lib/chunks/chunk-F3PHE627.js +22 -0
  7. package/lib/chunks/chunk-F3PHE627.js.map +7 -0
  8. package/lib/chunks/chunk-F3WBFWPO.js +151 -0
  9. package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
  10. package/lib/chunks/chunk-G5DRV3DH.js +22 -0
  11. package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
  12. package/lib/chunks/{chunk-2A4FPYNB.js → chunk-GDIUOJMD.js} +2 -2
  13. package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
  14. package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
  15. package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
  16. package/lib/chunks/chunk-QXIOO2RL.js +22 -0
  17. package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
  18. package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-UH445BGK.js} +2 -2
  19. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  20. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  21. package/lib/chunks/chunk-W74UL7AY.js +22 -0
  22. package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
  23. package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-NODQAE3F.js} +2 -2
  26. package/lib/firebase/crud/aggregate.d.ts +1 -1
  27. package/lib/firebase/index.js +1 -1
  28. package/lib/firebase/index.js.map +3 -3
  29. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  30. package/lib/shared/billing/createCheckout.d.ts +1 -1
  31. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  32. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  33. package/lib/shared/billing/stripePinned.d.ts +43 -0
  34. package/lib/shared/denoEnv.d.ts +25 -0
  35. package/lib/shared/github.d.ts +0 -8
  36. package/lib/shared/index.js +1 -1
  37. package/lib/shared/logger.d.ts +14 -14
  38. package/lib/shared/utils/external/subscription.d.ts +0 -8
  39. package/lib/shared/utils.d.ts +15 -3
  40. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  41. package/lib/supabase/crud/create.d.ts +0 -8
  42. package/lib/supabase/crud/entityStore.d.ts +13 -0
  43. package/lib/supabase/crud/update.d.ts +0 -8
  44. package/lib/supabase/index.d.ts +1 -0
  45. package/lib/supabase/index.js +1 -1
  46. package/lib/supabase/index.js.map +4 -4
  47. package/lib/vercel/api/index.js +1 -1
  48. package/lib/vercel/api/index.js.map +3 -3
  49. package/package.json +9 -9
  50. package/src/firebase/auth/getCustomClaims.ts +2 -0
  51. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  52. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  53. package/src/firebase/auth/setCustomClaims.ts +3 -0
  54. package/src/firebase/baseFunction.ts +5 -2
  55. package/src/firebase/billing/changePlan.ts +6 -5
  56. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  57. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  58. package/src/firebase/billing/webhookHandler.ts +4 -4
  59. package/src/firebase/crud/aggregate.ts +41 -12
  60. package/src/firebase/crud/bulk.ts +7 -0
  61. package/src/firebase/crud/create.ts +21 -8
  62. package/src/firebase/crud/delete.ts +6 -1
  63. package/src/firebase/crud/get.ts +9 -2
  64. package/src/firebase/crud/list.ts +18 -8
  65. package/src/firebase/crud/update.ts +15 -7
  66. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  67. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  68. package/src/firebase/oauth/exchangeToken.ts +4 -0
  69. package/src/firebase/oauth/getConnections.ts +1 -1
  70. package/src/firebase/oauth/githubAccess.ts +3 -0
  71. package/src/firebase/oauth/refreshToken.ts +1 -0
  72. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  73. package/src/shared/ai/classifyAIError.ts +18 -10
  74. package/src/shared/ai/createAIRoute.ts +2 -1
  75. package/src/shared/ai/resolveModelTier.ts +2 -1
  76. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  77. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  78. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  79. package/src/shared/billing/checkoutValidation.ts +19 -2
  80. package/src/shared/billing/createCheckout.ts +56 -11
  81. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  82. package/src/shared/billing/orderWebhook.ts +69 -1
  83. package/src/shared/billing/stripeClient.ts +2 -1
  84. package/src/shared/billing/stripePinned.ts +71 -0
  85. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  86. package/src/shared/billing/webhookHandler.ts +5 -1
  87. package/src/shared/crud/bulkCore.ts +3 -2
  88. package/src/shared/denoEnv.ts +29 -0
  89. package/src/shared/email/createEmailRoute.ts +2 -2
  90. package/src/shared/errorHandling.ts +8 -8
  91. package/src/shared/firebase.ts +26 -9
  92. package/src/shared/github.ts +15 -5
  93. package/src/shared/logger.ts +37 -38
  94. package/src/shared/schema.ts +6 -10
  95. package/src/shared/utils/external/date.ts +4 -4
  96. package/src/shared/utils/external/subscription.ts +2 -89
  97. package/src/shared/utils/firebaseHelpers.ts +2 -0
  98. package/src/shared/utils/internal/idempotency.ts +3 -0
  99. package/src/shared/utils/internal/monitoring.ts +6 -5
  100. package/src/shared/utils/internal/validation.ts +2 -0
  101. package/src/shared/utils/schemaValidation.ts +1 -0
  102. package/src/shared/utils/validation.ts +10 -20
  103. package/src/shared/utils.ts +12 -7
  104. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  105. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  106. package/src/supabase/auth/deleteAccount.ts +72 -5
  107. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  108. package/src/supabase/crud/aggregate.ts +85 -72
  109. package/src/supabase/crud/bulk.ts +3 -0
  110. package/src/supabase/crud/create.ts +13 -9
  111. package/src/supabase/crud/delete.ts +2 -1
  112. package/src/supabase/crud/entityStore.ts +1 -1
  113. package/src/supabase/crud/get.ts +2 -1
  114. package/src/supabase/crud/list.ts +23 -17
  115. package/src/supabase/crud/update.ts +9 -6
  116. package/src/supabase/edgeFunction.ts +2 -1
  117. package/src/supabase/email/createEmailFunction.ts +2 -1
  118. package/src/supabase/index.ts +1 -0
  119. package/src/supabase/oauth/exchangeToken.ts +1 -0
  120. package/src/supabase/oauth/getConnections.ts +1 -1
  121. package/src/supabase/oauth/refreshToken.ts +1 -0
  122. package/src/supabase/utils/idempotency.ts +1 -1
  123. package/src/supabase/utils/monitoring.ts +1 -0
  124. package/src/vercel/api/billing/change-plan.ts +6 -5
  125. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  126. package/src/vercel/api/crud/bulk.ts +7 -2
  127. package/src/vercel/api/crud/create.ts +6 -3
  128. package/src/vercel/api/crud/delete.ts +5 -2
  129. package/src/vercel/api/crud/get.ts +5 -2
  130. package/src/vercel/api/crud/list.ts +6 -3
  131. package/src/vercel/api/crud/update.ts +6 -3
  132. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  133. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  134. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  135. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  136. package/src/vercel/baseFunction.ts +5 -1
  137. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  138. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  139. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  140. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  141. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  142. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  143. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  144. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  145. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  146. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  147. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  148. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  149. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  150. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  151. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  152. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  153. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  154. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  155. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  156. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  157. package/src/shared/utils/functionWrapper.ts +0 -73
  158. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-UH445BGK.js.map} +0 -0
  159. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  160. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  161. /package/lib/chunks/{server-RYGEBS2B.js.map → server-NODQAE3F.js.map} +0 -0
@@ -9,6 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type { SupabaseClient } from '@supabase/supabase-js';
12
13
  import * as v from 'valibot';
13
14
 
14
15
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
@@ -24,6 +25,7 @@ const mapper = defaultFieldMapper;
24
25
  /** Request payload for updating an entity by ID with optional idempotency. */
25
26
  export type UpdateEntityRequest = {
26
27
  id: string;
28
+ // 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)
27
29
  payload: Record<string, any>;
28
30
  idempotencyKey?: string;
29
31
  };
@@ -44,10 +46,10 @@ function normalizeValue(value: unknown): unknown {
44
46
  async function checkUniqueKeys(
45
47
  collection: string,
46
48
  id: string,
47
- payload: Record<string, any>,
49
+ payload: Record<string, unknown>,
48
50
  uniqueKeys: UniqueKeyDefinition[],
49
51
  isDraft: boolean,
50
- supabaseAdmin: any
52
+ supabaseAdmin: SupabaseClient
51
53
  ): Promise<void> {
52
54
  for (const uniqueKey of uniqueKeys) {
53
55
  if (isDraft && uniqueKey.skipForDrafts === true) continue;
@@ -100,12 +102,13 @@ async function checkUniqueKeys(
100
102
  */
101
103
  export function createSupabaseUpdateEntity(
102
104
  collection: string,
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
103
106
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
104
107
  requiredRole: UserRole
105
108
  ) {
106
109
  const requestSchema = v.object({
107
110
  id: v.pipe(v.string(), v.minLength(1)),
108
- payload: v.record(v.string(), v.any()),
111
+ payload: v.record(v.string(), v.unknown()),
109
112
  idempotencyKey: v.optional(v.string()),
110
113
  });
111
114
 
@@ -118,7 +121,7 @@ export function createSupabaseUpdateEntity(
118
121
 
119
122
  // Idempotency check if key provided
120
123
  if (idempotencyKey) {
121
- const cachedResult = await checkIdempotency<any>(
124
+ const cachedResult = await checkIdempotency<unknown>(
122
125
  supabaseAdmin,
123
126
  idempotencyKey,
124
127
  'update'
@@ -143,7 +146,7 @@ export function createSupabaseUpdateEntity(
143
146
  // `payload` arrives from the client in camelCase. The merge produces a camelCase object
144
147
  // which is later converted back to snake_case via toBackendKeys before the UPDATE query.
145
148
  const merged = {
146
- ...(mapper.fromBackendRow(existing) as Record<string, any>),
149
+ ...(mapper.fromBackendRow(existing) as Record<string, unknown>),
147
150
  ...payload,
148
151
  };
149
152
  const status = merged.status ?? existing.status;
@@ -204,7 +207,7 @@ export function createSupabaseUpdateEntity(
204
207
  );
205
208
  }
206
209
 
207
- const result = mapper.fromBackendRow(updated) as Record<string, any>;
210
+ const result = mapper.fromBackendRow(updated) as Record<string, unknown>;
208
211
 
209
212
  // Store result for idempotency if key provided
210
213
  if (idempotencyKey) {
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { createClient } from '@supabase/supabase-js';
17
17
  import type { SupabaseClient } from '@supabase/supabase-js';
18
+ import { getDenoEnv } from '../shared/denoEnv.js';
18
19
 
19
20
  // =============================================================================
20
21
  // Types
@@ -190,7 +191,7 @@ function jsonResponse(
190
191
 
191
192
  function getEnv(key: string): string {
192
193
  if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
193
- return (globalThis as any).Deno?.env?.get(key) ?? '';
194
+ return getDenoEnv()?.get(key) ?? '';
194
195
  }
195
196
  return typeof process !== 'undefined' ? (process.env[key] ?? '') : '';
196
197
  }
@@ -16,6 +16,7 @@ import { SendEmailRequestSchema } from '@donotdev/core/server';
16
16
  import { handleEmailRequest } from '../../shared/email/index.js';
17
17
  import { createResendProvider } from '../../shared/email/resendProvider.js';
18
18
  import { createSupabaseHandler } from '../baseFunction.js';
19
+ import { getDenoEnv } from '../../shared/denoEnv.js';
19
20
 
20
21
  /**
21
22
  * Create a Supabase Edge Function handler for sending emails.
@@ -66,7 +67,7 @@ export function createEmailFunction(config: EmailRouteConfig) {
66
67
 
67
68
  function getEnv(name: string): string | undefined {
68
69
  if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
69
- return (globalThis as any).Deno?.env?.get(name);
70
+ return getDenoEnv()?.get(name);
70
71
  }
71
72
  return typeof process !== 'undefined' ? process.env[name] : undefined;
72
73
  }
@@ -23,6 +23,7 @@ export { createSupabaseAuthProvider } from './helpers/authProvider.js';
23
23
 
24
24
  // Auth
25
25
  export { createDeleteAccount } from './auth/deleteAccount.js';
26
+ export type { DeleteAccountOptions } from './auth/deleteAccount.js';
26
27
  export { createSetCustomClaims } from './auth/setCustomClaims.js';
27
28
  export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
28
29
  export { createGetCustomClaims } from './auth/getCustomClaims.js';
@@ -122,6 +122,7 @@ export function createExchangeToken() {
122
122
  );
123
123
  }
124
124
 
125
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: untrusted OAuth token response; needs a valibot schema (strict vs loose expires_in is an open owner decision)
125
126
  const tokenData = (await tokenResponse.json()) as any;
126
127
 
127
128
  // Format credentials
@@ -58,7 +58,7 @@ export function createGetConnections() {
58
58
  throw new Error(`Failed to get connections: ${error.message}`);
59
59
  }
60
60
 
61
- const connections = (rows || []).map((row: any) => {
61
+ const connections = (rows || []).map((row) => {
62
62
  const isExpired = row.credentials?.expiresAt
63
63
  ? row.credentials.expiresAt < Math.floor(Date.now() / 1000)
64
64
  : false;
@@ -94,6 +94,7 @@ export function createRefreshToken() {
94
94
  throw new Error(`Failed to refresh token: ${response.status}`);
95
95
  }
96
96
 
97
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: untrusted OAuth token response; needs a valibot schema (strict vs loose expires_in is an open owner decision)
97
98
  const tokenData = (await response.json()) as any;
98
99
 
99
100
  const credentials = {
@@ -95,7 +95,7 @@ export async function storeIdempotency<T>(
95
95
  id,
96
96
  operation,
97
97
  idempotency_key: idempotencyKey,
98
- result: result as any,
98
+ result,
99
99
  processed_by: uid,
100
100
  expires_at: expiresAt.toISOString(),
101
101
  },
@@ -19,6 +19,7 @@ export interface OperationMetrics {
19
19
  userId?: string;
20
20
  status: 'success' | 'failed' | 'pending';
21
21
  durationMs?: number;
22
+ // 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)
22
23
  metadata?: Record<string, any>;
23
24
  errorCode?: string;
24
25
  errorMessage?: string;
@@ -19,6 +19,7 @@ import { updateUserSubscription } from '../../../shared/billing/helpers/updateUs
19
19
  import { handleError } from '../../../shared/errorHandling.js';
20
20
  import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
21
21
  import { createVercelBaseFunction } from '../../baseFunction.js';
22
+ import { isOneOf, pinnedSubscriptionPeriod } from '../../../shared/billing/stripePinned.js';
22
23
 
23
24
  const changePlanSchema = v.object({
24
25
  userId: v.string(),
@@ -86,8 +87,8 @@ async function changePlanLogic(
86
87
  'trialing',
87
88
  'incomplete',
88
89
  ] as const;
89
- const status = validStatuses.includes(updatedSubscription.status as any)
90
- ? (updatedSubscription.status as (typeof validStatuses)[number])
90
+ const status = isOneOf(validStatuses, updatedSubscription.status)
91
+ ? updatedSubscription.status
91
92
  : 'incomplete';
92
93
 
93
94
  // Update Firebase Auth
@@ -97,9 +98,9 @@ async function changePlanLogic(
97
98
  tier: billingItem.tier,
98
99
  status,
99
100
  subscriptionEnd: new Date(
100
- (updatedSubscription as any).current_period_end * 1000
101
+ pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
101
102
  ).toISOString(),
102
- cancelAtPeriodEnd: (updatedSubscription as any).cancel_at_period_end,
103
+ cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,
103
104
  subscriptionId: updatedSubscription.id,
104
105
  customerId: updatedSubscription.customer as string,
105
106
  },
@@ -107,7 +108,7 @@ async function changePlanLogic(
107
108
  async getUser(uid: string) {
108
109
  return getFirebaseAdminAuth().getUser(uid);
109
110
  },
110
- async setCustomUserClaims(uid: string, claims: Record<string, any>) {
111
+ async setCustomUserClaims(uid: string, claims: Record<string, unknown>) {
111
112
  await getFirebaseAdminAuth().setCustomUserClaims(uid, claims);
112
113
  },
113
114
  }
@@ -17,6 +17,7 @@ import type { RefreshSubscriptionRequest } from '@donotdev/core/server';
17
17
 
18
18
  import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
19
19
  import { createVercelBaseFunction } from '../../baseFunction.js';
20
+ import { pinnedSubscriptionPeriod } from '../../../shared/billing/stripePinned.js';
20
21
 
21
22
  const refreshSubscriptionStatusSchema = v.object({
22
23
  userId: v.pipe(v.string(), v.minLength(1, 'User ID is required')),
@@ -76,7 +77,7 @@ async function refreshSubscriptionStatusLogic(
76
77
  customerId: subscription.customer,
77
78
  status: subscription.status,
78
79
  currentPeriodEnd: new Date(
79
- (subscription as any).current_period_end * 1000
80
+ pinnedSubscriptionPeriod(subscription).current_period_end * 1000
80
81
  ).toISOString(),
81
82
  };
82
83
 
@@ -113,6 +114,7 @@ async function refreshSubscriptionStatusLogic(
113
114
  * @author AMBROISE PARK Consulting
114
115
  */
115
116
  const refreshSubscriptionStatus = (
117
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
116
118
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
117
119
  ) => {
118
120
  const schema = customSchema || refreshSubscriptionStatusSchema;
@@ -29,7 +29,10 @@ import {
29
29
  import type { BulkRequest, BulkResponse } from '@donotdev/core/server';
30
30
 
31
31
  import { executeBulk } from '../../../shared/crud/bulkCore.js';
32
- import { handleError } from '../../../shared/errorHandling.js';
32
+ import {
33
+ DoNotDevError,
34
+ handleError,
35
+ } from '../../../shared/errorHandling.js';
33
36
  import { prepareForFirestore } from '../../../shared/firebase.js';
34
37
  import { createMetadata, updateMetadata } from '../../../shared/metadata.js';
35
38
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
@@ -199,7 +202,9 @@ export default async function handler(
199
202
  } catch (error) {
200
203
  try {
201
204
  handleError(error);
202
- } catch (handledError: any) {
205
+ } catch (handledError) {
206
+ // handleError always throws DoNotDevError; narrow for typed access
207
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
203
208
  // BulkCollisionError surfaces as 400 (invalid-argument) because the
204
209
  // caller sent an incoherent payload — same class as schema failure.
205
210
  const isCollision = error instanceof BulkCollisionError;
@@ -13,7 +13,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
14
  import type { CreateEntityData } from '@donotdev/core/server';
15
15
 
16
- import { handleError } from '../../../shared/errorHandling.js';
16
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
17
17
  import {
18
18
  prepareForFirestore,
19
19
  transformFirestoreData,
@@ -37,6 +37,7 @@ export default async function handler(
37
37
  // C1: verify JWT — previously only checked header presence.
38
38
  const uid = await verifyAuthToken(req);
39
39
 
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
40
41
  const { schema, payload } = req.body as CreateEntityData<any>;
41
42
 
42
43
  if (!schema || !payload) {
@@ -53,7 +54,7 @@ export default async function handler(
53
54
  // Draft handling is schema-driven: `schemas.draft` must convert required
54
55
  // fields into nullish/optional, so we still validate drafts.
55
56
  const payloadForValidation = {
56
- ...(payload as Record<string, any>),
57
+ ...payload,
57
58
  status,
58
59
  };
59
60
  validateDocument(payloadForValidation, schema);
@@ -87,7 +88,9 @@ export default async function handler(
87
88
  } catch (error) {
88
89
  try {
89
90
  handleError(error);
90
- } catch (handledError: any) {
91
+ } catch (handledError) {
92
+ // handleError always throws DoNotDevError; narrow for typed access
93
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
91
94
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
92
95
  return res
93
96
  .status(status)
@@ -13,7 +13,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
14
  import type { GetEntityData } from '@donotdev/core/server';
15
15
 
16
- import { handleError } from '../../../shared/errorHandling.js';
16
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
17
17
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
18
18
  import { validateCollectionName } from '../../../shared/utils.js';
19
19
 
@@ -29,6 +29,7 @@ export default async function handler(
29
29
  // C1: verify JWT — previously only checked header presence.
30
30
  const uid = await verifyAuthToken(req);
31
31
 
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
32
33
  const { schema, id } = req.body as { schema: any; id: string };
33
34
 
34
35
  if (!schema || !id) {
@@ -59,7 +60,9 @@ export default async function handler(
59
60
  } catch (error) {
60
61
  try {
61
62
  handleError(error);
62
- } catch (handledError: any) {
63
+ } catch (handledError) {
64
+ // handleError always throws DoNotDevError; narrow for typed access
65
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
63
66
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
64
67
  return res
65
68
  .status(status)
@@ -14,7 +14,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
14
14
  import { HIDDEN_STATUSES } from '@donotdev/core/server';
15
15
  import type { GetEntityData } from '@donotdev/core/server';
16
16
 
17
- import { handleError } from '../../../shared/errorHandling.js';
17
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
18
18
  import { transformFirestoreData } from '../../../shared/firebase.js';
19
19
  import { filterVisibleFields } from '../../../shared/schema.js';
20
20
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
@@ -32,6 +32,7 @@ export default async function handler(
32
32
  // C1: verify JWT — previously only checked header presence.
33
33
  const uid = await verifyAuthToken(req);
34
34
 
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
35
36
  const { schema, id } = req.query as unknown as GetEntityData<any>;
36
37
 
37
38
  // G71: Validate query params are strings (Next.js can pass string[] for repeated params)
@@ -78,7 +79,9 @@ export default async function handler(
78
79
  } catch (error) {
79
80
  try {
80
81
  handleError(error);
81
- } catch (handledError: any) {
82
+ } catch (handledError) {
83
+ // handleError always throws DoNotDevError; narrow for typed access
84
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
82
85
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
83
86
  return res
84
87
  .status(status)
@@ -14,7 +14,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
14
14
  import { HIDDEN_STATUSES } from '@donotdev/core/server';
15
15
  import type { ListEntityData } from '@donotdev/core/server';
16
16
 
17
- import { handleError } from '../../../shared/errorHandling.js';
17
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
18
18
  import { transformFirestoreData } from '../../../shared/firebase.js';
19
19
  import { filterVisibleFields } from '../../../shared/schema.js';
20
20
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
@@ -36,6 +36,7 @@ export default async function handler(
36
36
  schema,
37
37
  limit = 10,
38
38
  offset = 0,
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
39
40
  } = req.query as unknown as ListEntityData<any> & {
40
41
  limit?: string;
41
42
  offset?: string;
@@ -69,7 +70,7 @@ export default async function handler(
69
70
  const snapshot = await query.get();
70
71
 
71
72
  // Transform the documents
72
- const documents = snapshot.docs.map((doc: any) => {
73
+ const documents = snapshot.docs.map((doc) => {
73
74
  const documentData = transformFirestoreData({
74
75
  id: doc.id,
75
76
  ...doc.data(),
@@ -86,7 +87,9 @@ export default async function handler(
86
87
  } catch (error) {
87
88
  try {
88
89
  handleError(error);
89
- } catch (handledError: any) {
90
+ } catch (handledError) {
91
+ // handleError always throws DoNotDevError; narrow for typed access
92
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
90
93
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
91
94
  return res
92
95
  .status(status)
@@ -14,7 +14,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
14
14
  import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
15
15
  import type { UpdateEntityData } from '@donotdev/core/server';
16
16
 
17
- import { handleError } from '../../../shared/errorHandling.js';
17
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
18
18
  import {
19
19
  prepareForFirestore,
20
20
  transformFirestoreData,
@@ -38,6 +38,7 @@ export default async function handler(
38
38
  // C1: verify JWT — previously only checked header presence.
39
39
  const uid = await verifyAuthToken(req);
40
40
 
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
41
42
  const { schema, id, payload } = req.body as UpdateEntityData<any>;
42
43
 
43
44
  if (!schema || !id || !payload) {
@@ -70,7 +71,7 @@ export default async function handler(
70
71
  // Validate the document against the schema
71
72
  // Skip validation for drafts - required fields can be incomplete
72
73
  if (!isDraft) {
73
- validateDocument(mergedData as Record<string, any>, schema);
74
+ validateDocument(mergedData, schema);
74
75
  }
75
76
 
76
77
  // Prepare the document for Firestore and add metadata
@@ -102,7 +103,9 @@ export default async function handler(
102
103
  } catch (error) {
103
104
  try {
104
105
  handleError(error);
105
- } catch (handledError: any) {
106
+ } catch (handledError) {
107
+ // handleError always throws DoNotDevError; narrow for typed access
108
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
106
109
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
107
110
  return res
108
111
  .status(status)
@@ -93,6 +93,7 @@ async function checkGitHubAccessLogic(
93
93
  * @author AMBROISE PARK Consulting
94
94
  */
95
95
  const checkGitHubAccess = (
96
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
96
97
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
97
98
  ) => {
98
99
  const schema = customSchema || checkGitHubAccessSchema;
@@ -60,12 +60,13 @@ async function exchangeTokenLogic(
60
60
  const { provider, purpose, code, redirectUri, codeVerifier, instance } = data;
61
61
 
62
62
  // Get provider endpoints
63
- let tokenUrl = OAUTH_PARTNERS[provider]?.endpoints?.tokenUrl;
63
+ let tokenUrl: string | undefined =
64
+ OAUTH_PARTNERS[provider]?.endpoints?.tokenUrl;
64
65
 
65
66
  // Special handling for Mastodon instances
66
67
  if (provider === 'mastodon' && instance) {
67
68
  validateInstanceUrl(instance);
68
- tokenUrl = `${instance.replace(/\/$/, '')}/oauth/token` as any;
69
+ tokenUrl = `${instance.replace(/\/$/, '')}/oauth/token`;
69
70
  }
70
71
 
71
72
  if (!tokenUrl) {
@@ -150,6 +151,7 @@ async function exchangeTokenLogic(
150
151
  }
151
152
 
152
153
  // Parse response
154
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: untrusted OAuth token response; needs a valibot schema (strict vs loose expires_in is an open owner decision)
153
155
  const tokenData = (await response.json()) as any;
154
156
 
155
157
  // Validate required fields
@@ -180,6 +182,7 @@ async function exchangeTokenLogic(
180
182
  * Base function handles all common concerns automatically
181
183
  */
182
184
  const exchangeToken = (
185
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
183
186
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
184
187
  ) => {
185
188
  const schema = customSchema || exchangeTokenSchema;
@@ -111,6 +111,7 @@ async function grantGitHubAccessLogic(
111
111
  * @author AMBROISE PARK Consulting
112
112
  */
113
113
  const grantGitHubAccess = (
114
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
114
115
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
115
116
  ) => {
116
117
  const schema = customSchema || grantGitHubAccessSchema;
@@ -24,6 +24,7 @@ import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
24
24
  export default async function handler(
25
25
  req: NextApiRequest,
26
26
  res: NextApiResponse,
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
27
28
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
28
29
  ) {
29
30
  if (req.method !== 'POST') {
@@ -26,6 +26,7 @@ import {
26
26
  checkRateLimitWithFirestore,
27
27
  DEFAULT_RATE_LIMITS,
28
28
  } from '../shared/utils/internal/rateLimiter.js';
29
+ import type { RateLimitConfig } from '../shared/utils/internal/rateLimiter.js';
29
30
  import { checkRateLimitWithPostgres } from '../supabase/utils/rateLimiter.js';
30
31
 
31
32
  /**
@@ -85,8 +86,11 @@ export function createVercelBaseFunction<TRequest, TResponse>(
85
86
 
86
87
  // Rate limiting
87
88
  const rateLimitKey = `${operation}_${uid}`;
89
+ const rateLimitsByOperation: Partial<
90
+ Record<string, RateLimitConfig>
91
+ > = DEFAULT_RATE_LIMITS;
88
92
  const rateLimitConfig =
89
- (DEFAULT_RATE_LIMITS as any)[operation] || DEFAULT_RATE_LIMITS.api;
93
+ rateLimitsByOperation[operation] || DEFAULT_RATE_LIMITS.api;
90
94
  // Rate-limit storage follows the auth backend (Postgres for Supabase)
91
95
  const rateLimitResult =
92
96
  provider === 'supabase'
@@ -1,7 +0,0 @@
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 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: any) => 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: any) => {\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: any) => {\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: any) => 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: any) => 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,gBA2Cf,eAAsBG,EACpBC,EACe,CACf,GAAI,CAGF,MAFW,MAAMJ,EAAa,GACR,WAAW,iBAAiB,EAAE,IAAI,EACvC,IAAI,CACnB,GAAGI,EACH,WAAY,IAAI,KAAK,EAAE,YAAY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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
- }
@@ -1,23 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{R as s,S as C,U as j,e as B,z as P}from"./chunk-G4FO76EA.js";import{a as o}from"./chunk-AYY7UXNI.js";import{initializeApp as N,getApps as Y,cert as Q}from"firebase-admin/app";import{getAuth as Z}from"firebase-admin/auth";import{getFirestore as X}from"firebase-admin/firestore";import{getFunctions as ee}from"firebase-admin/functions";function te(){let e=Y(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=N({credential:Q({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
22
- `)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=N():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:Z(t),firestore:X(t),functions:ee(t)}}o(te,"initializeFirebaseAdminServices");var D=j(te);async function be(){try{return D()}catch(e){throw s(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}o(be,"initFirebaseAdmin");async function $(){let e=D();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}o($,"getFirebaseAdminApp");function I(){let e=D();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}o(I,"getFirebaseAdminAuth");function z(){let e=D();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}o(z,"getFirebaseAdminFirestore");function we(){let e=D();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}o(we,"getFirebaseAdminFunctions");var W=class{static{o(this,"FirebaseServerAuthAdapter")}async verifyToken(t){try{let r=await I().verifyIdToken(t);return{uid:r.uid,email:r.email,claims:r}}catch(r){throw C(r,"FirebaseServerAuthAdapter","verifyToken")}}async getUser(t){try{let r=await I().getUser(t);return{uid:r.uid,email:r.email,displayName:r.displayName,customClaims:r.customClaims??{}}}catch(r){if(r.code==="auth/user-not-found")return null;throw C(r,"FirebaseServerAuthAdapter","getUser",{uid:t})}}async setCustomClaims(t,r){try{let i=(await I().getUser(t)).customClaims??{};await I().setCustomUserClaims(t,{...i,...r})}catch(n){throw C(n,"FirebaseServerAuthAdapter","setCustomClaims",{uid:t})}}};var O={async getServerAdmin(){try{return $()}catch(e){throw s(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return z()}catch(e){throw s(e,"Error getting Admin Firestore")}},async generateServerId(){return(await O.getServerFirestore()).collection("_").doc().id}},Ie=O.getServerAdmin,g=O.getServerFirestore,Re=O.generateServerId;function L(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:o(()=>new Date(e),"toDate"),toMillis:o(()=>e.getTime(),"toMillis"),isEqual:o(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:o(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}o(L,"createTimestamp");function Ce(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return L(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return L(e)}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to Timestamp")}}o(Ce,"toTimestamp");function re(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to ISO string")}}o(re,"firestoreToISOString");function ne(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}o(ne,"isTimestamp");function ie(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}o(ie,"isISODateString");function J(e){if(!e)return e;if(Array.isArray(e))return e.map(t=>J(t));if(typeof e=="string"&&ie(e))return new Date(e);if(typeof e=="object"&&e!==null){let t={};for(let[r,n]of Object.entries(e))t[r]=J(n);return t}return e}o(J,"convertISOStringsToDates");function v(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,n=r.data();return{id:r.id,...v(n)}}if(Array.isArray(e))return e.map(r=>v(r));if(ne(e))return re(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,i]of Object.entries(e))r[n]=v(i);return r}return e}o(v,"transformFirestoreData");function F(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>F(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[n,i]of Object.entries(e))t.includes(n)||i!==void 0&&(r[n]=F(i,t));return r}return e}o(F,"prepareForFirestore");function Oe(e,t){let r={};for(let[n,i]of Object.entries(t)){if(!(n in e)){r[n]=i;continue}JSON.stringify(e[n])!==JSON.stringify(i)&&(r[n]=i)}return{...r,updatedAt:new Date().toISOString()}}o(Oe,"createFirestorePartialUpdate");var x=typeof window<"u",y={async batchWrite(e,t,r,n,i={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:a="id",generateIds:d=!0,maxBatchSize:u=450,removeFields:c=[],validate:S=!!n}=i,l={successes:0,failures:0,failedItems:[]};try{let b=[],w=await g(),p=w.batch(),h=0;for(let T=0;T<t.length;T++){let m=t[T];if(!m){l.failures++,l.failedItems?.push({index:T,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!m[a])throw s(new Error(`Missing ID for delete operation (${a})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:a,operation:r}});let f=w.collection(e).doc(m[a]);p.delete(f)}else{if(S&&n)try{P(n,m)}catch(K){throw s(K,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:a,itemId:m[a]}})}let f=m[a];if(!f&&r==="create"&&d)f=w.collection(e).doc().id,m={...m,[a]:f};else if(!f)throw s(new Error(`Missing ID for ${r} operation (${a})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:a,operation:r}});let q=[a,...c],A=F(m,q),U=w.collection(e).doc(f);r==="create"?p.create(U,A):r==="update"&&p.update(U,A)}h++,h>=u&&(b.push({batch:p,size:h}),p=w.batch(),h=0)}catch(f){l.failures++,l.failedItems?.push({index:T,error:f instanceof Error?f:new Error(String(f))})}}h>0&&b.push({batch:p,size:h});let k=0;for(let{batch:T,size:m}of b){try{await T.commit(),l.successes+=m}catch(f){let q=f instanceof Error?f:new Error(String(f));for(let A=k;A<k+m;A++)l.failures++,l.failedItems?.push({index:A,error:q})}k+=m}return l}catch(b){throw s(b,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:l.successes+l.failures,successCount:l.successes,failureCount:l.failures}})}},async batchCreate(e,t,r,n={}){return y.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return y.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let n=r.idField||"id",i=t.map(a=>({[n]:a}));return y.batchWrite(e,i,"delete",void 0,r)}return y.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await g()).runTransaction(e)}catch(t){throw s(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:i=!0}=r;try{let a=[];for(let c=0;c<t.length;c+=n)a.push(t.slice(c,c+n));let d=a.map(async c=>{let b=await(await g()).collection(e).where("__name__","in",c).get(),w=new Map;return b.forEach(p=>{w.set(p.id,p.data())}),c.map(p=>{let h=w.get(p);return h?i?v({id:p,...h}):{id:p,...h}:null})});return(await Promise.all(d)).flat()}catch(a){throw s(a,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},E=o(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),Be=x?E("batchWrite"):y.batchWrite,je=x?E("batchCreate"):y.batchCreate,Ne=x?E("batchUpdate"):y.batchUpdate,$e=x?E("batchDelete"):y.batchDelete,ze=x?E("runTransaction"):y.runTransaction,We=x?E("bulkGet"):y.bulkGet;function R(e,t){return s(e,{userMessage:t?`Error during ${t}`:void 0,context:{operation:t}})}o(R,"handleFirebaseError");async function se(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{let d=await(await g()).collection(r).where(n,"==",e).where("status","==","active").limit(1).get();if(d.empty)return null;let u=d.docs[0];if(!u)return null;let c=u.data();return v({id:u.id,...c})}catch(i){throw R(i,"getActiveSubscription")}}o(se,"getActiveSubscription");async function et(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{return(await(await g()).collection(r).where(n,"==",e).orderBy("createdAt","desc").get()).docs.map(u=>v({id:u.id,...u.data()}))}catch(i){throw R(i,"getUserSubscriptions")}}o(et,"getUserSubscriptions");async function ae(e,t={}){let{collection:r="subscriptions"}=t;try{let n=await g(),i=new Date().toISOString(),a={...e,createdAt:e.createdAt||i,updatedAt:i},d=F(a),{id:u,...c}=d,S=u?n.collection(r).doc(u):n.collection(r).doc();return await S.set(c,{merge:!0}),{...a,id:S.id}}catch(n){throw R(n,"saveSubscription")}}o(ae,"saveSubscription");async function ce(e,t,r={}){let{collection:n="subscriptions"}=r;try{await(await g()).collection(n).doc(e).update({status:t,updatedAt:new Date().toISOString()})}catch(i){throw R(i,"updateSubscriptionStatus")}}o(ce,"updateSubscriptionStatus");async function tt(e,t,r={}){try{let n=await se(e,r);return n?n.features&&Array.isArray(n.features)?n.features.includes(t):n.metadata&&n.metadata[t]?n.metadata[t]==="true":!1:!1}catch(n){throw s(n,{userMessage:"Failed to check feature access",severity:"error",context:{function:"hasFeatureAccess",userId:e,featureKey:t}})}}o(tt,"hasFeatureAccess");async function rt(e){let{rawBody:t,signature:r,webhookSecret:n,...i}=e,a;try{let u=await import("stripe"),c=u.default??u;a=new c("placeholder",{apiVersion:"2023-10-16"})}catch{throw s(new Error("stripe package is not installed"),{userMessage:"Stripe package missing \u2014 cannot verify webhook signature",severity:"error"})}let d;try{d=a.webhooks.constructEvent(t,r,n)}catch(u){throw s(u,{userMessage:"Stripe webhook signature verification failed",severity:"error",context:{function:"verifyAndHandleStripeWebhook"}})}await ue(d,i)}o(rt,"verifyAndHandleStripeWebhook");async function ue(e,t={}){let r=e.type,n=e.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await de(n,t);break;case"customer.subscription.deleted":await ce(n.id,"canceled",t);break;default:}}catch(i){throw s(i,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:e.id}})}}o(ue,"handleStripeWebhookEvent");async function de(e,t={}){if(!e.items.data.length)throw s(new Error("[subscription] Stripe subscription has no items"),{userMessage:"Stripe subscription has no items \u2014 cannot determine plan",severity:"error",context:{subscriptionId:e.id}});let r={id:e.id,customerId:e.customer,status:e.status,planId:e.items.data[0]?.plan.id||"",currentPeriodStart:new Date(e.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(e.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:e.cancel_at_period_end,metadata:e.metadata||{},createdAt:new Date(e.created*1e3).toISOString(),updatedAt:new Date().toISOString()};e.canceled_at&&(r.canceledAt=new Date(e.canceled_at*1e3).toISOString()),await ae(r,t)}o(de,"saveSubscriptionFromStripeEvent");var V={};function _(e){V.uniqueConstraintValidator=e}o(_,"registerUniqueConstraintValidator");function G(){return V.uniqueConstraintValidator}o(G,"getUniqueConstraintValidator");function le(){return!!V.uniqueConstraintValidator}o(le,"hasUniqueConstraintValidator");async function H(){let e=await g(),t={checkDuplicate:o(async(r,n,i,a)=>{if(i==null)return!1;try{return(await e.collection(r).where(n,"==",i).get()).docs.some(c=>c.id!==a&&c.data()[n]===i)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:i}})}},"checkDuplicate")};return _(t),t}o(H,"createFirestoreValidator");async function fe(){let e=await g(),t={checkDuplicate:o(async(r,n,i,a)=>{if(i==null)return!1;try{return(await e.collection(r).where(n,"==",i).get()).docs.some(c=>c.id!==a&&c.data()[n]===i)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:i}})}},"checkDuplicate")};return _(t),t}o(fe,"createAdminFirestoreValidator");async function M(e,t,r,n){if(!t.length)return;let i=G();i||(i=await H());let a=[],u=(await Promise.allSettled(t.map(async({field:c,errorMessage:S})=>{let l=r[c];if(l==null)return;await i.checkDuplicate(e,c,l,n)&&a.push({field:c,message:S||`The ${c} must be unique`})}))).find(c=>c.status==="rejected");if(u&&u.status==="rejected")throw u.reason;if(a.length>0)throw s(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:a,collection:e}})}o(M,"validateUniqueness");async function lt(e,t,r,n){try{P(e,t),e.metadata?.uniqueFields?.length&&await M(e.metadata.collection,e.metadata.uniqueFields,t,n),e.metadata?.customValidate&&await e.metadata.customValidate(t,r)}catch(i){throw B(i)?s(i,{userMessage:"Document validation failed",context:{validationErrors:i.issues,data:t},severity:"warning"}):s(i,{userMessage:"Document validation failed",context:{collection:e.metadata?.collection||"unknown"},severity:"error"})}}o(lt,"validateFirestoreDocument");function ft(e,t){let r=e;return r.metadata=t,r}o(ft,"enhanceSchema");import{FieldValue as Et,Query as Dt,Timestamp as It}from"firebase-admin/firestore";export{be as a,$ as b,I as c,z as d,we as e,W as f,Ie as g,g as h,Re as i,L as j,Ce as k,re as l,ne as m,J as n,v as o,F as p,Oe as q,Be as r,je as s,Ne as t,$e as u,ze as v,We as w,se as x,et as y,ae as z,ce as A,tt as B,rt as C,_ as D,G as E,le as F,H as G,fe as H,M as I,lt as J,ft as K,Et as L,Dt as M,It as N};
23
- //# sourceMappingURL=chunk-2IFFIUFV.js.map