@donotdev/functions 0.1.44 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/README.md +25 -14
  2. package/lib/chunks/chunk-3F4BWKQD.js +22 -0
  3. package/lib/chunks/chunk-3F4BWKQD.js.map +7 -0
  4. package/lib/chunks/chunk-5IPULSUX.js +22 -0
  5. package/lib/chunks/chunk-5IPULSUX.js.map +7 -0
  6. package/lib/chunks/chunk-6USHTJED.js +22 -0
  7. package/lib/chunks/chunk-6USHTJED.js.map +7 -0
  8. package/lib/chunks/chunk-AYY7UXNI.js +22 -0
  9. package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
  10. package/lib/chunks/chunk-CXBSROEW.js +23 -0
  11. package/lib/chunks/chunk-CXBSROEW.js.map +7 -0
  12. package/lib/chunks/chunk-GYTCWMXV.js +22 -0
  13. package/lib/chunks/chunk-GYTCWMXV.js.map +7 -0
  14. package/lib/chunks/chunk-HLNYUAZH.js +22 -0
  15. package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
  16. package/lib/chunks/chunk-LCDLG4VG.js +151 -0
  17. package/lib/chunks/chunk-LCDLG4VG.js.map +7 -0
  18. package/lib/chunks/chunk-MQANUSY3.js +22 -0
  19. package/lib/chunks/chunk-MQANUSY3.js.map +7 -0
  20. package/lib/chunks/chunk-OFQVO3FD.js +22 -0
  21. package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
  22. package/lib/chunks/chunk-PWAGW4R6.js +22 -0
  23. package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
  24. package/lib/chunks/chunk-US2VOP4S.js +22 -0
  25. package/lib/chunks/chunk-US2VOP4S.js.map +7 -0
  26. package/lib/chunks/chunk-YTKDNZNW.js +22 -0
  27. package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
  28. package/lib/chunks/monitoring-E7JBYBHQ.js +22 -0
  29. package/lib/chunks/monitoring-E7JBYBHQ.js.map +7 -0
  30. package/lib/chunks/rateLimiter-SQISLOP5.js +22 -0
  31. package/lib/chunks/rateLimiter-SQISLOP5.js.map +7 -0
  32. package/lib/chunks/server-IQ5JNJOM.js +22 -0
  33. package/lib/chunks/server-IQ5JNJOM.js.map +7 -0
  34. package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
  35. package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
  36. package/lib/firebase/auth/index.d.ts +0 -0
  37. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  38. package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
  39. package/lib/firebase/baseFunction.d.ts +1 -1
  40. package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
  41. package/lib/firebase/billing/changePlan.d.ts +0 -0
  42. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
  43. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  44. package/lib/firebase/billing/healthCheck.d.ts +0 -0
  45. package/lib/firebase/billing/index.d.ts +2 -1
  46. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
  47. package/lib/firebase/billing/webhookHandler.d.ts +17 -2
  48. package/lib/firebase/config/constants.d.ts +0 -0
  49. package/lib/firebase/config/index.d.ts +0 -0
  50. package/lib/firebase/config/secrets.d.ts +0 -0
  51. package/lib/firebase/crud/aggregate.d.ts +0 -9
  52. package/lib/firebase/crud/bulk.d.ts +2 -2
  53. package/lib/firebase/crud/create.d.ts +1 -1
  54. package/lib/firebase/crud/delete.d.ts +1 -1
  55. package/lib/firebase/crud/get.d.ts +1 -1
  56. package/lib/firebase/crud/index.d.ts +0 -0
  57. package/lib/firebase/crud/list.d.ts +1 -1
  58. package/lib/firebase/crud/update.d.ts +1 -9
  59. package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
  60. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
  61. package/lib/firebase/helpers/index.d.ts +0 -0
  62. package/lib/firebase/index.d.ts +0 -0
  63. package/lib/firebase/index.js +1 -5
  64. package/lib/firebase/index.js.map +4 -4
  65. package/lib/firebase/oauth/disconnect.d.ts +0 -0
  66. package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
  67. package/lib/firebase/oauth/getConnections.d.ts +0 -0
  68. package/lib/firebase/oauth/githubAccess.d.ts +2 -2
  69. package/lib/firebase/oauth/index.d.ts +0 -0
  70. package/lib/firebase/oauth/refreshToken.d.ts +0 -0
  71. package/lib/firebase/registerCrudFunctions.d.ts +9 -1
  72. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
  73. package/lib/firebase/scheduled/index.d.ts +0 -0
  74. package/lib/shared/ai/classifyAIError.d.ts +0 -0
  75. package/lib/shared/ai/costTracker.d.ts +0 -0
  76. package/lib/shared/ai/createAIRoute.d.ts +0 -0
  77. package/lib/shared/ai/index.d.ts +0 -0
  78. package/lib/shared/ai/resolveModelTier.d.ts +0 -0
  79. package/lib/shared/billing/apiVersion.d.ts +22 -0
  80. package/lib/shared/billing/checkoutPrice.d.ts +27 -0
  81. package/lib/shared/billing/checkoutValidation.d.ts +89 -0
  82. package/lib/shared/billing/createCheckout.d.ts +73 -24
  83. package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
  84. package/lib/shared/billing/helpers/index.d.ts +0 -1
  85. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
  86. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
  87. package/lib/shared/billing/idempotency.d.ts +21 -10
  88. package/lib/shared/billing/idempotencyContract.d.ts +121 -0
  89. package/lib/shared/billing/index.d.ts +2 -0
  90. package/lib/shared/billing/orderWebhook.d.ts +75 -0
  91. package/lib/shared/billing/stripeClient.d.ts +45 -0
  92. package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
  93. package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
  94. package/lib/shared/billing/webhookHandler.d.ts +29 -20
  95. package/lib/shared/email/createEmailRoute.d.ts +0 -0
  96. package/lib/shared/email/index.d.ts +0 -0
  97. package/lib/shared/email/provider.d.ts +0 -0
  98. package/lib/shared/email/resendProvider.d.ts +0 -0
  99. package/lib/shared/errorHandling.d.ts +0 -0
  100. package/lib/shared/firebase.d.ts +0 -0
  101. package/lib/shared/github.d.ts +0 -0
  102. package/lib/shared/index.d.ts +0 -0
  103. package/lib/shared/index.js +1 -6
  104. package/lib/shared/index.js.map +4 -4
  105. package/lib/shared/logger.d.ts +0 -0
  106. package/lib/shared/metadata.d.ts +0 -0
  107. package/lib/shared/oauth/exchangeToken.d.ts +0 -0
  108. package/lib/shared/oauth/grantAccess.d.ts +0 -0
  109. package/lib/shared/oauth/index.d.ts +0 -0
  110. package/lib/shared/schema.d.ts +0 -0
  111. package/lib/shared/utils/detectFirestore.d.ts +0 -0
  112. package/lib/shared/utils/external/date.d.ts +0 -0
  113. package/lib/shared/utils/external/index.d.ts +0 -0
  114. package/lib/shared/utils/external/references.d.ts +0 -0
  115. package/lib/shared/utils/external/subscription.d.ts +0 -0
  116. package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
  117. package/lib/shared/utils/functionWrapper.d.ts +1 -1
  118. package/lib/shared/utils/index.d.ts +0 -0
  119. package/lib/shared/utils/internal/auth.d.ts +38 -1
  120. package/lib/shared/utils/internal/firebase.d.ts +0 -0
  121. package/lib/shared/utils/internal/idempotency.d.ts +0 -0
  122. package/lib/shared/utils/internal/index.d.ts +0 -0
  123. package/lib/shared/utils/internal/monitoring.d.ts +0 -0
  124. package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
  125. package/lib/shared/utils/internal/validation.d.ts +0 -8
  126. package/lib/shared/utils/schemaValidation.d.ts +1 -1
  127. package/lib/shared/utils/validation.d.ts +0 -0
  128. package/lib/shared/utils/vercelHelpers.d.ts +8 -0
  129. package/lib/shared/utils.d.ts +0 -56
  130. package/lib/shared/validation.d.ts +0 -0
  131. package/lib/supabase/ai/createAIFunction.d.ts +0 -0
  132. package/lib/supabase/auth/deleteAccount.d.ts +0 -0
  133. package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
  134. package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
  135. package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
  136. package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
  137. package/lib/supabase/baseFunction.d.ts +1 -1
  138. package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
  139. package/lib/supabase/billing/changePlan.d.ts +0 -0
  140. package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
  141. package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
  142. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
  143. package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
  144. package/lib/supabase/crud/aggregate.d.ts +0 -0
  145. package/lib/supabase/crud/bulk.d.ts +1 -1
  146. package/lib/supabase/crud/create.d.ts +0 -0
  147. package/lib/supabase/crud/delete.d.ts +0 -0
  148. package/lib/supabase/crud/entityStore.d.ts +71 -0
  149. package/lib/supabase/crud/get.d.ts +0 -0
  150. package/lib/supabase/crud/index.d.ts +2 -0
  151. package/lib/supabase/crud/list.d.ts +0 -8
  152. package/lib/supabase/crud/update.d.ts +0 -0
  153. package/lib/supabase/edgeFunction.d.ts +0 -0
  154. package/lib/supabase/email/createEmailFunction.d.ts +0 -0
  155. package/lib/supabase/helpers/authProvider.d.ts +5 -5
  156. package/lib/supabase/index.d.ts +11 -2
  157. package/lib/supabase/index.js +1 -3
  158. package/lib/supabase/index.js.map +4 -4
  159. package/lib/supabase/oauth/disconnect.d.ts +0 -0
  160. package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
  161. package/lib/supabase/oauth/getConnections.d.ts +0 -0
  162. package/lib/supabase/oauth/index.d.ts +0 -0
  163. package/lib/supabase/oauth/refreshToken.d.ts +0 -0
  164. package/lib/supabase/registerCrudFunctions.d.ts +0 -0
  165. package/lib/supabase/utils/idempotency.d.ts +0 -0
  166. package/lib/supabase/utils/monitoring.d.ts +0 -0
  167. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  168. package/lib/vercel/api/ai/chat.d.ts +0 -9
  169. package/lib/vercel/api/ai/index.d.ts +0 -0
  170. package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
  171. package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
  172. package/lib/vercel/api/auth/index.d.ts +0 -0
  173. package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
  174. package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
  175. package/lib/vercel/api/billing/backend.d.ts +39 -0
  176. package/lib/vercel/api/billing/cancel.d.ts +8 -0
  177. package/lib/vercel/api/billing/change-plan.d.ts +9 -1
  178. package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
  179. package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
  180. package/lib/vercel/api/billing/index.d.ts +4 -2
  181. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
  182. package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
  183. package/lib/vercel/api/config/constants.d.ts +0 -0
  184. package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
  185. package/lib/vercel/api/config/index.d.ts +0 -0
  186. package/lib/vercel/api/crud/bulk.d.ts +17 -0
  187. package/lib/vercel/api/crud/create.d.ts +8 -0
  188. package/lib/vercel/api/crud/delete.d.ts +8 -0
  189. package/lib/vercel/api/crud/get.d.ts +8 -0
  190. package/lib/vercel/api/crud/index.d.ts +0 -0
  191. package/lib/vercel/api/crud/list.d.ts +8 -0
  192. package/lib/vercel/api/crud/update.d.ts +8 -0
  193. package/lib/vercel/api/index.d.ts +0 -0
  194. package/lib/vercel/api/index.js +1 -3
  195. package/lib/vercel/api/index.js.map +4 -4
  196. package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
  197. package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
  198. package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
  199. package/lib/vercel/api/oauth/index.d.ts +0 -0
  200. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  201. package/lib/vercel/api/utils/cors.d.ts +0 -0
  202. package/lib/vercel/baseFunction.d.ts +4 -1
  203. package/lib/vercel/supabaseAdmin.d.ts +22 -0
  204. package/package.json +25 -26
  205. package/src/firebase/auth/getCustomClaims.ts +4 -5
  206. package/src/firebase/auth/getUserAuthStatus.ts +4 -5
  207. package/src/firebase/auth/removeCustomClaims.ts +4 -5
  208. package/src/firebase/auth/setCustomClaims.ts +4 -5
  209. package/src/firebase/baseFunction.ts +4 -5
  210. package/src/firebase/billing/cancelSubscription.ts +2 -3
  211. package/src/firebase/billing/changePlan.ts +3 -8
  212. package/src/firebase/billing/createCheckoutSession.ts +31 -61
  213. package/src/firebase/billing/createCustomerPortal.ts +5 -6
  214. package/src/firebase/billing/healthCheck.ts +1 -1
  215. package/src/firebase/billing/index.ts +8 -1
  216. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -4
  217. package/src/firebase/billing/webhookHandler.ts +21 -5
  218. package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
  219. package/src/firebase/crud/aggregate.ts +1 -2
  220. package/src/firebase/crud/bulk.ts +5 -6
  221. package/src/firebase/crud/create.ts +5 -6
  222. package/src/firebase/crud/delete.ts +4 -5
  223. package/src/firebase/crud/get.ts +4 -5
  224. package/src/firebase/crud/list.ts +4 -5
  225. package/src/firebase/crud/update.ts +5 -6
  226. package/src/firebase/oauth/githubAccess.ts +2 -3
  227. package/src/firebase/registerCrudFunctions.ts +2 -2
  228. package/src/shared/__tests__/auth.test.ts +0 -3
  229. package/src/shared/__tests__/bulkCore.test.ts +3 -2
  230. package/src/shared/__tests__/errorHandling.test.ts +2 -2
  231. package/src/shared/__tests__/idempotency.test.ts +282 -55
  232. package/src/shared/__tests__/internalValidation.test.ts +3 -42
  233. package/src/shared/__tests__/logger.test.ts +31 -0
  234. package/src/shared/__tests__/rateLimiter.test.ts +2 -8
  235. package/src/shared/__tests__/schemaValidation.test.ts +1 -1
  236. package/src/shared/__tests__/utils.test.ts +3 -2
  237. package/src/shared/__tests__/validation-env.test.ts +0 -0
  238. package/src/shared/ai/createAIRoute.ts +53 -30
  239. package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
  240. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
  241. package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
  242. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
  243. package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
  244. package/src/shared/billing/__tests__/webhookHandler.test.ts +370 -23
  245. package/src/shared/billing/apiVersion.ts +25 -0
  246. package/src/shared/billing/checkoutPrice.ts +125 -0
  247. package/src/shared/billing/checkoutValidation.ts +284 -0
  248. package/src/shared/billing/createCheckout.ts +332 -196
  249. package/src/shared/billing/firestoreIdempotency.ts +189 -0
  250. package/src/shared/billing/helpers/index.ts +0 -1
  251. package/src/shared/billing/helpers/subscriptionManagement.ts +8 -10
  252. package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
  253. package/src/shared/billing/idempotency.ts +104 -168
  254. package/src/shared/billing/idempotencyContract.ts +135 -0
  255. package/src/shared/billing/index.ts +2 -0
  256. package/src/shared/billing/orderWebhook.ts +269 -0
  257. package/src/shared/billing/stripeClient.ts +91 -0
  258. package/src/shared/billing/supabaseIdempotency.ts +228 -0
  259. package/src/shared/billing/tierWebhookEvents.ts +432 -0
  260. package/src/shared/billing/webhookHandler.ts +189 -386
  261. package/src/shared/logger.ts +4 -6
  262. package/src/shared/utils/external/subscription.ts +0 -0
  263. package/src/shared/utils/firebaseHelpers.ts +2 -3
  264. package/src/shared/utils/functionWrapper.ts +1 -2
  265. package/src/shared/utils/internal/auth.ts +55 -7
  266. package/src/shared/utils/internal/monitoring.ts +17 -9
  267. package/src/shared/utils/internal/rateLimiter.ts +14 -5
  268. package/src/shared/utils/internal/validation.ts +0 -18
  269. package/src/shared/utils/schemaValidation.ts +1 -2
  270. package/src/shared/utils/vercelHelpers.ts +3 -3
  271. package/src/shared/utils.ts +5 -99
  272. package/src/shared/validation.ts +1 -1
  273. package/src/supabase/__tests__/bulk.test.ts +3 -1
  274. package/src/supabase/__tests__/entityStore.test.ts +90 -0
  275. package/src/supabase/baseFunction.ts +1 -2
  276. package/src/supabase/billing/cancelSubscription.ts +1 -1
  277. package/src/supabase/billing/changePlan.ts +1 -1
  278. package/src/supabase/billing/createCheckoutSession.ts +11 -41
  279. package/src/supabase/billing/createCustomerPortal.ts +1 -1
  280. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -7
  281. package/src/supabase/billing/stripeWebhook.ts +79 -0
  282. package/src/supabase/crud/aggregate.ts +1 -1
  283. package/src/supabase/crud/bulk.ts +3 -7
  284. package/src/supabase/crud/create.ts +1 -1
  285. package/src/supabase/crud/entityStore.ts +240 -0
  286. package/src/supabase/crud/index.ts +8 -0
  287. package/src/supabase/crud/list.ts +2 -0
  288. package/src/supabase/crud/update.ts +1 -1
  289. package/src/supabase/helpers/authProvider.ts +6 -5
  290. package/src/supabase/index.ts +26 -0
  291. package/src/supabase/utils/rateLimiter.ts +2 -2
  292. package/src/vercel/__tests__/bulk.test.ts +24 -21
  293. package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
  294. package/src/vercel/api/ai/chat.ts +2 -1
  295. package/src/vercel/api/auth/get-custom-claims.ts +2 -3
  296. package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
  297. package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
  298. package/src/vercel/api/auth/set-custom-claims.ts +3 -3
  299. package/src/vercel/api/billing/backend.ts +72 -0
  300. package/src/vercel/api/billing/cancel.ts +2 -4
  301. package/src/vercel/api/billing/change-plan.ts +4 -5
  302. package/src/vercel/api/billing/create-checkout-session.ts +43 -73
  303. package/src/vercel/api/billing/customer-portal.ts +3 -5
  304. package/src/vercel/api/billing/index.ts +4 -2
  305. package/src/vercel/api/billing/refresh-subscription-status.ts +22 -7
  306. package/src/vercel/api/billing/webhook-handler.ts +32 -26
  307. package/src/vercel/api/config/firebase-admin.ts +2 -2
  308. package/src/vercel/api/crud/bulk.ts +6 -9
  309. package/src/vercel/api/crud/create.ts +6 -5
  310. package/src/vercel/api/crud/delete.ts +4 -3
  311. package/src/vercel/api/crud/get.ts +6 -5
  312. package/src/vercel/api/crud/list.ts +6 -5
  313. package/src/vercel/api/crud/update.ts +6 -5
  314. package/src/vercel/api/oauth/check-github-access.ts +5 -5
  315. package/src/vercel/api/oauth/exchange-token.ts +3 -3
  316. package/src/vercel/api/oauth/grant-github-access.ts +5 -5
  317. package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
  318. package/src/vercel/baseFunction.ts +23 -8
  319. package/src/vercel/supabaseAdmin.ts +45 -0
  320. package/lib/shared/ai/createAIHandler.d.ts +0 -39
  321. package/lib/shared/ai/providers/anthropic.d.ts +0 -12
  322. package/lib/shared/ai/providers/google.d.ts +0 -10
  323. package/lib/shared/ai/providers/index.d.ts +0 -23
  324. package/lib/shared/ai/providers/openai.d.ts +0 -10
  325. package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
@@ -12,7 +12,7 @@
12
12
 
13
13
  import { describe, it, expect, vi, beforeEach } from 'vitest';
14
14
 
15
- // Mock detectFirestore before any module that uses it (idempotency.ts)
15
+ // Deprecated auto-detected store (0.1.x call path) must resolve to in-memory
16
16
  vi.mock('../../utils/detectFirestore.js', () => ({
17
17
  isFirestoreConfigured: vi.fn(() => false),
18
18
  }));
@@ -47,6 +47,22 @@ vi.mock('@donotdev/core/server', () => ({
47
47
  PRO: 'pro',
48
48
  PREMIUM: 'premium',
49
49
  },
50
+ DoNotDevError: class DoNotDevError extends Error {
51
+ code: string;
52
+ details?: Record<string, unknown>;
53
+ constructor(
54
+ message: string,
55
+ code = 'internal',
56
+ options?: { details?: Record<string, unknown> }
57
+ ) {
58
+ super(message);
59
+ this.code = code;
60
+ this.details = options?.details;
61
+ this.name = 'DoNotDevError';
62
+ }
63
+ },
64
+ // Fixed ISO string for deterministic assertions
65
+ calculateSubscriptionEndDate: vi.fn(() => '2026-03-18T00:00:00.000Z'),
50
66
  EntityHookError: class EntityHookError extends Error {
51
67
  type: string;
52
68
  constructor(message: string, type: string) {
@@ -62,11 +78,6 @@ vi.mock('@donotdev/firebase/server', () => ({
62
78
  getFirebaseAdminFirestore: vi.fn(),
63
79
  }));
64
80
 
65
- // Mock the date utility — return a fixed ISO string for deterministic assertions
66
- vi.mock('../../utils/external/date.js', () => ({
67
- calculateSubscriptionEndDate: vi.fn(() => '2026-03-18T00:00:00.000Z'),
68
- }));
69
-
70
81
  // Mock logger to silence output in tests
71
82
  vi.mock('../../logger.js', () => ({
72
83
  logger: {
@@ -77,14 +88,10 @@ vi.mock('../../logger.js', () => ({
77
88
  },
78
89
  }));
79
90
 
80
- // Reset idempotency store between tests so events are never pre-marked
81
- import { resetIdempotencyStore } from '../idempotency.js';
91
+ import { createInMemoryIdempotencyStore } from '../idempotency.js';
92
+ import type { IdempotencyStore } from '../idempotency.js';
82
93
  import { processWebhook } from '../webhookHandler.js';
83
-
84
- import type {
85
- UpdateSubscriptionFn,
86
- WebhookAuthProvider,
87
- } from '../webhookHandler.js';
94
+ import type { BillingAuthProvider, UpdateSubscriptionFn } from '@donotdev/core/server';
88
95
 
89
96
  // ---------------------------------------------------------------------------
90
97
  // Shared test fixtures
@@ -113,8 +120,11 @@ const makeConfig = (overrides: Record<string, any> = {}) => ({
113
120
  },
114
121
  });
115
122
 
116
- /** Build a minimal Stripe event object */
123
+ /** Build a minimal Stripe event object (Checkout Sessions default to payment_status 'paid') */
117
124
  function makeEvent(type: string, dataObject: Record<string, any>): any {
125
+ if (type.startsWith('checkout.session.') && !('payment_status' in dataObject)) {
126
+ dataObject = { ...dataObject, payment_status: 'paid' };
127
+ }
118
128
  return {
119
129
  id: `evt_test_${Math.random().toString(36).slice(2)}`,
120
130
  type,
@@ -122,7 +132,7 @@ function makeEvent(type: string, dataObject: Record<string, any>): any {
122
132
  created: Date.now() / 1000,
123
133
  livemode: false,
124
134
  pending_webhooks: 1,
125
- api_version: '2023-10-16',
135
+ api_version: '2026-02-25.clover',
126
136
  object: 'event',
127
137
  };
128
138
  }
@@ -131,7 +141,7 @@ function makeEvent(type: string, dataObject: Record<string, any>): any {
131
141
  function makeStripe(eventOrFn?: any): any {
132
142
  return {
133
143
  webhooks: {
134
- constructEvent: vi.fn((_body, _sig, _secret) => {
144
+ constructEventAsync: vi.fn(async (_body, _sig, _secret) => {
135
145
  if (typeof eventOrFn === 'function') return eventOrFn();
136
146
  return eventOrFn;
137
147
  }),
@@ -143,7 +153,7 @@ function makeStripe(eventOrFn?: any): any {
143
153
  }
144
154
 
145
155
  /** Default mock auth provider */
146
- function makeAuthProvider(): WebhookAuthProvider {
156
+ function makeAuthProvider(): BillingAuthProvider {
147
157
  return {
148
158
  getUser: vi.fn(async () => ({ customClaims: {} })),
149
159
  setCustomUserClaims: vi.fn(async () => {}),
@@ -155,6 +165,12 @@ function makeUpdateSubscription(): UpdateSubscriptionFn {
155
165
  return vi.fn(async () => {});
156
166
  }
157
167
 
168
+ // Fresh store per test (beforeEach) so events are never pre-marked
169
+ let idempotencyStore: IdempotencyStore = createInMemoryIdempotencyStore();
170
+ function resetIdempotencyStore() {
171
+ idempotencyStore = createInMemoryIdempotencyStore();
172
+ }
173
+
158
174
  const RAW_BODY = 'raw-body-bytes';
159
175
  const SIGNATURE = 'stripe-sig-header';
160
176
  const WEBHOOK_SECRET = 'whsec_test_secret';
@@ -172,7 +188,7 @@ async function callProcessWebhook({
172
188
  stripe: any;
173
189
  config?: any;
174
190
  updateSubscription?: UpdateSubscriptionFn;
175
- authProvider?: WebhookAuthProvider | null;
191
+ authProvider?: BillingAuthProvider | null;
176
192
  }) {
177
193
  return processWebhook(
178
194
  RAW_BODY,
@@ -181,7 +197,8 @@ async function callProcessWebhook({
181
197
  stripe,
182
198
  config,
183
199
  updateSubscription,
184
- authProvider
200
+ authProvider,
201
+ idempotencyStore
185
202
  );
186
203
  }
187
204
 
@@ -197,7 +214,7 @@ describe('processWebhook — signature verification', () => {
197
214
  vi.spyOn(console, 'error').mockImplementation(() => {});
198
215
  });
199
216
 
200
- it('calls stripe.webhooks.constructEvent with raw body, signature and secret', async () => {
217
+ it('calls stripe.webhooks.constructEventAsync with raw body, signature and secret', async () => {
201
218
  const event = makeEvent('checkout.session.completed', {
202
219
  metadata: { userId: 'u1', billingConfigKey: 'pro_monthly' },
203
220
  subscription: 'sub_abc',
@@ -210,17 +227,17 @@ describe('processWebhook — signature verification', () => {
210
227
 
211
228
  await callProcessWebhook({ stripe, config, updateSubscription });
212
229
 
213
- expect(stripe.webhooks.constructEvent).toHaveBeenCalledWith(
230
+ expect(stripe.webhooks.constructEventAsync).toHaveBeenCalledWith(
214
231
  RAW_BODY,
215
232
  SIGNATURE,
216
233
  WEBHOOK_SECRET
217
234
  );
218
235
  });
219
236
 
220
- it('throws when constructEvent throws (invalid signature)', async () => {
237
+ it('throws when constructEventAsync rejects (invalid signature)', async () => {
221
238
  const stripe = {
222
239
  webhooks: {
223
- constructEvent: vi.fn(() => {
240
+ constructEventAsync: vi.fn(async () => {
224
241
  throw new Error(
225
242
  'No signatures found matching the expected signature'
226
243
  );
@@ -327,6 +344,27 @@ describe('processWebhook — config validation', () => {
327
344
  expect(validateStripeBackConfig).toHaveBeenCalledWith(config);
328
345
  });
329
346
 
347
+ it('routes with the original config so hooks survive validation (valibot strips unknown keys)', async () => {
348
+ const { validateStripeBackConfig } = await import('@donotdev/core/server');
349
+ // Mimic valibot output: functions (hooks) are dropped from the parse result
350
+ (validateStripeBackConfig as any).mockImplementationOnce((c: unknown) =>
351
+ JSON.parse(JSON.stringify(c))
352
+ );
353
+ const onSubscriptionCreated = vi.fn(async () => {});
354
+ const event = makeEvent('checkout.session.completed', {
355
+ metadata: { userId: 'u_strip', billingConfigKey: 'pro_monthly' },
356
+ subscription: 'sub_strip',
357
+ customer: 'cus_strip',
358
+ });
359
+
360
+ await callProcessWebhook({
361
+ stripe: makeStripe(event),
362
+ config: makeConfig({ onSubscriptionCreated }),
363
+ });
364
+
365
+ expect(onSubscriptionCreated).toHaveBeenCalledOnce();
366
+ });
367
+
330
368
  it('throws when validateStripeBackConfig throws', async () => {
331
369
  const { validateStripeBackConfig } = await import('@donotdev/core/server');
332
370
  (validateStripeBackConfig as any).mockImplementationOnce(() => {
@@ -1181,3 +1219,312 @@ describe('processWebhook — return value', () => {
1181
1219
  });
1182
1220
  });
1183
1221
  });
1222
+
1223
+ // ---------------------------------------------------------------------------
1224
+
1225
+ describe('processWebhook — idempotency lifecycle', () => {
1226
+ beforeEach(() => {
1227
+ resetIdempotencyStore();
1228
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
1229
+ vi.spyOn(console, 'log').mockImplementation(() => {});
1230
+ vi.spyOn(console, 'error').mockImplementation(() => {});
1231
+ });
1232
+
1233
+ it('releases the reservation when routing throws, so the retry is processed', async () => {
1234
+ const event = makeEvent('checkout.session.completed', {
1235
+ metadata: { userId: 'u_retry', billingConfigKey: 'pro_monthly' },
1236
+ subscription: 'sub_retry',
1237
+ customer: 'cus_retry',
1238
+ });
1239
+ const failing = vi.fn(async () => {
1240
+ throw new Error('claims write failed');
1241
+ });
1242
+
1243
+ await expect(
1244
+ callProcessWebhook({ stripe: makeStripe(event), updateSubscription: failing })
1245
+ ).rejects.toThrow();
1246
+
1247
+ const updateSubscription = makeUpdateSubscription();
1248
+ const result = await callProcessWebhook({
1249
+ stripe: makeStripe(event),
1250
+ updateSubscription,
1251
+ });
1252
+ expect(result.message).toBe('Webhook processed');
1253
+ expect(updateSubscription).toHaveBeenCalledOnce();
1254
+ });
1255
+
1256
+ it('marks the event processed only after success, with the owner token', async () => {
1257
+ const markProcessed = vi.fn(async () => {});
1258
+ idempotencyStore = {
1259
+ reserve: vi.fn(async () => ({ state: 'reserved' as const, ownerToken: 'tok_1' })),
1260
+ markProcessed,
1261
+ release: vi.fn(async () => true),
1262
+ };
1263
+ const event = makeEvent('checkout.session.completed', {
1264
+ metadata: { userId: 'u_mark', billingConfigKey: 'pro_monthly' },
1265
+ subscription: 'sub_mark',
1266
+ customer: 'cus_mark',
1267
+ });
1268
+
1269
+ await callProcessWebhook({ stripe: makeStripe(event) });
1270
+ expect(markProcessed).toHaveBeenCalledWith(event.id, 'tok_1');
1271
+ });
1272
+ });
1273
+
1274
+ // ---------------------------------------------------------------------------
1275
+
1276
+ describe('event routing — StripeOrder', () => {
1277
+ const PAID_LINES = [
1278
+ {
1279
+ id: 'li_1',
1280
+ description: 'Serum 30ml',
1281
+ quantity: 24,
1282
+ amount_subtotal: 24000,
1283
+ amount_discount: 0,
1284
+ amount_tax: 4800,
1285
+ amount_total: 28800,
1286
+ price: {
1287
+ product: { id: 'prod_1', deleted: undefined, metadata: { productId: 'serum-30ml' } },
1288
+ },
1289
+ },
1290
+ ];
1291
+
1292
+ function makeOrderConfig(hooks: Record<string, any> = {}) {
1293
+ return {
1294
+ ...makeConfig(),
1295
+ shop_order: {
1296
+ type: 'StripeOrder' as const,
1297
+ name: 'Shop order',
1298
+ currency: 'eur',
1299
+ tax: { mode: 'manual' as const, taxRateIds: ['txr_fr_20'] },
1300
+ taxIdCollection: 'optional' as const,
1301
+ billingAddressCollection: 'required' as const,
1302
+ customerCreation: 'always' as const,
1303
+ invoiceCreation: true,
1304
+ resolveLineItems: vi.fn(),
1305
+ onOrderPaid: vi.fn(async () => {}),
1306
+ ...hooks,
1307
+ },
1308
+ };
1309
+ }
1310
+
1311
+ function makeOrderSession(overrides: Record<string, any> = {}) {
1312
+ return {
1313
+ id: 'cs_order_1',
1314
+ payment_status: 'paid',
1315
+ currency: 'eur',
1316
+ amount_subtotal: 24000,
1317
+ amount_total: 28800,
1318
+ total_details: { amount_discount: 0, amount_shipping: 0, amount_tax: 4800 },
1319
+ customer: 'cus_order',
1320
+ customer_details: {
1321
+ email: 'buyer@pro.example',
1322
+ name: 'Buyer',
1323
+ phone: null,
1324
+ business_name: 'Pro SARL',
1325
+ individual_name: null,
1326
+ address: { line1: '1 rue A', line2: null, postal_code: '75001', city: 'Paris', state: null, country: 'FR' },
1327
+ tax_exempt: 'none',
1328
+ tax_ids: [{ type: 'eu_vat', value: 'FR00123456789' }],
1329
+ },
1330
+ collected_information: null,
1331
+ invoice: 'in_order',
1332
+ payment_intent: 'pi_order',
1333
+ metadata: { userId: 'u_order', billingConfigKey: 'shop_order', orderId: 'ord_42' },
1334
+ ...overrides,
1335
+ };
1336
+ }
1337
+
1338
+ function makeOrderStripe(event: any) {
1339
+ const stripe = makeStripe(event);
1340
+ stripe.checkout = {
1341
+ sessions: {
1342
+ listLineItems: vi.fn(() => ({
1343
+ async *[Symbol.asyncIterator]() {
1344
+ yield* PAID_LINES;
1345
+ },
1346
+ })),
1347
+ },
1348
+ };
1349
+ return stripe;
1350
+ }
1351
+
1352
+ beforeEach(() => {
1353
+ resetIdempotencyStore();
1354
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
1355
+ vi.spyOn(console, 'log').mockImplementation(() => {});
1356
+ vi.spyOn(console, 'error').mockImplementation(() => {});
1357
+ });
1358
+
1359
+ it('completed + paid → onOrderPaid with snapshot, paid lines and context; no subscription update', async () => {
1360
+ const config = makeOrderConfig();
1361
+ const event = makeEvent('checkout.session.completed', makeOrderSession());
1362
+ const stripe = makeOrderStripe(event);
1363
+ const updateSubscription = makeUpdateSubscription();
1364
+
1365
+ await callProcessWebhook({ stripe, config, updateSubscription });
1366
+
1367
+ expect(stripe.checkout.sessions.listLineItems).toHaveBeenCalledWith(
1368
+ 'cs_order_1',
1369
+ { limit: 100, expand: ['data.price.product'] }
1370
+ );
1371
+ const onOrderPaid = config.shop_order.onOrderPaid;
1372
+ expect(onOrderPaid).toHaveBeenCalledOnce();
1373
+ const [snapshot, lines, ctx] = (onOrderPaid as any).mock.calls[0];
1374
+ expect(snapshot).toMatchObject({
1375
+ id: 'cs_order_1',
1376
+ paymentStatus: 'paid',
1377
+ amountTax: 4800,
1378
+ invoiceId: 'in_order',
1379
+ customer: {
1380
+ businessName: 'Pro SARL',
1381
+ taxIds: [{ type: 'eu_vat', value: 'FR00123456789' }],
1382
+ address: { postalCode: '75001', country: 'FR' },
1383
+ },
1384
+ });
1385
+ expect(lines).toEqual([
1386
+ {
1387
+ productId: 'serum-30ml',
1388
+ name: 'Serum 30ml',
1389
+ quantity: 24,
1390
+ amountSubtotal: 24000,
1391
+ amountDiscount: 0,
1392
+ amountTax: 4800,
1393
+ amountTotal: 28800,
1394
+ },
1395
+ ]);
1396
+ expect(ctx).toEqual({
1397
+ userId: 'u_order',
1398
+ orderId: 'ord_42',
1399
+ billingConfigKey: 'shop_order',
1400
+ eventId: event.id,
1401
+ });
1402
+ expect(updateSubscription).not.toHaveBeenCalled();
1403
+ });
1404
+
1405
+ it('completed + unpaid (SEPA) → waits, onOrderPaid not called', async () => {
1406
+ const config = makeOrderConfig();
1407
+ const event = makeEvent(
1408
+ 'checkout.session.completed',
1409
+ makeOrderSession({ payment_status: 'unpaid' })
1410
+ );
1411
+
1412
+ await callProcessWebhook({ stripe: makeOrderStripe(event), config });
1413
+
1414
+ expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
1415
+ });
1416
+
1417
+ it('async_payment_succeeded → onOrderPaid', async () => {
1418
+ const config = makeOrderConfig();
1419
+ const event = makeEvent(
1420
+ 'checkout.session.async_payment_succeeded',
1421
+ makeOrderSession()
1422
+ );
1423
+
1424
+ await callProcessWebhook({ stripe: makeOrderStripe(event), config });
1425
+
1426
+ expect(config.shop_order.onOrderPaid).toHaveBeenCalledOnce();
1427
+ });
1428
+
1429
+ it('async_payment_failed → onOrderPaymentFailed', async () => {
1430
+ const onOrderPaymentFailed = vi.fn(async () => {});
1431
+ const config = makeOrderConfig({ onOrderPaymentFailed });
1432
+ const event = makeEvent(
1433
+ 'checkout.session.async_payment_failed',
1434
+ makeOrderSession({ payment_status: 'unpaid' })
1435
+ );
1436
+
1437
+ await callProcessWebhook({ stripe: makeOrderStripe(event), config });
1438
+
1439
+ expect(onOrderPaymentFailed).toHaveBeenCalledOnce();
1440
+ expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
1441
+ });
1442
+
1443
+ it('expired → onOrderExpired', async () => {
1444
+ const onOrderExpired = vi.fn(async () => {});
1445
+ const config = makeOrderConfig({ onOrderExpired });
1446
+ const event = makeEvent(
1447
+ 'checkout.session.expired',
1448
+ makeOrderSession({ payment_status: 'unpaid' })
1449
+ );
1450
+
1451
+ await callProcessWebhook({ stripe: makeOrderStripe(event), config });
1452
+
1453
+ expect(onOrderExpired).toHaveBeenCalledOnce();
1454
+ });
1455
+
1456
+ it('onOrderPaid failure rejects (Stripe retries) and the retry is processed once', async () => {
1457
+ const onOrderPaid = vi
1458
+ .fn()
1459
+ .mockRejectedValueOnce(new Error('db down'))
1460
+ .mockResolvedValueOnce(undefined);
1461
+ const config = makeOrderConfig({ onOrderPaid });
1462
+ const event = makeEvent('checkout.session.completed', makeOrderSession());
1463
+
1464
+ await expect(
1465
+ callProcessWebhook({ stripe: makeOrderStripe(event), config })
1466
+ ).rejects.toThrow();
1467
+ await callProcessWebhook({ stripe: makeOrderStripe(event), config });
1468
+ const third = await callProcessWebhook({
1469
+ stripe: makeOrderStripe(event),
1470
+ config,
1471
+ });
1472
+
1473
+ expect(onOrderPaid).toHaveBeenCalledTimes(2);
1474
+ expect(third.message).toBe('Event already processed');
1475
+ });
1476
+
1477
+ it('rejects order events rendered with an API version older than collected_information', async () => {
1478
+ const config = makeOrderConfig();
1479
+ const event = makeEvent('checkout.session.completed', makeOrderSession());
1480
+ event.api_version = '2024-12-18.acacia';
1481
+
1482
+ await expect(
1483
+ callProcessWebhook({ stripe: makeOrderStripe(event), config })
1484
+ ).rejects.toThrow();
1485
+ expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
1486
+ });
1487
+
1488
+ it('throws when the order session has no orderId', async () => {
1489
+ const config = makeOrderConfig();
1490
+ const event = makeEvent(
1491
+ 'checkout.session.completed',
1492
+ makeOrderSession({ metadata: { userId: 'u_order', billingConfigKey: 'shop_order' } })
1493
+ );
1494
+
1495
+ await expect(
1496
+ callProcessWebhook({ stripe: makeOrderStripe(event), config })
1497
+ ).rejects.toThrow();
1498
+ expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
1499
+ });
1500
+
1501
+ it('throws when a paid line carries no productId metadata', async () => {
1502
+ const config = makeOrderConfig();
1503
+ const event = makeEvent('checkout.session.completed', makeOrderSession());
1504
+ const stripe = makeOrderStripe(event);
1505
+ stripe.checkout.sessions.listLineItems = vi.fn(() => ({
1506
+ async *[Symbol.asyncIterator]() {
1507
+ yield { ...PAID_LINES[0], price: { product: { id: 'prod_x', metadata: {} } } };
1508
+ },
1509
+ }));
1510
+
1511
+ await expect(callProcessWebhook({ stripe, config })).rejects.toThrow();
1512
+ expect(config.shop_order.onOrderPaid).not.toHaveBeenCalled();
1513
+ });
1514
+
1515
+ it('ignores async/expired events for non-order items', async () => {
1516
+ const updateSubscription = makeUpdateSubscription();
1517
+ const event = makeEvent('checkout.session.expired', {
1518
+ id: 'cs_sub',
1519
+ metadata: { userId: 'u_sub', billingConfigKey: 'pro_monthly' },
1520
+ });
1521
+
1522
+ const result = await callProcessWebhook({
1523
+ stripe: makeStripe(event),
1524
+ updateSubscription,
1525
+ });
1526
+
1527
+ expect(result.message).toBe('Webhook processed');
1528
+ expect(updateSubscription).not.toHaveBeenCalled();
1529
+ });
1530
+ });
@@ -0,0 +1,25 @@
1
+ // packages/functions/src/shared/billing/apiVersion.ts
2
+
3
+ /**
4
+ * @fileoverview Stripe API version pin
5
+ * @description Single source of truth for the Stripe API version the framework
6
+ * reads. The subscription handlers still read pre-basil fields
7
+ * (`invoice.subscription`, `subscription.current_period_end`), so the pin stays
8
+ * on acacia; StripeOrder needs `collected_information` (2025-02-24.acacia).
9
+ *
10
+ * @version 0.2.0
11
+ * @since 0.2.0
12
+ * @author AMBROISE PARK Consulting
13
+ */
14
+
15
+ /**
16
+ * Stripe API version used by `initStripe` when `STRIPE_API_VERSION` is unset,
17
+ * and the oldest version whose Checkout Session payload StripeOrder can read.
18
+ * Webhook event payloads follow the webhook ENDPOINT's API version (set when
19
+ * the endpoint is created in the Dashboard or API), not this value.
20
+ *
21
+ * @version 0.2.0
22
+ * @since 0.2.0
23
+ * @author AMBROISE PARK Consulting
24
+ */
25
+ export const STRIPE_API_VERSION_PIN = '2025-02-24.acacia';
@@ -0,0 +1,125 @@
1
+ // packages/functions/src/shared/billing/checkoutPrice.ts
2
+
3
+ /**
4
+ * @fileoverview Single-price checkout (StripePayment / StripeSubscription)
5
+ * @description 0.1.x pricing rules and the 0.1.x params → Stripe params mapping
6
+ * used by `createCheckoutAlgorithm`.
7
+ *
8
+ * @version 0.2.0
9
+ * @since 0.2.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type Stripe from 'stripe';
14
+
15
+ import type {
16
+ CheckoutMode,
17
+ CheckoutSessionParams,
18
+ CreateCheckoutSessionRequest,
19
+ StripePaymentBackItem,
20
+ StripeSubscriptionBackItem,
21
+ } from '@donotdev/core/server';
22
+
23
+
24
+ /** Price resolved for a single-price item (0.1.x rules). */
25
+ export interface PricePlan {
26
+ /** Fixed price charged; undefined for dynamic pricing */
27
+ priceId?: string;
28
+ /** 0.1.x dynamic pricing (client unitAmount + productName) */
29
+ dynamic: boolean;
30
+ mode: CheckoutMode;
31
+ }
32
+
33
+ /**
34
+ * 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must
35
+ * match the config priceId when set), else 0.1.x dynamic pricing capped by
36
+ * `maxUnitAmount`, else the back-config priceId.
37
+ */
38
+ export function resolvePricePlan(
39
+ item: StripePaymentBackItem | StripeSubscriptionBackItem,
40
+ request: CreateCheckoutSessionRequest
41
+ ): PricePlan {
42
+ const { billingConfigKey: key, priceId, unitAmount, productName } = request;
43
+ const [line] = request.lineItems;
44
+ if (
45
+ request.lineItems.length !== 1 ||
46
+ !line ||
47
+ line.productId !== key ||
48
+ line.quantity !== 1
49
+ ) {
50
+ throw new Error(
51
+ `'${key}' is a single-price item: lineItems must be [{ productId: '${key}', quantity: 1 }]`
52
+ );
53
+ }
54
+
55
+ const dynamic = !priceId && !!unitAmount && !!productName;
56
+ const mode: CheckoutMode =
57
+ request.mode ?? (item.type === 'StripeSubscription' ? 'subscription' : 'payment');
58
+
59
+ if (priceId) {
60
+ if (item.priceId && item.priceId !== priceId) {
61
+ throw new Error('Price ID mismatch with configuration');
62
+ }
63
+ return { priceId, dynamic, mode };
64
+ }
65
+
66
+ if (dynamic) {
67
+ if (mode === 'subscription') {
68
+ throw new Error(
69
+ 'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
70
+ );
71
+ }
72
+ if (!item.maxUnitAmount) {
73
+ throw new Error(
74
+ 'Dynamic pricing requires maxUnitAmount in billing config for security'
75
+ );
76
+ }
77
+ if (unitAmount! > item.maxUnitAmount) {
78
+ throw new Error(
79
+ `Unit amount ${unitAmount} exceeds maximum allowed: ${item.maxUnitAmount}`
80
+ );
81
+ }
82
+ if (unitAmount! < 100) {
83
+ throw new Error('Unit amount must be at least 100 cents (1.00)');
84
+ }
85
+ return { dynamic, mode };
86
+ }
87
+
88
+ if (!item.priceId) {
89
+ throw new Error(
90
+ `'${key}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`
91
+ );
92
+ }
93
+ return { priceId: item.priceId, dynamic, mode };
94
+ }
95
+
96
+ /** 0.1.x params → Stripe params (what the 0.1.x Firebase/Supabase providers sent). */
97
+ export function toStripeSessionParams(
98
+ params: CheckoutSessionParams
99
+ ): Stripe.Checkout.SessionCreateParams {
100
+ const mode = params.mode || 'payment';
101
+ return {
102
+ mode,
103
+ line_items: [
104
+ params.priceId
105
+ ? { price: params.priceId, quantity: 1 }
106
+ : {
107
+ price_data: {
108
+ currency: params.currency || 'eur',
109
+ unit_amount: params.unitAmount!,
110
+ product_data: { name: params.productName! },
111
+ },
112
+ quantity: 1,
113
+ },
114
+ ],
115
+ allow_promotion_codes: params.allowPromotionCodes,
116
+ success_url: params.successUrl,
117
+ cancel_url: params.cancelUrl,
118
+ customer_email: params.customerEmail,
119
+ metadata: params.metadata,
120
+ // Renewal/cancellation events read the subscription's own metadata
121
+ ...(mode === 'subscription' && {
122
+ subscription_data: { metadata: params.metadata },
123
+ }),
124
+ };
125
+ }