@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
@@ -17,7 +17,7 @@
17
17
  * @author AMBROISE PARK Consulting
18
18
  */
19
19
 
20
- import * as v from 'valibot';
20
+ import type * as v from 'valibot';
21
21
 
22
22
  import {
23
23
  BulkCollisionError,
@@ -32,11 +32,8 @@ import type {
32
32
  } from '@donotdev/core/server';
33
33
  import { defaultFieldMapper } from '@donotdev/supabase/server';
34
34
 
35
- import {
36
- createMetadata,
37
- executeBulk,
38
- updateMetadata,
39
- } from '../../shared/index.js';
35
+ import { executeBulk } from '../../shared/crud/bulkCore.js';
36
+ import { createMetadata, updateMetadata } from '../../shared/metadata.js';
40
37
  import { createSupabaseHandler } from '../baseFunction.js';
41
38
 
42
39
  // =============================================================================
@@ -78,7 +75,6 @@ function preparePatch(
78
75
  patch: Record<string, unknown>,
79
76
  uid: string
80
77
  ): Record<string, unknown> {
81
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
82
78
  const {
83
79
  createdAt,
84
80
  updatedAt,
@@ -15,7 +15,7 @@ import { filterVisibleFields } from '@donotdev/core/server';
15
15
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
16
16
  import { defaultFieldMapper } from '@donotdev/supabase/server';
17
17
 
18
- import { createMetadata } from '../../shared/index.js';
18
+ import { createMetadata } from '../../shared/metadata.js';
19
19
  import { DoNotDevError, validateDocument } from '../../shared/utils.js';
20
20
  import { createSupabaseHandler } from '../baseFunction.js';
21
21
  import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
@@ -0,0 +1,240 @@
1
+ // packages/functions/src/supabase/crud/entityStore.ts
2
+
3
+ /**
4
+ * @fileoverview In-process, entity-aware CRUD for server code (Edge Functions, jobs).
5
+ * @description The HTTP CRUD handlers serve clients. Server code that already holds
6
+ * a Supabase client (usually the service role) reads and writes through this store
7
+ * instead of raw `.from()` queries: entity field names in and out (snake_case
8
+ * columns stay behind the field mapper), unknown fields rejected, and the
9
+ * publication filter applied by default (draft / deleted rows hidden, as the
10
+ * database policy hides them from non-admin users; the service role bypasses that
11
+ * policy, so the store re-applies it on reads).
12
+ *
13
+ * No role or visibility masking: the caller is trusted server code. Atomic
14
+ * multi-table writes stay in SQL functions (`client.rpc`).
15
+ *
16
+ * @version 0.1.0
17
+ * @since 0.5.0
18
+ * @author AMBROISE PARK Consulting
19
+ */
20
+
21
+ import type { SupabaseClient } from '@supabase/supabase-js';
22
+
23
+ import { HIDDEN_STATUSES } from '@donotdev/core/server';
24
+ import type { AnyEntity, InferEntityRow } from '@donotdev/core/server';
25
+ import { createEntityAwareMapper } from '@donotdev/supabase/server';
26
+
27
+ import { DoNotDevError } from '../../shared/utils.js';
28
+
29
+ /** Filter operators, same vocabulary as the list handler and the client CRUD. */
30
+ export type EntityStoreOperator =
31
+ | '=='
32
+ | '!='
33
+ | '>'
34
+ | '>='
35
+ | '<'
36
+ | '<='
37
+ | 'in'
38
+ | 'not-in'
39
+ | 'array-contains'
40
+ | 'array-contains-any';
41
+
42
+ /** `[field, operator, value]`; field is an entity field name. */
43
+ export type EntityStoreCondition = readonly [string, EntityStoreOperator, unknown];
44
+
45
+ /** Read options of {@link EntityStore.list} and {@link EntityStore.find}. */
46
+ export interface EntityStoreQuery {
47
+ where?: readonly EntityStoreCondition[];
48
+ /** Entity fields to read (default: every column). `id` is always read. */
49
+ select?: readonly string[];
50
+ orderBy?: readonly (readonly [string, 'asc' | 'desc'])[];
51
+ limit?: number;
52
+ /** Also return draft / deleted rows (default false). */
53
+ includeHidden?: boolean;
54
+ }
55
+
56
+ /** Values written to a row: any subset of its fields; `null` clears a nullable column. */
57
+ export type EntityStoreValues<Row> = { [K in keyof Row]?: Row[K] | null };
58
+
59
+ /** Entity-aware CRUD bound to one entity and one Supabase client. */
60
+ export interface EntityStore<Row> {
61
+ /** Rows matching the query. */
62
+ list(query?: EntityStoreQuery): Promise<Row[]>;
63
+ /** The single row matching the query, or null; more than one row is an error. */
64
+ find(query: EntityStoreQuery): Promise<Row | null>;
65
+ /** Row by id, or null (hidden rows only with `includeHidden`). */
66
+ get(id: string, options?: Pick<EntityStoreQuery, 'includeHidden' | 'select'>): Promise<Row | null>;
67
+ /** Inserts rows and returns them as stored (database defaults and triggers applied). */
68
+ insert(values: readonly EntityStoreValues<Row>[]): Promise<Row[]>;
69
+ /** Updates the rows matching `where` (hidden rows included) and returns them as stored. */
70
+ update(where: readonly EntityStoreCondition[], patch: EntityStoreValues<Row>): Promise<Row[]>;
71
+ }
72
+
73
+ const SAFE_FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
74
+
75
+ /** The PostgREST filter builder methods the store uses. */
76
+ interface Filterable {
77
+ eq(column: string, value: unknown): this;
78
+ neq(column: string, value: unknown): this;
79
+ gt(column: string, value: unknown): this;
80
+ gte(column: string, value: unknown): this;
81
+ lt(column: string, value: unknown): this;
82
+ lte(column: string, value: unknown): this;
83
+ in(column: string, values: readonly unknown[]): this;
84
+ not(column: string, operator: string, value: unknown): this;
85
+ contains(column: string, value: unknown): this;
86
+ overlaps(column: string, value: unknown): this;
87
+ }
88
+
89
+ /** Result of an awaited PostgREST query. */
90
+ interface QueryResult {
91
+ data: unknown;
92
+ error: { message: string } | null;
93
+ }
94
+
95
+ /**
96
+ * Untyped view of the PostgREST builder: the table name is only known at runtime,
97
+ * and the generic builder types instantiate too deeply for a dynamic table.
98
+ */
99
+ interface Query extends Filterable, PromiseLike<QueryResult> {
100
+ select(columns: string): Query;
101
+ order(column: string, options: { ascending: boolean }): Query;
102
+ limit(count: number): Query;
103
+ }
104
+
105
+ interface Table {
106
+ select(columns: string): Query;
107
+ insert(rows: Record<string, unknown>[]): Query;
108
+ update(values: Record<string, unknown>): Query;
109
+ }
110
+
111
+ /** PostgREST list literal for `not.in`: ("a","b"). */
112
+ function postgrestList(values: readonly unknown[]): string {
113
+ return `(${values.map((v) => JSON.stringify(String(v))).join(',')})`;
114
+ }
115
+
116
+ function applyCondition<Q extends Filterable>(query: Q, column: string, operator: EntityStoreOperator, value: unknown): Q {
117
+ const list = Array.isArray(value) ? value : [value];
118
+ switch (operator) {
119
+ case '==':
120
+ return query.eq(column, value);
121
+ case '!=':
122
+ return query.neq(column, value);
123
+ case '>':
124
+ return query.gt(column, value);
125
+ case '>=':
126
+ return query.gte(column, value);
127
+ case '<':
128
+ return query.lt(column, value);
129
+ case '<=':
130
+ return query.lte(column, value);
131
+ case 'in':
132
+ return query.in(column, list);
133
+ case 'not-in':
134
+ return query.not(column, 'in', postgrestList(list));
135
+ case 'array-contains':
136
+ return query.contains(column, [value]);
137
+ case 'array-contains-any':
138
+ // Postgres array columns only: PostgREST has no overlap operator for jsonb.
139
+ return query.overlaps(column, list);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Creates an entity-aware CRUD store for server code.
145
+ *
146
+ * @param client - Supabase client the store runs with (service role in Edge Functions)
147
+ * @param entity - Entity from `defineEntity()`; its collection is the table
148
+ * @returns Store whose rows use the entity field names
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * import { createEntityStore } from '@donotdev/functions/supabase';
153
+ * import { productEntity } from 'entities';
154
+ *
155
+ * const products = createEntityStore(supabaseAdmin, productEntity);
156
+ * // Published products only (draft / deleted hidden by default)
157
+ * const rows = await products.list({ where: [['id', 'in', ids]], select: ['name', 'sku'] });
158
+ * ```
159
+ *
160
+ * @version 0.1.0
161
+ * @since 0.5.0
162
+ */
163
+ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, entity: E): EntityStore<InferEntityRow<E>> {
164
+ type Row = InferEntityRow<E>;
165
+ const fieldNames = Object.keys(entity.fields);
166
+ const known = new Set(fieldNames);
167
+ const mapper = createEntityAwareMapper(fieldNames);
168
+ const table = entity.collection;
169
+ const hasStatus = known.has('status');
170
+ const from = (): Table => client.from(table) as unknown as Table;
171
+
172
+ const column = (field: string): string => {
173
+ if (!known.has(field) || !SAFE_FIELD_NAME.test(field)) {
174
+ throw new DoNotDevError(`${entity.name}: unknown field '${field}'`, 'invalid-argument');
175
+ }
176
+ return mapper.toBackendField(field);
177
+ };
178
+
179
+ const toColumns = (values: Record<string, unknown>): Record<string, unknown> => {
180
+ const out: Record<string, unknown> = {};
181
+ for (const [field, value] of Object.entries(values)) {
182
+ if (value === undefined) continue;
183
+ out[column(field)] = value;
184
+ }
185
+ return out;
186
+ };
187
+
188
+ const fromRows = (data: unknown): Row[] => ((data ?? []) as Record<string, unknown>[]).map((row) => mapper.fromBackendRow(row) as Row);
189
+
190
+ const fail = (operation: string, error: { message: string }): never => {
191
+ throw new DoNotDevError(`${operation} ${table}: ${error.message}`, 'internal');
192
+ };
193
+
194
+ const selectList = (select: readonly string[] | undefined): string =>
195
+ select && select.length > 0 ? [...new Set(['id', ...select])].map(column).join(', ') : '*';
196
+
197
+ const filtered = (query: Query, where: readonly EntityStoreCondition[], includeHidden: boolean | undefined): Query => {
198
+ let q = query;
199
+ for (const [field, operator, value] of where) q = applyCondition(q, column(field), operator, value);
200
+ if (hasStatus && !includeHidden) q = q.not('status', 'in', postgrestList(HIDDEN_STATUSES));
201
+ return q;
202
+ };
203
+
204
+ const list = async (query: EntityStoreQuery = {}): Promise<Row[]> => {
205
+ let q = filtered(from().select(selectList(query.select)), query.where ?? [], query.includeHidden);
206
+ for (const [field, direction] of query.orderBy ?? []) q = q.order(column(field), { ascending: direction === 'asc' });
207
+ if (query.limit !== undefined) q = q.limit(query.limit);
208
+ const { data, error } = await q;
209
+ if (error) fail('list', error);
210
+ return fromRows(data);
211
+ };
212
+
213
+ const find = async (query: EntityStoreQuery): Promise<Row | null> => {
214
+ const rows = await list({ ...query, limit: 2 });
215
+ if (rows.length > 1) throw new DoNotDevError(`${entity.name}: more than one row matches`, 'internal');
216
+ return rows[0] ?? null;
217
+ };
218
+
219
+ return {
220
+ list,
221
+ find,
222
+ get: (id, options) => find({ ...options, where: [['id', '==', id]] }),
223
+
224
+ async insert(values) {
225
+ if (values.length === 0) return [];
226
+ const { data, error } = await from()
227
+ .insert(values.map((v) => toColumns(v as Record<string, unknown>)))
228
+ .select('*');
229
+ if (error) fail('insert', error);
230
+ return fromRows(data);
231
+ },
232
+
233
+ async update(where, patch) {
234
+ if (where.length === 0) throw new DoNotDevError(`${entity.name}: update without a condition`, 'invalid-argument');
235
+ const { data, error } = await filtered(from().update(toColumns(patch as Record<string, unknown>)), where, true).select('*');
236
+ if (error) fail('update', error);
237
+ return fromRows(data);
238
+ },
239
+ };
240
+ }
@@ -16,6 +16,7 @@ export { createSupabaseDeleteEntity } from './delete.js';
16
16
  export { createSupabaseListEntities } from './list.js';
17
17
  export { createSupabaseAggregateEntities } from './aggregate.js';
18
18
  export { createSupabaseBulkEntity } from './bulk.js';
19
+ export { createEntityStore } from './entityStore.js';
19
20
 
20
21
  export type { GetEntityRequest } from './get.js';
21
22
  export type { CreateEntityRequest } from './create.js';
@@ -24,3 +25,10 @@ export type { DeleteEntityRequest, ReferenceMetadata } from './delete.js';
24
25
  export type { ListEntityRequest } from './list.js';
25
26
  export type { AggregateEntityRequest } from './aggregate.js';
26
27
  export type { BulkEntityRequest } from './bulk.js';
28
+ export type {
29
+ EntityStore,
30
+ EntityStoreCondition,
31
+ EntityStoreOperator,
32
+ EntityStoreQuery,
33
+ EntityStoreValues,
34
+ } from './entityStore.js';
@@ -14,7 +14,7 @@ import * as v from 'valibot';
14
14
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
15
15
  import { defaultFieldMapper } from '@donotdev/supabase/server';
16
16
 
17
- import { updateMetadata } from '../../shared/index.js';
17
+ import { updateMetadata } from '../../shared/metadata.js';
18
18
  import { DoNotDevError, validateDocument } from '../../shared/utils.js';
19
19
  import { createSupabaseHandler } from '../baseFunction.js';
20
20
  import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
@@ -2,7 +2,7 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview Supabase Auth Provider for shared billing logic
5
- * @description Maps Supabase Admin auth to the shared `AuthProvider` interface,
5
+ * @description Maps Supabase Admin auth to the core `BillingAuthProvider` interface,
6
6
  * bridging `app_metadata` ↔ `customClaims`.
7
7
  *
8
8
  * @version 0.1.0
@@ -10,26 +10,27 @@
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
12
 
13
- import type { AuthProvider } from '../../shared/billing/helpers/updateUserSubscription.js';
14
13
  import type { SupabaseClient } from '@supabase/supabase-js';
15
14
 
15
+ import type { BillingAuthProvider } from '@donotdev/core/server';
16
+
16
17
  // =============================================================================
17
18
  // Factory
18
19
  // =============================================================================
19
20
 
20
21
  /**
21
- * Create an AuthProvider backed by Supabase Admin.
22
+ * Create a BillingAuthProvider backed by Supabase Admin.
22
23
  * `app_metadata` is used as the equivalent of Firebase custom claims.
23
24
  *
24
25
  * @param supabaseAdmin - Supabase client created with the service role key
25
- * @returns AuthProvider compatible with shared billing helpers
26
+ * @returns BillingAuthProvider compatible with shared billing helpers
26
27
  *
27
28
  * @version 0.1.0
28
29
  * @since 0.5.0
29
30
  */
30
31
  export function createSupabaseAuthProvider(
31
32
  supabaseAdmin: SupabaseClient
32
- ): AuthProvider {
33
+ ): BillingAuthProvider {
33
34
  return {
34
35
  async getUser(userId: string) {
35
36
  const { data, error } =
@@ -31,6 +31,20 @@ export { createGetUserAuthStatus } from './auth/getUserAuthStatus.js';
31
31
 
32
32
  // Billing
33
33
  export { createCheckoutSession } from './billing/createCheckoutSession.js';
34
+ export { createStripeWebhook } from './billing/stripeWebhook.js';
35
+ export {
36
+ createSupabaseIdempotencyStore,
37
+ ReservationLostError,
38
+ WEBHOOK_EVENTS_SQL,
39
+ } from '../shared/billing/idempotency.js';
40
+ export type {
41
+ IdempotencyStore,
42
+ ReservationResult,
43
+ } from '../shared/billing/idempotency.js';
44
+ // Custom StripeOrder entry points (app request shape, own StripeSessionProvider)
45
+ export { createCheckoutAlgorithm } from '../shared/billing/createCheckout.js';
46
+ export type { StripeSessionProvider } from '../shared/billing/createCheckout.js';
47
+ export { STRIPE_API_VERSION_PIN } from '../shared/billing/apiVersion.js';
34
48
  export { createCancelSubscription } from './billing/cancelSubscription.js';
35
49
  export { createChangePlan } from './billing/changePlan.js';
36
50
  export { createCustomerPortal } from './billing/createCustomerPortal.js';
@@ -58,6 +72,12 @@ export type {
58
72
 
59
73
  // Email
60
74
  export { createEmailFunction } from './email/createEmailFunction.js';
75
+ // Server-side sending from app functions (webhooks, jobs): same templates and provider
76
+ export {
77
+ handleEmailRequest,
78
+ createResendProvider,
79
+ } from '../shared/email/index.js';
80
+ export type { EmailProviderAdapter } from '../shared/email/index.js';
61
81
 
62
82
  // CRUD
63
83
  export {
@@ -67,6 +87,7 @@ export {
67
87
  createSupabaseDeleteEntity,
68
88
  createSupabaseListEntities,
69
89
  createSupabaseAggregateEntities,
90
+ createEntityStore,
70
91
  } from './crud/index.js';
71
92
  export { createSupabaseCrudFunctions } from './registerCrudFunctions.js';
72
93
  export type {
@@ -77,6 +98,11 @@ export type {
77
98
  ListEntityRequest,
78
99
  AggregateEntityRequest,
79
100
  ReferenceMetadata,
101
+ EntityStore,
102
+ EntityStoreCondition,
103
+ EntityStoreOperator,
104
+ EntityStoreQuery,
105
+ EntityStoreValues,
80
106
  } from './crud/index.js';
81
107
 
82
108
  // Utils
@@ -23,13 +23,13 @@
23
23
  * @author AMBROISE PARK Consulting
24
24
  */
25
25
 
26
+ import type { SupabaseClient } from '@supabase/supabase-js';
27
+
26
28
  import type {
27
29
  ServerRateLimitConfig as RateLimitConfig,
28
30
  ServerRateLimitResult as RateLimitResult,
29
31
  } from '@donotdev/core';
30
32
 
31
- import type { SupabaseClient } from '@supabase/supabase-js';
32
-
33
33
  export type { RateLimitConfig, RateLimitResult };
34
34
 
35
35
  /**
@@ -38,26 +38,28 @@ vi.mock('../../shared/utils.js', () => ({
38
38
  // `executeBulk` is the real orchestrator so end-to-end behaviour (collision
39
39
  // detection, empty short-circuit, transact invocation) exercises the shared
40
40
  // core.
41
- vi.mock('../../shared/index.js', async () => {
42
- const actual = await vi.importActual<typeof import('../../shared/index.js')>(
43
- '../../shared/index.js'
44
- );
41
+ vi.mock('../../shared/firebase.js', async () => {
42
+ const actual = await vi.importActual<
43
+ typeof import('../../shared/firebase.js')
44
+ >('../../shared/firebase.js');
45
45
  return {
46
46
  ...actual,
47
47
  prepareForFirestore: (obj: Record<string, unknown>) => ({ ...obj }),
48
48
  transformFirestoreData: (obj: Record<string, unknown>) => ({ ...obj }),
49
- createMetadata: (uid: string) => ({
50
- createdAt: 'now',
51
- updatedAt: 'now',
52
- createdById: uid,
53
- updatedById: uid,
54
- }),
55
- updateMetadata: (uid: string) => ({
56
- updatedAt: 'now',
57
- updatedById: uid,
58
- }),
59
49
  };
60
50
  });
51
+ vi.mock('../../shared/metadata.js', () => ({
52
+ createMetadata: (uid: string) => ({
53
+ createdAt: 'now',
54
+ updatedAt: 'now',
55
+ createdById: uid,
56
+ updatedById: uid,
57
+ }),
58
+ updateMetadata: (uid: string) => ({
59
+ updatedAt: 'now',
60
+ updatedById: uid,
61
+ }),
62
+ }));
61
63
 
62
64
  // ---------------------------------------------------------------------------
63
65
  // Firebase Admin SDK — shared spy surface so each test can assert calls.
@@ -70,7 +72,7 @@ type TxSpy = {
70
72
  delete: ReturnType<typeof vi.fn>;
71
73
  };
72
74
 
73
- let txSpy: TxSpy;
75
+ let txSpy: TxSpy | undefined;
74
76
  let existingDocIds: Set<string>;
75
77
  let mintedIds: string[];
76
78
  let mintedIdx: number;
@@ -170,6 +172,7 @@ function makeReq(opts: {
170
172
  }
171
173
 
172
174
  beforeEach(() => {
175
+ txSpy = undefined;
173
176
  existingDocIds = new Set();
174
177
  mintedIds = [];
175
178
  mintedIdx = 0;
@@ -203,9 +206,9 @@ describe('vercel bulk handler — happy path', () => {
203
206
  deletedIds: ['d1'],
204
207
  });
205
208
  // One transaction, N writes inside it.
206
- expect(txSpy.set).toHaveBeenCalledTimes(2);
207
- expect(txSpy.update).toHaveBeenCalledTimes(1);
208
- expect(txSpy.delete).toHaveBeenCalledTimes(1);
209
+ expect(txSpy!.set).toHaveBeenCalledTimes(2);
210
+ expect(txSpy!.update).toHaveBeenCalledTimes(1);
211
+ expect(txSpy!.delete).toHaveBeenCalledTimes(1);
209
212
  });
210
213
  });
211
214
 
@@ -263,9 +266,9 @@ describe('vercel bulk handler — validation failure', () => {
263
266
 
264
267
  expect(res._status).toBe(500);
265
268
  // No writes issued — existence check runs before any tx.set/update/delete.
266
- expect(txSpy.set).not.toHaveBeenCalled();
267
- expect(txSpy.update).not.toHaveBeenCalled();
268
- expect(txSpy.delete).not.toHaveBeenCalled();
269
+ expect(txSpy!.set).not.toHaveBeenCalled();
270
+ expect(txSpy!.update).not.toHaveBeenCalled();
271
+ expect(txSpy!.delete).not.toHaveBeenCalled();
269
272
  });
270
273
 
271
274
  it('rejects structurally invalid body (ACL-equivalent schema check)', async () => {
@@ -0,0 +1,64 @@
1
+ // packages/functions/src/vercel/__tests__/firebaseOptional.test.ts
2
+
3
+ /**
4
+ * @fileoverview Regression test: the Vercel entry loads without Firebase
5
+ * @description `firebase-admin` and `firebase-functions` are optional peers. A
6
+ * Supabase-only Vercel app does not install them, so nothing reachable from
7
+ * `@donotdev/functions/vercel` may import them (or `@donotdev/firebase/server`)
8
+ * at module load. Every Firebase module is mocked to throw on load; the entry
9
+ * and the Supabase billing backend must still load and resolve.
10
+ *
11
+ * vitest isolates the module registry per test file, so the mocks below
12
+ * cannot leak into suites that load Firebase for real.
13
+ *
14
+ * @version 0.2.0
15
+ * @since 0.2.0
16
+ * @author AMBROISE PARK Consulting
17
+ */
18
+
19
+ import { describe, expect, it, vi } from 'vitest';
20
+
21
+ function blocked(name: string): never {
22
+ throw new Error(`${name} must not be loaded on the Supabase path`);
23
+ }
24
+
25
+ vi.mock('firebase-admin', () => blocked('firebase-admin'));
26
+ vi.mock('firebase-admin/app', () => blocked('firebase-admin/app'));
27
+ vi.mock('firebase-admin/auth', () => blocked('firebase-admin/auth'));
28
+ vi.mock('firebase-admin/firestore', () => blocked('firebase-admin/firestore'));
29
+ vi.mock('firebase-admin/functions', () => blocked('firebase-admin/functions'));
30
+ vi.mock('firebase-functions', () => blocked('firebase-functions'));
31
+ vi.mock('firebase-functions/v2', () => blocked('firebase-functions/v2'));
32
+ vi.mock('firebase-functions/v2/https', () => blocked('firebase-functions/v2/https'));
33
+ vi.mock('firebase-functions/params', () => blocked('firebase-functions/params'));
34
+ vi.mock('@donotdev/firebase/server', () => blocked('@donotdev/firebase/server'));
35
+
36
+ vi.mock('@supabase/supabase-js', () => ({
37
+ createClient: () => ({
38
+ auth: { admin: { getUserById: async () => ({ data: {}, error: null }) } },
39
+ from: () => ({}),
40
+ }),
41
+ }));
42
+
43
+ describe('vercel entry without firebase', () => {
44
+ it('loads the whole @donotdev/functions/vercel entry', async () => {
45
+ const entry = await import('../api/index.js');
46
+ expect(typeof entry.createStripeWebhook).toBe('function');
47
+ expect(typeof entry.createCheckoutSession).toBe('function');
48
+ expect(typeof entry.refreshSubscriptionStatus).toBe('function');
49
+ });
50
+
51
+ it('builds Supabase billing handlers and resolves the supabase backend', async () => {
52
+ process.env.SUPABASE_URL = 'https://example.supabase.co';
53
+ process.env.SUPABASE_SECRET_KEY = 'sb_secret_test';
54
+ const entry = await import('../api/index.js');
55
+ const { resolveBillingBackend } = await import('../api/billing/backend.js');
56
+
57
+ expect(typeof entry.createCheckoutSession({}, { backend: 'supabase' })).toBe(
58
+ 'function'
59
+ );
60
+ const resolved = await resolveBillingBackend('supabase');
61
+ expect(typeof resolved.authProvider.getUser).toBe('function');
62
+ expect(typeof resolved.idempotencyStore).toBe('object');
63
+ });
64
+ });
@@ -10,9 +10,10 @@
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
12
 
13
+ import * as v from 'valibot';
14
+
13
15
  import type { AIRouteConfig } from '@donotdev/core/server';
14
16
  import { AIChatRequestSchema } from '@donotdev/core/server';
15
- import * as v from 'valibot';
16
17
 
17
18
  import { handleAIRequest } from '../../../shared/ai/index.js';
18
19
  import { verifyToken } from '../../../shared/utils/internal/auth.js';
@@ -9,13 +9,11 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
12
+ import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
14
  import { handleError } from '../../../shared/errorHandling.js';
15
15
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
16
16
 
17
- import type { NextApiRequest, NextApiResponse } from 'next';
18
-
19
17
  export default async function handler(
20
18
  req: NextApiRequest,
21
19
  res: NextApiResponse
@@ -27,6 +25,7 @@ export default async function handler(
27
25
  try {
28
26
  // C1: verify JWT — previously only checked header presence.
29
27
  const uid = await verifyAuthToken(req);
28
+ const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
30
29
  const user = await getFirebaseAdminAuth().getUser(uid);
31
30
  return res.status(200).json({ customClaims: user.customClaims || {} });
32
31
  } catch (error) {
@@ -9,13 +9,11 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
12
+ import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
14
  import { handleError } from '../../../shared/errorHandling.js';
15
15
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
16
16
 
17
- import type { NextApiRequest, NextApiResponse } from 'next';
18
-
19
17
  export default async function handler(
20
18
  req: NextApiRequest,
21
19
  res: NextApiResponse
@@ -27,6 +25,7 @@ export default async function handler(
27
25
  try {
28
26
  // C1: verify JWT — previously only checked header presence.
29
27
  const uid = await verifyAuthToken(req);
28
+ const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
30
29
  const user = await getFirebaseAdminAuth().getUser(uid);
31
30
 
32
31
  return res.status(200).json({
@@ -9,13 +9,11 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
12
+ import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
14
  import { handleError } from '../../../shared/errorHandling.js';
15
15
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
16
16
 
17
- import type { NextApiRequest, NextApiResponse } from 'next';
18
-
19
17
  export default async function handler(
20
18
  req: NextApiRequest,
21
19
  res: NextApiResponse
@@ -33,6 +31,7 @@ export default async function handler(
33
31
  throw handleError(new Error('claimsToRemove must be an array'));
34
32
  }
35
33
 
34
+ const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');
36
35
  const user = await getFirebaseAdminAuth().getUser(uid);
37
36
  const currentClaims = user.customClaims || {};
38
37