@donotdev/functions 0.1.42 → 0.2.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.
Files changed (279) hide show
  1. package/README.md +25 -14
  2. package/lib/chunks/chunk-2JL3GDTO.js +151 -0
  3. package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
  4. package/lib/chunks/chunk-4TVLH2W2.js +22 -0
  5. package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
  6. package/lib/chunks/chunk-4U7QQWYG.js +22 -0
  7. package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
  8. package/lib/chunks/chunk-5DTPEM64.js +22 -0
  9. package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
  10. package/lib/chunks/chunk-6CQXHNVL.js +22 -0
  11. package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
  12. package/lib/chunks/chunk-6DSCPZC6.js +22 -0
  13. package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
  14. package/lib/chunks/chunk-7E6TGWHU.js +22 -0
  15. package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
  16. package/lib/chunks/chunk-7LT32OWE.js +22 -0
  17. package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
  18. package/lib/chunks/chunk-7VH2GJXT.js +151 -0
  19. package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
  20. package/lib/chunks/chunk-API5A4BV.js +22 -0
  21. package/lib/chunks/chunk-API5A4BV.js.map +7 -0
  22. package/lib/chunks/chunk-AYY7UXNI.js +22 -0
  23. package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
  24. package/lib/chunks/chunk-BUP7SXPV.js +23 -0
  25. package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
  26. package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
  27. package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
  28. package/lib/chunks/chunk-FSLGZD7A.js +21 -0
  29. package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
  30. package/lib/chunks/chunk-GVLSPWDD.js +151 -0
  31. package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
  32. package/lib/chunks/chunk-GXQVWEFT.js +22 -0
  33. package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
  34. package/lib/chunks/chunk-HB7EGXVI.js +22 -0
  35. package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
  36. package/lib/chunks/chunk-HLNYUAZH.js +22 -0
  37. package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
  38. package/lib/chunks/chunk-HM7XCMWW.js +22 -0
  39. package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
  40. package/lib/chunks/chunk-I7IOIL6U.js +151 -0
  41. package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
  42. package/lib/chunks/chunk-IFOYVSPU.js +22 -0
  43. package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
  44. package/lib/chunks/chunk-JTAGPPPL.js +22 -0
  45. package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
  46. package/lib/chunks/chunk-MZ232FUE.js +22 -0
  47. package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
  48. package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
  49. package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
  50. package/lib/chunks/chunk-NP2AN2TV.js +22 -0
  51. package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
  52. package/lib/chunks/chunk-QJAU2MWV.js +22 -0
  53. package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
  54. package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
  55. package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
  56. package/lib/chunks/chunk-RQZGIZHD.js +151 -0
  57. package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
  58. package/lib/chunks/chunk-TBEDQLOB.js +23 -0
  59. package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
  60. package/lib/chunks/chunk-TMHBP3HB.js +22 -0
  61. package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
  62. package/lib/chunks/chunk-UH4L3EF3.js +151 -0
  63. package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
  64. package/lib/chunks/chunk-UJBIU6TL.js +22 -0
  65. package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
  66. package/lib/chunks/chunk-VKEYW3NT.js +22 -0
  67. package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
  68. package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
  69. package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
  70. package/lib/chunks/chunk-Y44NEQQG.js +22 -0
  71. package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
  72. package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
  73. package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
  74. package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
  75. package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
  76. package/lib/chunks/monitoring-PVQMFL34.js +22 -0
  77. package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
  78. package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
  79. package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
  80. package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
  81. package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
  82. package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
  83. package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
  84. package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
  85. package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
  86. package/lib/chunks/server-32A5RH4C.js +22 -0
  87. package/lib/chunks/server-32A5RH4C.js.map +7 -0
  88. package/lib/chunks/server-7HDAP5DL.js +22 -0
  89. package/lib/chunks/server-7HDAP5DL.js.map +7 -0
  90. package/lib/chunks/server-S2IMFOY7.js +22 -0
  91. package/lib/chunks/server-S2IMFOY7.js.map +7 -0
  92. package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
  93. package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
  94. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  95. package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
  96. package/lib/firebase/baseFunction.d.ts +1 -1
  97. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
  98. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  99. package/lib/firebase/billing/index.d.ts +2 -1
  100. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
  101. package/lib/firebase/billing/webhookHandler.d.ts +17 -2
  102. package/lib/firebase/crud/aggregate.d.ts +0 -9
  103. package/lib/firebase/crud/bulk.d.ts +2 -2
  104. package/lib/firebase/crud/create.d.ts +1 -1
  105. package/lib/firebase/crud/delete.d.ts +1 -1
  106. package/lib/firebase/crud/get.d.ts +1 -1
  107. package/lib/firebase/crud/list.d.ts +1 -1
  108. package/lib/firebase/crud/update.d.ts +1 -9
  109. package/lib/firebase/index.js +1 -5
  110. package/lib/firebase/index.js.map +4 -4
  111. package/lib/firebase/oauth/githubAccess.d.ts +2 -2
  112. package/lib/firebase/registerCrudFunctions.d.ts +9 -1
  113. package/lib/shared/billing/apiVersion.d.ts +22 -0
  114. package/lib/shared/billing/checkoutPrice.d.ts +27 -0
  115. package/lib/shared/billing/checkoutValidation.d.ts +89 -0
  116. package/lib/shared/billing/createCheckout.d.ts +73 -24
  117. package/lib/shared/billing/helpers/index.d.ts +0 -1
  118. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
  119. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
  120. package/lib/shared/billing/idempotency.d.ts +32 -10
  121. package/lib/shared/billing/idempotencyContract.d.ts +121 -0
  122. package/lib/shared/billing/index.d.ts +2 -0
  123. package/lib/shared/billing/orderWebhook.d.ts +75 -0
  124. package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
  125. package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
  126. package/lib/shared/billing/webhookHandler.d.ts +28 -20
  127. package/lib/shared/index.js +1 -6
  128. package/lib/shared/index.js.map +4 -4
  129. package/lib/shared/utils/functionWrapper.d.ts +1 -1
  130. package/lib/shared/utils/internal/auth.d.ts +38 -1
  131. package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
  132. package/lib/shared/utils/schemaValidation.d.ts +1 -1
  133. package/lib/shared/utils/vercelHelpers.d.ts +8 -0
  134. package/lib/shared/utils.d.ts +4 -17
  135. package/lib/supabase/baseFunction.d.ts +1 -1
  136. package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
  137. package/lib/supabase/crud/bulk.d.ts +1 -1
  138. package/lib/supabase/crud/entityStore.d.ts +71 -0
  139. package/lib/supabase/crud/index.d.ts +2 -0
  140. package/lib/supabase/helpers/authProvider.d.ts +5 -5
  141. package/lib/supabase/index.d.ts +10 -2
  142. package/lib/supabase/index.js +1 -3
  143. package/lib/supabase/index.js.map +4 -4
  144. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  145. package/lib/vercel/api/ai/chat.d.ts +0 -9
  146. package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
  147. package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
  148. package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
  149. package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
  150. package/lib/vercel/api/billing/backend.d.ts +39 -0
  151. package/lib/vercel/api/billing/cancel.d.ts +8 -0
  152. package/lib/vercel/api/billing/change-plan.d.ts +9 -1
  153. package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
  154. package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
  155. package/lib/vercel/api/billing/index.d.ts +4 -2
  156. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
  157. package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
  158. package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
  159. package/lib/vercel/api/crud/bulk.d.ts +17 -0
  160. package/lib/vercel/api/crud/create.d.ts +8 -0
  161. package/lib/vercel/api/crud/delete.d.ts +8 -0
  162. package/lib/vercel/api/crud/get.d.ts +8 -0
  163. package/lib/vercel/api/crud/list.d.ts +8 -0
  164. package/lib/vercel/api/crud/update.d.ts +8 -0
  165. package/lib/vercel/api/index.js +1 -3
  166. package/lib/vercel/api/index.js.map +4 -4
  167. package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
  168. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  169. package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
  170. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  171. package/lib/vercel/baseFunction.d.ts +4 -1
  172. package/lib/vercel/supabaseAdmin.d.ts +22 -0
  173. package/package.json +25 -26
  174. package/src/firebase/auth/getCustomClaims.ts +4 -5
  175. package/src/firebase/auth/getUserAuthStatus.ts +4 -5
  176. package/src/firebase/auth/removeCustomClaims.ts +4 -5
  177. package/src/firebase/auth/setCustomClaims.ts +4 -5
  178. package/src/firebase/baseFunction.ts +4 -5
  179. package/src/firebase/billing/cancelSubscription.ts +1 -2
  180. package/src/firebase/billing/changePlan.ts +2 -3
  181. package/src/firebase/billing/createCheckoutSession.ts +30 -56
  182. package/src/firebase/billing/createCustomerPortal.ts +4 -5
  183. package/src/firebase/billing/healthCheck.ts +0 -0
  184. package/src/firebase/billing/index.ts +8 -1
  185. package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
  186. package/src/firebase/billing/webhookHandler.ts +20 -4
  187. package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
  188. package/src/firebase/crud/aggregate.ts +1 -2
  189. package/src/firebase/crud/bulk.ts +5 -6
  190. package/src/firebase/crud/create.ts +5 -6
  191. package/src/firebase/crud/delete.ts +4 -5
  192. package/src/firebase/crud/get.ts +4 -5
  193. package/src/firebase/crud/list.ts +4 -5
  194. package/src/firebase/crud/update.ts +5 -6
  195. package/src/firebase/oauth/githubAccess.ts +2 -3
  196. package/src/firebase/registerCrudFunctions.ts +2 -2
  197. package/src/shared/__tests__/auth.test.ts +0 -3
  198. package/src/shared/__tests__/bulkCore.test.ts +3 -2
  199. package/src/shared/__tests__/errorHandling.test.ts +2 -2
  200. package/src/shared/__tests__/idempotency.test.ts +282 -55
  201. package/src/shared/__tests__/internalValidation.test.ts +3 -3
  202. package/src/shared/__tests__/rateLimiter.test.ts +2 -8
  203. package/src/shared/__tests__/schemaValidation.test.ts +1 -1
  204. package/src/shared/__tests__/utils.test.ts +2 -1
  205. package/src/shared/__tests__/validation-env.test.ts +0 -0
  206. package/src/shared/ai/createAIRoute.ts +53 -30
  207. package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
  208. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
  209. package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
  210. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
  211. package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
  212. package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
  213. package/src/shared/billing/apiVersion.ts +25 -0
  214. package/src/shared/billing/checkoutPrice.ts +125 -0
  215. package/src/shared/billing/checkoutValidation.ts +284 -0
  216. package/src/shared/billing/createCheckout.ts +332 -196
  217. package/src/shared/billing/helpers/index.ts +0 -1
  218. package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
  219. package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
  220. package/src/shared/billing/idempotency.ts +253 -150
  221. package/src/shared/billing/idempotencyContract.ts +135 -0
  222. package/src/shared/billing/index.ts +2 -0
  223. package/src/shared/billing/orderWebhook.ts +269 -0
  224. package/src/shared/billing/supabaseIdempotency.ts +228 -0
  225. package/src/shared/billing/tierWebhookEvents.ts +432 -0
  226. package/src/shared/billing/webhookHandler.ts +188 -385
  227. package/src/shared/utils/external/subscription.ts +0 -0
  228. package/src/shared/utils/firebaseHelpers.ts +2 -3
  229. package/src/shared/utils/functionWrapper.ts +1 -2
  230. package/src/shared/utils/internal/auth.ts +55 -7
  231. package/src/shared/utils/internal/monitoring.ts +17 -9
  232. package/src/shared/utils/internal/rateLimiter.ts +14 -5
  233. package/src/shared/utils/schemaValidation.ts +1 -2
  234. package/src/shared/utils/vercelHelpers.ts +3 -3
  235. package/src/shared/utils.ts +14 -31
  236. package/src/shared/validation.ts +1 -1
  237. package/src/supabase/__tests__/bulk.test.ts +3 -1
  238. package/src/supabase/__tests__/entityStore.test.ts +90 -0
  239. package/src/supabase/baseFunction.ts +1 -2
  240. package/src/supabase/billing/createCheckoutSession.ts +10 -36
  241. package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
  242. package/src/supabase/billing/stripeWebhook.ts +79 -0
  243. package/src/supabase/crud/aggregate.ts +1 -1
  244. package/src/supabase/crud/bulk.ts +3 -7
  245. package/src/supabase/crud/create.ts +1 -1
  246. package/src/supabase/crud/entityStore.ts +240 -0
  247. package/src/supabase/crud/index.ts +8 -0
  248. package/src/supabase/crud/update.ts +1 -1
  249. package/src/supabase/helpers/authProvider.ts +6 -5
  250. package/src/supabase/index.ts +26 -0
  251. package/src/supabase/utils/rateLimiter.ts +2 -2
  252. package/src/vercel/__tests__/bulk.test.ts +24 -21
  253. package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
  254. package/src/vercel/api/ai/chat.ts +2 -1
  255. package/src/vercel/api/auth/get-custom-claims.ts +2 -3
  256. package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
  257. package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
  258. package/src/vercel/api/auth/set-custom-claims.ts +3 -3
  259. package/src/vercel/api/billing/backend.ts +72 -0
  260. package/src/vercel/api/billing/cancel.ts +2 -4
  261. package/src/vercel/api/billing/change-plan.ts +3 -4
  262. package/src/vercel/api/billing/create-checkout-session.ts +42 -68
  263. package/src/vercel/api/billing/customer-portal.ts +2 -4
  264. package/src/vercel/api/billing/index.ts +4 -2
  265. package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
  266. package/src/vercel/api/billing/webhook-handler.ts +31 -25
  267. package/src/vercel/api/config/firebase-admin.ts +2 -2
  268. package/src/vercel/api/crud/bulk.ts +6 -9
  269. package/src/vercel/api/crud/create.ts +6 -5
  270. package/src/vercel/api/crud/delete.ts +4 -3
  271. package/src/vercel/api/crud/get.ts +6 -5
  272. package/src/vercel/api/crud/list.ts +6 -5
  273. package/src/vercel/api/crud/update.ts +6 -5
  274. package/src/vercel/api/oauth/check-github-access.ts +5 -5
  275. package/src/vercel/api/oauth/exchange-token.ts +3 -3
  276. package/src/vercel/api/oauth/grant-github-access.ts +5 -5
  277. package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
  278. package/src/vercel/baseFunction.ts +23 -8
  279. package/src/vercel/supabaseAdmin.ts +45 -0
@@ -10,16 +10,64 @@
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
12
 
13
- import { hasProvider, getProvider } from '@donotdev/core/server';
14
- import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
15
-
16
13
  import type { NextApiRequest } from 'next';
14
+ import * as v from 'valibot';
15
+
16
+ import { DoNotDevError, hasProvider, getProvider } from '@donotdev/core/server';
17
+
18
+ /**
19
+ * Auth backends a server function can be explicitly configured with.
20
+ *
21
+ * @version 0.2.0
22
+ * @since 0.2.0
23
+ * @author AMBROISE PARK Consulting
24
+ */
25
+ export const AuthBackendSchema = v.picklist(['firebase', 'supabase']);
17
26
 
18
27
  /** Auth provider type for explicit configuration */
19
- export type AuthProvider = 'firebase' | 'supabase';
28
+ export type AuthProvider = v.InferOutput<typeof AuthBackendSchema>;
29
+
30
+ /**
31
+ * Validate an auth backend at runtime. Values typed as `AuthProvider` can
32
+ * still arrive as arbitrary strings from JS or env-driven config, and an
33
+ * unknown value must never silently run as Firebase.
34
+ *
35
+ * @param backend - Value to validate
36
+ * @returns The validated backend
37
+ * @throws DoNotDevError (`invalid-argument`) naming the allowed values
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const backend = parseAuthBackend(process.env.AUTH_BACKEND); // 'firebase' | 'supabase'
42
+ * ```
43
+ *
44
+ * @version 0.2.0
45
+ * @since 0.2.0
46
+ * @author AMBROISE PARK Consulting
47
+ */
48
+ export function parseAuthBackend(backend: unknown): AuthProvider {
49
+ const result = v.safeParse(AuthBackendSchema, backend);
50
+ if (!result.success) {
51
+ const allowed = AuthBackendSchema.options.map((o) => `'${o}'`).join(', ');
52
+ throw new DoNotDevError(
53
+ `Invalid backend ${JSON.stringify(backend)}: expected one of ${allowed}`,
54
+ 'invalid-argument'
55
+ );
56
+ }
57
+ return result.output;
58
+ }
20
59
 
21
60
  // IMPORTANT: Don't call getAuth() at module load - breaks Firebase deployment
22
61
 
62
+ /**
63
+ * Firebase Admin Auth, loaded on first use. `firebase-admin` is an optional
64
+ * peer: Supabase deployments never load it.
65
+ */
66
+ async function getFirebaseAuth() {
67
+ const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
68
+ return getFirebaseAdminAuth();
69
+ }
70
+
23
71
  /**
24
72
  * Validates that user is authenticated
25
73
  *
@@ -54,7 +102,7 @@ export async function assertAdmin(uid: string): Promise<string> {
54
102
  claims = (user?.customClaims as Record<string, unknown>) ?? {};
55
103
  } else {
56
104
  // Legacy Firebase path
57
- const user = await getFirebaseAdminAuth().getUser(uid);
105
+ const user = await (await getFirebaseAuth()).getUser(uid);
58
106
  claims = user.customClaims ?? {};
59
107
  }
60
108
 
@@ -134,7 +182,7 @@ export async function verifyToken(
134
182
  }
135
183
 
136
184
  if (provider === 'firebase') {
137
- const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);
185
+ const decodedToken = await (await getFirebaseAuth()).verifyIdToken(token);
138
186
  return { uid: decodedToken.uid };
139
187
  }
140
188
 
@@ -145,7 +193,7 @@ export async function verifyToken(
145
193
  }
146
194
 
147
195
  // Legacy Firebase path
148
- const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);
196
+ const decodedToken = await (await getFirebaseAuth()).verifyIdToken(token);
149
197
  return { uid: decodedToken.uid };
150
198
  } catch (error) {
151
199
  throw new Error('Invalid or expired token');
@@ -9,9 +9,17 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { logger } from 'firebase-functions/v2';
12
+ import { logger } from '../../logger.js';
13
13
 
14
- import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
14
+ /**
15
+ * Firestore, loaded on first use. `firebase-admin` is an optional peer:
16
+ * Supabase deployments never load it.
17
+ */
18
+ async function getFirestore() {
19
+ const { getFirebaseAdminFirestore } =
20
+ await import('@donotdev/firebase/server');
21
+ return getFirebaseAdminFirestore();
22
+ }
15
23
 
16
24
  /**
17
25
  * Payment metrics data structure
@@ -54,7 +62,7 @@ export async function recordPaymentMetrics(
54
62
  metrics: PaymentMetrics
55
63
  ): Promise<void> {
56
64
  try {
57
- const db = getFirebaseAdminFirestore();
65
+ const db = await getFirestore();
58
66
  const metricsRef = db.collection('payment_metrics').doc();
59
67
  await metricsRef.set({
60
68
  ...metrics,
@@ -86,7 +94,7 @@ export async function checkPaymentFailureRate(
86
94
  timeWindowHours: number = 24
87
95
  ): Promise<{ failureRate: number; shouldAlert: boolean }> {
88
96
  try {
89
- const db = getFirebaseAdminFirestore();
97
+ const db = await getFirestore();
90
98
  const cutoffTime = new Date();
91
99
  cutoffTime.setHours(cutoffTime.getHours() - timeWindowHours);
92
100
 
@@ -135,7 +143,7 @@ export async function checkPaymentVolume(
135
143
  volumeThreshold: number = 10000 // $10,000 default threshold
136
144
  ): Promise<{ totalVolume: number; shouldAlert: boolean }> {
137
145
  try {
138
- const db = getFirebaseAdminFirestore();
146
+ const db = await getFirestore();
139
147
  const today = new Date();
140
148
  today.setHours(0, 0, 0, 0);
141
149
  const tomorrow = new Date(today);
@@ -180,7 +188,7 @@ async function triggerPaymentFailureAlert(
180
188
  failedPayments: number
181
189
  ): Promise<void> {
182
190
  try {
183
- const db = getFirebaseAdminFirestore();
191
+ const db = await getFirestore();
184
192
  const alertRef = db.collection('payment_alerts').doc();
185
193
  await alertRef.set({
186
194
  type: 'payment_failure_rate',
@@ -221,7 +229,7 @@ async function triggerHighVolumeAlert(
221
229
  threshold: number
222
230
  ): Promise<void> {
223
231
  try {
224
- const db = getFirebaseAdminFirestore();
232
+ const db = await getFirestore();
225
233
  const alertRef = db.collection('payment_alerts').doc();
226
234
  await alertRef.set({
227
235
  type: 'high_payment_volume',
@@ -264,7 +272,7 @@ export async function getPaymentMetricsSummary(
264
272
  averageAmount: number;
265
273
  }> {
266
274
  try {
267
- const db = getFirebaseAdminFirestore();
275
+ const db = await getFirestore();
268
276
  const metricsRef = db.collection('payment_metrics');
269
277
  const metrics = await metricsRef
270
278
  .where('timestamp', '>=', startDate.toISOString())
@@ -326,7 +334,7 @@ export async function cleanupOldMetrics(
326
334
  alertsRetentionDays: number = 30
327
335
  ): Promise<void> {
328
336
  try {
329
- const db = getFirebaseAdminFirestore();
337
+ const db = await getFirestore();
330
338
  const now = new Date();
331
339
 
332
340
  // Clean up old metrics
@@ -9,13 +9,12 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { logger } from 'firebase-functions/v2';
13
-
14
12
  import type {
15
13
  ServerRateLimitConfig as RateLimitConfig,
16
14
  ServerRateLimitResult as RateLimitResult,
17
15
  } from '@donotdev/core';
18
- import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
16
+
17
+ import { logger } from '../../logger.js';
19
18
 
20
19
  export type { RateLimitConfig, RateLimitResult };
21
20
 
@@ -25,6 +24,16 @@ interface RateLimitEntry {
25
24
  blockUntil: number | null;
26
25
  }
27
26
 
27
+ /**
28
+ * Firestore, loaded on first use. `firebase-admin` is an optional peer:
29
+ * Supabase deployments never load it.
30
+ */
31
+ async function getFirestore() {
32
+ const { getFirebaseAdminFirestore } =
33
+ await import('@donotdev/firebase/server');
34
+ return getFirebaseAdminFirestore();
35
+ }
36
+
28
37
  // In-memory storage for rate limiting (in production, use Redis or Firestore)
29
38
  const rateLimitStore = new Map<string, RateLimitEntry>();
30
39
 
@@ -121,7 +130,7 @@ export async function checkRateLimitWithFirestore(
121
130
  key: string,
122
131
  config: RateLimitConfig
123
132
  ): Promise<RateLimitResult> {
124
- const db = getFirebaseAdminFirestore();
133
+ const db = await getFirestore();
125
134
  const rateLimitRef = db.collection('rateLimits').doc(key);
126
135
 
127
136
  try {
@@ -258,7 +267,7 @@ export function resetRateLimit(key: string): void {
258
267
  * @author AMBROISE PARK Consulting
259
268
  */
260
269
  export async function resetRateLimitInFirestore(key: string): Promise<void> {
261
- const db = getFirebaseAdminFirestore();
270
+ const db = await getFirestore();
262
271
  const rateLimitRef = db.collection('rateLimits').doc(key);
263
272
 
264
273
  try {
@@ -9,10 +9,9 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import * as v from 'valibot';
13
-
14
12
  import type { CallableRequest } from 'firebase-functions/v2/https';
15
13
  import type { NextApiRequest, NextApiResponse } from 'next';
14
+ import * as v from 'valibot';
16
15
 
17
16
  /**
18
17
  * Validates request data using a schema with custom override support
@@ -9,14 +9,14 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type { NextApiRequest, NextApiResponse } from 'next';
13
+ import type * as v from 'valibot';
14
+
12
15
  import {
13
16
  withVercelSchemaValidation,
14
17
  validateRequestData,
15
18
  } from './schemaValidation.js';
16
19
 
17
- import type { NextApiRequest, NextApiResponse } from 'next';
18
- import type * as v from 'valibot';
19
-
20
20
  /**
21
21
  * Creates a Vercel API handler with schema validation
22
22
  *
@@ -14,12 +14,8 @@ import * as v from 'valibot';
14
14
 
15
15
  import { DoNotDevError } from '@donotdev/core/server';
16
16
  import type { OAuthPartnerId, UserRole } from '@donotdev/core/server';
17
- import {
18
- getFirebaseAdminAuth,
19
- getFirebaseAdminFirestore,
20
- initFirebaseAdmin,
21
- } from '@donotdev/firebase/server';
22
17
 
18
+ import { STRIPE_API_VERSION_PIN } from './billing/apiVersion.js';
23
19
  import {
24
20
  assertAuthenticated as internalAssertAuthenticated,
25
21
  assertAdmin as internalAssertAdmin,
@@ -28,41 +24,23 @@ import {
28
24
  // Re-export DoNotDevError for external use
29
25
  export { DoNotDevError };
30
26
 
31
- /**
32
- * Get Firestore instance using @donotdev/firebase/server
33
- * Provider handles initialization and caching
34
- *
35
- * @version 0.1.0
36
- * @since 0.0.1
37
- * @author AMBROISE PARK Consulting
38
- */
39
- export function getFirestore() {
40
- return getFirebaseAdminFirestore();
41
- }
42
-
43
- /**
44
- * Get Auth instance using @donotdev/firebase/server
45
- * Provider handles initialization and caching
46
- *
47
- * @version 0.1.0
48
- * @since 0.0.1
49
- * @author AMBROISE PARK Consulting
50
- */
51
- export function getAuth() {
52
- return getFirebaseAdminAuth();
53
- }
54
-
55
27
  // Lazy initialization of Stripe
56
28
  let _stripe: Stripe | null = null;
57
29
 
58
30
  /**
59
- * Initialize Stripe explicitly (e.g. with a secret from defineSecret)
31
+ * Initialize Stripe explicitly (e.g. with a secret from defineSecret).
32
+ * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.
60
33
  * @param apiKey - Stripe secret key
34
+ *
35
+ * @version 0.2.0
36
+ * @since 0.0.1
37
+ * @author AMBROISE PARK Consulting
61
38
  */
62
39
  export function initStripe(apiKey: string) {
63
40
  if (!apiKey) throw new Error('Stripe API key is required');
64
41
 
65
- const apiVersion = process.env.STRIPE_API_VERSION || '2024-12-18.acacia'; // Fallback or strict latest
42
+ // Unset: the framework pin (pre-basil fields are still read by subscription handlers)
43
+ const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
66
44
 
67
45
  _stripe = new Stripe(apiKey, {
68
46
  apiVersion: apiVersion as any,
@@ -414,6 +392,8 @@ export async function verifyFirebaseAuthToken(token: string): Promise<string> {
414
392
  throw new DoNotDevError('Missing authentication token', 'unauthenticated');
415
393
  }
416
394
 
395
+ // Lazy: the Vercel/Supabase entries must load without firebase-admin
396
+ const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
417
397
  try {
418
398
  const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);
419
399
  return decodedToken.uid;
@@ -449,6 +429,9 @@ export async function findReferences(
449
429
  return references;
450
430
  }
451
431
 
432
+ // Lazy: the Vercel/Supabase entries must load without firebase-admin
433
+ const { getFirebaseAdminFirestore } =
434
+ await import('@donotdev/firebase/server');
452
435
  const db = getFirebaseAdminFirestore();
453
436
 
454
437
  for (const ref of referenceMetadata.incoming) {
@@ -43,7 +43,7 @@ export function validateEnvironment(): void {
43
43
  if (!apiVersion.match(/^\d{4}-\d{2}-\d{2}\./)) {
44
44
  throw new Error(
45
45
  `❌ Invalid STRIPE_API_VERSION format: "${apiVersion}"\n` +
46
- `Expected format: YYYY-MM-DD.name (e.g., "2025-09-30.clover")`
46
+ `Expected format: YYYY-MM-DD.name (e.g., "2025-02-24.acacia")`
47
47
  );
48
48
  }
49
49
 
@@ -6,8 +6,8 @@
6
6
  * inner business logic directly without needing a mock Deno `Request`.
7
7
  */
8
8
 
9
- import { describe, it, expect, vi, beforeEach } from 'vitest';
10
9
  import * as v from 'valibot';
10
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
11
11
 
12
12
  // ---------------------------------------------------------------------------
13
13
  // Mocks
@@ -79,6 +79,7 @@ function setup(opts?: {
79
79
  const inner = createSupabaseBulkEntity(
80
80
  'events',
81
81
  CreateSchema,
82
+ CreateSchema,
82
83
  UpdateSchema,
83
84
  access
84
85
  ) as unknown as (data: any, ctx: any) => Promise<any>;
@@ -227,6 +228,7 @@ describe('createSupabaseBulkEntity', () => {
227
228
  const inner = createSupabaseBulkEntity(
228
229
  'events',
229
230
  CreateSchema,
231
+ CreateSchema,
230
232
  UpdateSchema,
231
233
  { ...access, delete: 'admin' }
232
234
  ) as unknown as (data: any, ctx: any) => Promise<any>;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @fileoverview Unit tests for `createEntityStore`: field mapping both ways,
3
+ * publication filter, unknown-field rejection, single-row `find`, writes.
4
+ */
5
+
6
+ import { describe, it, expect } from 'vitest';
7
+
8
+ import { createEntityStore } from '../crud/entityStore.js';
9
+
10
+ type Call = [string, ...unknown[]];
11
+
12
+ /** Records every builder call; awaiting the query resolves to `result`. */
13
+ function fakeClient(result: { data: unknown; error: { message: string } | null }) {
14
+ const calls: Call[] = [];
15
+ const query: Record<string, unknown> = {};
16
+ for (const m of ['select', 'insert', 'update', 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'not', 'contains', 'overlaps', 'order', 'limit']) {
17
+ query[m] = (...args: unknown[]) => {
18
+ calls.push([m, ...args]);
19
+ return query;
20
+ };
21
+ }
22
+ query.then = (resolve: (r: unknown) => unknown) => Promise.resolve(result).then(resolve);
23
+ const client = {
24
+ from: (table: string) => {
25
+ calls.push(['from', table]);
26
+ return query;
27
+ },
28
+ };
29
+ return { client: client as never, calls };
30
+ }
31
+
32
+ const entity = {
33
+ name: 'Product',
34
+ collection: 'products',
35
+ fields: { id: {}, status: {}, name: {}, weightGrams: {}, brandId: {} },
36
+ } as never;
37
+
38
+ describe('createEntityStore', () => {
39
+ it('lists with entity names in, snake_case columns out, hidden statuses excluded', async () => {
40
+ const { client, calls } = fakeClient({ data: [{ id: 'p1', name: 'A', weight_grams: 50 }], error: null });
41
+ const rows = await createEntityStore(client, entity).list({
42
+ where: [['brandId', 'in', ['b1']]],
43
+ select: ['name', 'weightGrams'],
44
+ orderBy: [['name', 'asc']],
45
+ });
46
+ expect(rows).toEqual([{ id: 'p1', name: 'A', weightGrams: 50 }]);
47
+ expect(calls).toEqual([
48
+ ['from', 'products'],
49
+ ['select', 'id, name, weight_grams'],
50
+ ['in', 'brand_id', ['b1']],
51
+ ['not', 'status', 'in', '("draft","deleted")'],
52
+ ['order', 'name', { ascending: true }],
53
+ ]);
54
+ });
55
+
56
+ it('includeHidden drops the publication filter', async () => {
57
+ const { client, calls } = fakeClient({ data: [], error: null });
58
+ await createEntityStore(client, entity).list({ includeHidden: true });
59
+ expect(calls.some(([m]) => m === 'not')).toBe(false);
60
+ });
61
+
62
+ it('rejects fields the entity does not define', async () => {
63
+ const { client } = fakeClient({ data: [], error: null });
64
+ await expect(createEntityStore(client, entity).list({ where: [['price', '==', 1]] })).rejects.toThrow("unknown field 'price'");
65
+ await expect(createEntityStore(client, entity).insert([{ price: 1 } as never])).rejects.toThrow("unknown field 'price'");
66
+ });
67
+
68
+ it('find returns null, one row, or fails on several', async () => {
69
+ const none = fakeClient({ data: [], error: null });
70
+ expect(await createEntityStore(none.client, entity).get('p1')).toBeNull();
71
+ const two = fakeClient({ data: [{ id: 'a' }, { id: 'b' }], error: null });
72
+ await expect(createEntityStore(two.client, entity).find({ where: [['name', '==', 'A']] })).rejects.toThrow('more than one row');
73
+ });
74
+
75
+ it('insert and update map keys, skip undefined, return stored rows', async () => {
76
+ const { client, calls } = fakeClient({ data: [{ id: 'p1', weight_grams: 10 }], error: null });
77
+ const store = createEntityStore(client, entity);
78
+ expect(await store.insert([{ weightGrams: 10, name: undefined }])).toEqual([{ id: 'p1', weightGrams: 10 }]);
79
+ await store.update([['id', '==', 'p1']], { weightGrams: 10 });
80
+ expect(calls).toContainEqual(['insert', [{ weight_grams: 10 }]]);
81
+ expect(calls).toContainEqual(['update', { weight_grams: 10 }]);
82
+ expect(calls).toContainEqual(['eq', 'id', 'p1']);
83
+ await expect(store.update([], { weightGrams: 1 })).rejects.toThrow('update without a condition');
84
+ });
85
+
86
+ it('surfaces database errors', async () => {
87
+ const { client } = fakeClient({ data: null, error: { message: 'boom' } });
88
+ await expect(createEntityStore(client, entity).list()).rejects.toThrow('list products: boom');
89
+ });
90
+ });
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { createClient } from '@supabase/supabase-js';
14
+ import type { SupabaseClient } from '@supabase/supabase-js';
14
15
  import * as v from 'valibot';
15
16
 
16
17
  import { hasRoleAccess } from '@donotdev/core/server';
@@ -21,9 +22,7 @@ import {
21
22
  checkRateLimitWithPostgres,
22
23
  DEFAULT_RATE_LIMITS,
23
24
  } from './utils/rateLimiter.js';
24
-
25
25
  import type { RateLimitConfig } from './utils/rateLimiter.js';
26
- import type { SupabaseClient } from '@supabase/supabase-js';
27
26
 
28
27
  // =============================================================================
29
28
  // Types
@@ -14,6 +14,7 @@ import type { StripeBackConfig } from '@donotdev/core/server';
14
14
  import type { CreateCheckoutSessionRequest } from '@donotdev/core/server';
15
15
 
16
16
  import { createCheckoutAlgorithm } from '../../shared/billing/createCheckout.js';
17
+ import type { StripeSessionProvider } from '../../shared/billing/createCheckout.js';
17
18
  import {
18
19
  initStripe,
19
20
  stripe,
@@ -45,48 +46,21 @@ export function createCheckoutSession(billingConfig: StripeBackConfig) {
45
46
 
46
47
  const authProvider = createSupabaseAuthProvider(ctx.supabaseAdmin);
47
48
 
48
- const stripeProvider = {
49
- async createCheckoutSession(params: {
50
- priceId?: string;
51
- unitAmount?: number;
52
- productName?: string;
53
- currency?: string;
54
- customerEmail?: string;
55
- metadata: Record<string, string>;
56
- allowPromotionCodes: boolean;
57
- successUrl: string;
58
- cancelUrl: string;
59
- mode?: 'payment' | 'subscription';
60
- }) {
61
- const session = await stripe.checkout.sessions.create({
62
- mode: params.mode || 'payment',
63
- line_items: [
64
- params.priceId
65
- ? { price: params.priceId, quantity: 1 }
66
- : {
67
- price_data: {
68
- currency: params.currency || 'eur',
69
- unit_amount: params.unitAmount!,
70
- product_data: { name: params.productName! },
71
- },
72
- quantity: 1,
73
- },
74
- ],
75
- customer_email: params.customerEmail || undefined,
76
- success_url: params.successUrl,
77
- cancel_url: params.cancelUrl,
78
- allow_promotion_codes: params.allowPromotionCodes,
79
- metadata: params.metadata,
80
- ...(params.mode === 'subscription' && {
81
- subscription_data: { metadata: params.metadata },
82
- }),
83
- });
49
+ const stripeProvider: StripeSessionProvider = {
50
+ async createStripeSession(params) {
51
+ const session = await stripe.checkout.sessions.create(params);
84
52
  return { id: session.id, url: session.url };
85
53
  },
54
+ async retrieveTaxRate(id) {
55
+ const rate = await stripe.taxRates.retrieve(id);
56
+ return { id: rate.id, inclusive: rate.inclusive };
57
+ },
86
58
  };
87
59
 
60
+ // userId comes from the verified JWT, never from the client
88
61
  return createCheckoutAlgorithm(
89
62
  data,
63
+ ctx.uid,
90
64
  stripeProvider,
91
65
  authProvider,
92
66
  billingConfig
@@ -9,6 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type Stripe from 'stripe';
12
13
  import * as v from 'valibot';
13
14
 
14
15
  import {
@@ -19,8 +20,6 @@ import {
19
20
  import { createSupabaseHandler } from '../baseFunction.js';
20
21
  import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
21
22
 
22
- import type Stripe from 'stripe';
23
-
24
23
  // =============================================================================
25
24
  // Schema
26
25
  // =============================================================================
@@ -0,0 +1,79 @@
1
+ // packages/functions/src/supabase/billing/stripeWebhook.ts
2
+
3
+ /**
4
+ * @fileoverview Stripe webhook Supabase Edge Function
5
+ * @description Verifies and routes Stripe webhook events through the shared
6
+ * processWebhook (SSOT). Idempotency is stored in Postgres (`webhook_events`).
7
+ *
8
+ * @version 0.2.0
9
+ * @since 0.2.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type { StripeBackConfig } from '@donotdev/core/server';
14
+
15
+ import { updateUserSubscription } from '../../shared/billing/helpers/updateUserSubscription.js';
16
+ import { createSupabaseIdempotencyStore } from '../../shared/billing/idempotency.js';
17
+ import { processWebhook } from '../../shared/billing/webhookHandler.js';
18
+ import { initStripe, stripe } from '../../shared/utils.js';
19
+ import { createEdgeFunction } from '../edgeFunction.js';
20
+ import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
21
+
22
+ declare const Deno:
23
+ | { env: { get(key: string): string | undefined } }
24
+ | undefined;
25
+
26
+ function getEnvOrThrow(key: string): string {
27
+ const value =
28
+ typeof Deno !== 'undefined' ? Deno.env.get(key) : process.env[key];
29
+ if (!value) throw new Error(`Missing ${key} environment variable`);
30
+ return value;
31
+ }
32
+
33
+ /**
34
+ * Create a Supabase Edge Function handler for Stripe webhooks.
35
+ * Requires the `webhook_events` migration (see `WEBHOOK_EVENTS_SQL`).
36
+ * Deploy with JWT verification disabled for this function: Stripe authenticates
37
+ * with its signature, not a Supabase JWT.
38
+ * Any failure answers non-2xx so Stripe retries the event.
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // supabase/functions/stripe-webhook/index.ts
43
+ * import { createStripeWebhook } from '@donotdev/functions/supabase';
44
+ * import { billingConfig } from '../_shared/billingConfig.ts';
45
+ *
46
+ * Deno.serve(createStripeWebhook(billingConfig));
47
+ * ```
48
+ *
49
+ * @param billingConfig - App back config
50
+ * @returns `(req: Request) => Promise<Response>` handler
51
+ *
52
+ * @version 0.2.0
53
+ * @since 0.2.0
54
+ * @author AMBROISE PARK Consulting
55
+ */
56
+ export function createStripeWebhook(billingConfig: StripeBackConfig) {
57
+ return createEdgeFunction(
58
+ async (req, ctx) => {
59
+ const signature = req.headers.get('stripe-signature');
60
+ if (!signature) return ctx.error('Missing Stripe signature', 400);
61
+
62
+ initStripe(getEnvOrThrow('STRIPE_SECRET_KEY'));
63
+
64
+ const result = await processWebhook(
65
+ await req.text(),
66
+ signature,
67
+ getEnvOrThrow('STRIPE_WEBHOOK_SECRET'),
68
+ stripe,
69
+ billingConfig,
70
+ updateUserSubscription,
71
+ createSupabaseAuthProvider(ctx.supabaseAdmin),
72
+ createSupabaseIdempotencyStore(ctx.supabaseAdmin)
73
+ );
74
+
75
+ return ctx.json({ received: true, message: result.message });
76
+ },
77
+ { requireAuth: false, extraHeaders: ['stripe-signature'] }
78
+ );
79
+ }
@@ -89,7 +89,7 @@ export function createSupabaseAggregateEntities(
89
89
  const { supabaseAdmin } = ctx;
90
90
 
91
91
  const aggregateColumn = mapper.toBackendField(aggregate.field);
92
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic aggregate builder; Supabase types change across chained calls
92
+
93
93
  let query: any = supabaseAdmin.from(collection);
94
94
 
95
95
  for (const [field, operator, value] of where) {