@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
@@ -0,0 +1,151 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname } from 'node:path';
4
+ import { Buffer } from 'node:buffer';
5
+ import process from 'node:process';
6
+
7
+ const require = __createRequire(import.meta.url);
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ if (typeof globalThis !== 'undefined') {
12
+ globalThis.require = require;
13
+ globalThis.__filename = __filename;
14
+ globalThis.__dirname = __dirname;
15
+ globalThis.Buffer = Buffer;
16
+ globalThis.process = process;
17
+ if (typeof global === 'undefined') {
18
+ globalThis.global = globalThis;
19
+ }
20
+ }
21
+ import{A as ge,B as P,D as ye,E as _e,F as D,H as we,L as A,V as Y,W as X,_ as B,a as ce,b as V,c as de,d as ue,k as pe,o as le,p as me,q as G,r as fe,s as $,t as T,v as he,x as Ee}from"./chunk-5DTPEM64.js";import{a as p}from"./chunk-NP2AN2TV.js";import{a as i}from"./chunk-AYY7UXNI.js";function E(e){let t,r,o;if(e instanceof A)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new A(r,t,o?{details:o}:void 0)}i(E,"handleError");var ve=T(["firebase","supabase"]);function xt(e){let t=P(ve,e);if(!t.success){let r=ve.options.map(o=>`'${o}'`).join(", ");throw new A(`Invalid backend ${JSON.stringify(e)}: expected one of ${r}`,"invalid-argument")}return t.output}i(xt,"parseAuthBackend");async function z(){let{getFirebaseAdminAuth:e}=await import("./server-32A5RH4C.js");return e()}i(z,"getFirebaseAuth");function je(e){if(!e||typeof e!="string")throw new Error("Authentication required");return e}i(je,"assertAuthenticated");async function Ot(e){je(e);try{let t={};X("serverAuth")?t=(await Y("serverAuth").getUser(e))?.customClaims??{}:t=(await(await z()).getUser(e)).customClaims??{};let r=t.role;if(!(r==="admin"||r==="super"||t.isAdmin===!0||t.isSuper===!0))throw new Error("Admin privileges required");return e}catch(t){throw t instanceof Error&&t.message==="Admin privileges required"?t:new Error("Failed to verify admin status")}}i(Ot,"assertAdmin");function Ve(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}i(Ve,"extractBearerToken");async function Ge(e,t){try{return t==="supabase"?await Ye(e):t==="firebase"?{uid:(await(await z()).verifyIdToken(e)).uid}:X("serverAuth")?{uid:(await Y("serverAuth").verifyToken(e)).uid}:{uid:(await(await z()).verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}i(Ge,"verifyToken");async function Ye(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let n=t(r,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:a}=await n.auth.getUser(e);if(a||!s)throw new Error("Invalid or expired token");return{uid:s.id}}i(Ye,"verifySupabaseToken");async function Xe(e,t){let r=Ve(e.headers.authorization),{uid:o}=await Ge(r,t);return o}i(Xe,"verifyAuthToken");var Nt=Xe;function J(e,t,r=de){let o=ue[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,s=e.completionTokens/1e6*o.completionPer1M,a=n+s;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:s}}}i(J,"calculateCost");async function ze(e,t){let o={anthropic:i(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:i(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:i(async()=>{let{createGoogle:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=tt(e);return(await o())(n)}i(ze,"resolveModel");var Je={maxRequests:30,windowMs:6e4},I=null;async function Qe(){if(I)return I;let e=K("UPSTASH_REDIS_REST_URL"),t=K("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),I={check:i(async()=>{},"check")},I;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),s=new Map;return I={check:i(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=s.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),s.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},I}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),I={check:i(async()=>{},"check")},I}}i(Qe,"getRateLimiter");function Ze(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[s,a]of Object.entries(o))n[s]=e.tool({description:a.description,inputSchema:e.jsonSchema(a.parameters)});return n}i(Ze,"resolveTools");function Q(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}i(Q,"toAIUsage");async function et(e,t,r){let o=ye(e);if(!o.success)return W(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",s=ce[n],a=e.model||t.model||s?.default||"claude-sonnet-4-20250514";if(s){let l=s.models;if(!l.includes(a))return W(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await Qe()).check(r.userId,t.rateLimitConfig||Je)}catch(l){return W(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await ze(n,a)}catch(l){return W(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
22
+ `):void 0),m=e.messages.filter(l=>l.role!=="system").map(l=>({role:l.role,content:l.content})),f=e.maxTokens||t.maxTokens||4096,h=e.temperature??t.temperature??.7,w=r.requestId||crypto.randomUUID(),U=await import("ai"),{streamText:v,generateText:R,toUIMessageStream:L,createUIMessageStreamResponse:M}=U,S=Ze(U,e.tools,t.tools),y=i(async l=>{if(!r.onCostRecord)return;let b=t.cost?.markup??4,ae=J(l,a,b),qe={userId:r.userId,model:a,provider:n,usage:l,providerCost:ae.providerCost,billedCost:ae.billedCost,markup:b,timestamp:new Date().toISOString(),requestId:w};r.onCostRecord(qe).catch(He=>{console.error("[AI] Failed to record cost:",He)})},"recordCost");if(e.stream!==!1){let l=v({model:c,messages:m,instructions:d,maxOutputTokens:f,temperature:h,tools:S,onEnd:i(async({usage:b})=>{await y(Q(b))},"onEnd")});return M({stream:L({stream:l.stream,messageMetadata:i(({part:b})=>b.type==="finish"?{usage:Q(b.totalUsage)}:void 0,"messageMetadata")})})}let g=await R({model:c,messages:m,instructions:d,maxOutputTokens:f,temperature:h,tools:S}),k=Q(g.usage);await y(k);let C=g.toolCalls.map(l=>({id:l.toolCallId,name:l.toolName,args:l.input}));return new Response(JSON.stringify({message:{role:"assistant",content:g.text},usage:k,finishReason:g.finishReason,toolCalls:C.length>0?C:void 0,model:a,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}i(et,"handleAIRequest");function W(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}i(W,"jsonError");function K(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(K,"getEnv");function tt(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=K(r);if(n)return n}let o=K("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}i(tt,"getAIApiKey");function ke(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(ke,"getEnv");function rt(e,t){if(t){let n=ke(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=ke(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(V).find(n=>n.id===e)?.defaultModel??V.STANDARD.defaultModel)}i(rt,"resolveModelForTier");function ot(e){let t=st(e),r=it(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:Ie(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:Ie(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}i(ot,"classifyAIError");function nt(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}i(nt,"mapClassifiedToHTTP");function st(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error?.status=="number")return e.error.status}}i(st,"extractStatus");function it(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}i(it,"extractMessage");function Ie(e){if(e&&typeof e=="object"){let t=e.headers;if(t){let r=typeof t.get=="function"?t.get("retry-after"):t["retry-after"];if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}i(Ie,"extractRetryAfter");var be="2025-02-24.acacia";var Z=be,F="orderId",q="productId";function ee(e){return e===null?null:typeof e=="string"?e:e.id}i(ee,"idOf");function Ae(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}i(Ae,"toAddress");function at(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:ee(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?Ae(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:Ae(r.address)}:null,invoiceId:ee(e.invoice),paymentIntentId:ee(e.payment_intent),metadata:e.metadata??{}}}i(at,"toCheckoutSessionSnapshot");async function ct(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,s=n&&typeof n!="string"&&!n.deleted?n.metadata[q]:void 0;if(!s)throw new Error(`Line item ${o.id} of session ${t} has no ${q} product metadata`);r.push({productId:s,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}i(ct,"listPaidLineItems");async function Re(e,t,r,o,n,s,a){if(!r||r.slice(0,10)<Z.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[F]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${Z} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${Z}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[F];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},f=at(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let w=await ct(a,o.id);await s.onOrderPaid(f,w,m),p.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":p.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":s.onOrderPaymentFailed&&await s.onOrderPaymentFailed(f,m),p.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":s.onOrderExpired&&await s.onOrderExpired(f,m),p.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}i(Re,"handleOrderSessionEvent");function Ce(e,t){let{billingConfigKey:r,priceId:o,unitAmount:n,productName:s}=t,[a]=t.lineItems;if(t.lineItems.length!==1||!a||a.productId!==r||a.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let c=!o&&!!n&&!!s,u=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,dynamic:c,mode:u}}if(c){if(u==="subscription")throw new Error("Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.");if(!e.maxUnitAmount)throw new Error("Dynamic pricing requires maxUnitAmount in billing config for security");if(n>e.maxUnitAmount)throw new Error(`Unit amount ${n} exceeds maximum allowed: ${e.maxUnitAmount}`);if(n<100)throw new Error("Unit amount must be at least 100 cents (1.00)");return{dynamic:c,mode:u}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,dynamic:c,mode:u}}i(Ce,"resolvePricePlan");function Te(e){let t=e.mode||"payment";return{mode:t,line_items:[e.priceId?{price:e.priceId,quantity:1}:{price_data:{currency:e.currency||"eur",unit_amount:e.unitAmount,product_data:{name:e.productName}},quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}i(Te,"toStripeSessionParams");var dt={maxKeys:50,maxKeyLength:40,maxValueLength:500};function re(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}i(re,"validateCheckoutUrl");function xe(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}i(xe,"sanitizeMetadata");function oe(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=dt,s=Object.entries(e);if(s.length>r)throw new Error(`${t}: ${s.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[a,c]of s){if(a.length>o)throw new Error(`${t}: metadata key '${a}' is too long (max ${o} characters)`);if(/[[\]]/.test(a))throw new Error(`${t}: metadata key '${a}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${a}' is too long (max ${n} characters)`)}}i(oe,"assertStripeMetadata");function ne(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&oe(o,r)}i(ne,"assertCheckoutSessionMetadata");function Oe(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&lt(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`)}}i(Oe,"assertResolvedOrder");var ut={minSeconds:1800,maxSeconds:1440*60},Pe=5e3,pt=["card","sepa_debit"];function lt(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:s,invoiceFooter:a}=e;if(o&&o.some(c=>typeof c!="string"||c.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let c of n)if(!pt.includes(c))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${c}'`)}if(s!==void 0){let{minSeconds:c,maxSeconds:u}=ut;if(!Number.isInteger(s)||s<r+c||s>r+u)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${s}`)}if(a!==void 0&&(a.length===0||a.length>Pe))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${Pe} characters`)}i(lt,"assertResolvedOrderSession");var te=new Map;async function se(e,t,r){for(let o of t){let n=te.get(o);if(n||(n=e(o).then(s=>s.inclusive),te.set(o,n),n.catch(()=>te.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}i(se,"assertExclusiveTaxRates");function Ne(e){return"createStripeSession"in e}i(Ne,"isSessionProvider");function Ue(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}i(Ue,"resolveRedirectUrl");function mt(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,s={...r.metadata,[F]:t.orderId};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(a=>({price_data:{currency:e.currency,unit_amount:a.unitAmount,tax_behavior:"exclusive",product_data:{name:a.name,...a.description&&{description:a.description},metadata:{[q]:a.productId}}},quantity:a.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:e.taxIdCollection==="disabled"?{enabled:!1}:{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(a=>({shipping_rate:a}))}},customer_creation:e.customerCreation,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:s,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,customer_email:r.customerEmail,metadata:s,payment_intent_data:{metadata:s}}}i(mt,"buildOrderSessionParams");async function pr(e,...t){let r=t.length===3,[o,n,s,a]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=a[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",f=m?void 0:Ce(d,u);await s.getUser(o);let h=xe(u.metadata??{}),w={...h,userId:o,billingConfigKey:c};oe(m?{...w,[F]:""}:w,"metadata");let U=u.allowPromotionCodes??!0,v=u.unitAmount,R=u.productName;if(d.beforeCheckout){let y={...u,userId:o,mode:f?.mode??"payment",priceId:f?.priceId,metadata:u.metadata??{},allowPromotionCodes:U},g=await d.beforeCheckout(o,y,h);if(!g.allowed)throw new Error(g.reason||"Checkout blocked by beforeCheckout hook");f?.dynamic&&g.overrides&&(v=g.overrides.unitAmount??v,R=g.overrides.productName??R)}let L=Ue(u.successUrl,"success"),M=Ue(u.cancelUrl,"cancel");re(L,"success"),re(M,"cancel");let S;if(d.type==="StripeOrder"){if(!Ne(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await se(C=>n.retrieveTaxRate(C),d.tax.taxRateIds,c);let y=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:h});Oe(y,c);let g=y.session;if(g?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await se(C=>n.retrieveTaxRate(C),g.taxRateIds,c)}if(g?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let k=mt(d,y,{successUrl:L,cancelUrl:M,customerEmail:u.customerEmail,metadata:w});ne(k),S=await n.createStripeSession(k)}else{let y=!!f?.dynamic&&!!v&&!!R;if(y&&d.maxUnitAmount&&v>d.maxUnitAmount)throw new Error(`Hook-overridden unit amount ${v} exceeds maximum allowed: ${d.maxUnitAmount}`);let g={priceId:f?.priceId,unitAmount:y?v:void 0,productName:y?R:void 0,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:w,allowPromotionCodes:U,successUrl:L,cancelUrl:M,mode:f?.mode};if(Ne(n)){let k=Te(g);ne(k),S=await n.createStripeSession(k)}else S=await n.createCheckoutSession(g)}return{sessionId:S.id,sessionUrl:S.url}}i(pr,"createCheckoutAlgorithm");async function fr(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},a={...n,subscription:s};await r.setCustomUserClaims(e,a)}i(fr,"updateUserSubscription");function ie(){if(process.env.FUNCTION_NAME||process.env.FIREBASE_CONFIG)return!0;let e=!!process.env.FIREBASE_PROJECT_ID,t=!!process.env.FIREBASE_CLIENT_EMAIL,r=!!process.env.FIREBASE_PRIVATE_KEY;return e&&t&&r}i(ie,"isFirestoreConfigured");async function gr(){if(!ie())return!1;try{let{getFirebaseAdminFirestore:e}=await import("./server-32A5RH4C.js");return await e().collection("_health_check").limit(1).get(),!0}catch(e){return console.warn("[Firestore] Not available:",e instanceof Error?e.message:String(e)),!1}}i(gr,"isFirestoreAvailable");var _=class extends Error{static{i(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},x=4200*1e3,H=720*60*60*1e3;function O(){return crypto.randomUUID()}i(O,"newOwnerToken");var ft=`
23
+ CREATE TABLE IF NOT EXISTS public.webhook_events (
24
+ event_id TEXT PRIMARY KEY,
25
+ status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
26
+ owner_token UUID NOT NULL,
27
+ reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
28
+ processed_at TIMESTAMPTZ
29
+ );
30
+
31
+ -- Only service_role accesses this table
32
+ ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
33
+
34
+ CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
35
+ ON public.webhook_events (processed_at);
36
+
37
+ -- The functions below run as the caller (SECURITY INVOKER) and refuse every
38
+ -- role but service_role. EXECUTE is deliberately not revoked: on Supabase
39
+ -- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
40
+ -- crashes the backend (signal 11), which restarts every connection.
41
+ CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
42
+ RETURNS VOID
43
+ LANGUAGE plpgsql
44
+ SET search_path = public
45
+ AS $$
46
+ BEGIN
47
+ IF current_user IS DISTINCT FROM 'service_role' THEN
48
+ RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
49
+ USING ERRCODE = 'insufficient_privilege';
50
+ END IF;
51
+ END;
52
+ $$;
53
+
54
+ -- Atomic reservation. Returns:
55
+ -- 'reserved' the caller now owns the event under p_owner_token
56
+ -- 'processed' the event was already processed (skip, answer 2xx)
57
+ -- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
58
+ -- A 'processing' row older than the lease is retaken (abandoned worker).
59
+ CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
60
+ p_event_id TEXT,
61
+ p_owner_token UUID,
62
+ p_lease_seconds INT
63
+ )
64
+ RETURNS TEXT
65
+ LANGUAGE plpgsql
66
+ SET search_path = public
67
+ AS $$
68
+ DECLARE
69
+ v_status TEXT;
70
+ BEGIN
71
+ PERFORM public.webhook_events_assert_service_role();
72
+
73
+ INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
74
+ VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
75
+ ON CONFLICT (event_id) DO UPDATE
76
+ SET owner_token = EXCLUDED.owner_token,
77
+ reserved_at = clock_timestamp()
78
+ WHERE webhook_events.status = 'processing'
79
+ AND webhook_events.reserved_at
80
+ < clock_timestamp() - make_interval(secs => p_lease_seconds);
81
+ IF FOUND THEN
82
+ RETURN 'reserved';
83
+ END IF;
84
+
85
+ SELECT status INTO v_status
86
+ FROM public.webhook_events
87
+ WHERE event_id = p_event_id;
88
+ IF v_status = 'processed' THEN
89
+ RETURN 'processed';
90
+ END IF;
91
+ -- Live lease, or the row was released in between: Stripe retries either way
92
+ RETURN 'in_progress';
93
+ END;
94
+ $$;
95
+
96
+ -- Mark a reservation processed. Returns false when p_owner_token no longer owns
97
+ -- the row (lease retaken, released, or deleted). Repeating it for the same
98
+ -- owner is a no-op that returns true.
99
+ CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
100
+ p_event_id TEXT,
101
+ p_owner_token UUID
102
+ )
103
+ RETURNS BOOLEAN
104
+ LANGUAGE plpgsql
105
+ SET search_path = public
106
+ AS $$
107
+ BEGIN
108
+ PERFORM public.webhook_events_assert_service_role();
109
+
110
+ UPDATE public.webhook_events
111
+ SET status = 'processed',
112
+ processed_at = COALESCE(processed_at, clock_timestamp())
113
+ WHERE event_id = p_event_id
114
+ AND owner_token = p_owner_token;
115
+ RETURN FOUND;
116
+ END;
117
+ $$;
118
+
119
+ -- Drop a reservation after a processing failure. Returns false when
120
+ -- p_owner_token does not own a 'processing' row (nothing is deleted).
121
+ CREATE OR REPLACE FUNCTION public.webhook_event_release(
122
+ p_event_id TEXT,
123
+ p_owner_token UUID
124
+ )
125
+ RETURNS BOOLEAN
126
+ LANGUAGE plpgsql
127
+ SET search_path = public
128
+ AS $$
129
+ BEGIN
130
+ PERFORM public.webhook_events_assert_service_role();
131
+
132
+ DELETE FROM public.webhook_events
133
+ WHERE event_id = p_event_id
134
+ AND owner_token = p_owner_token
135
+ AND status = 'processing';
136
+ RETURN FOUND;
137
+ END;
138
+ $$;
139
+
140
+ -- Enable pg_cron extension (if not already enabled)
141
+ CREATE EXTENSION IF NOT EXISTS pg_cron;
142
+
143
+ -- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
144
+ -- Stripe retries an event for up to 3 days, so older rows are never read again.
145
+ SELECT cron.schedule(
146
+ 'cleanup-webhook-events',
147
+ '0 5 * * *',
148
+ $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
149
+ );
150
+ `,ht=T(["reserved","processed","in_progress"]),Le=le();function Et(e){let t=i(async(r,o,n)=>{let{data:s,error:a}=await e.rpc(r,o);if(a)throw E(a);let c=P(n,s);if(!c.success)throw E(new Error(`${r} returned an unexpected result: ${JSON.stringify(s)}`));return c.output},"call");return{async reserve(r){let o=O(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:x/1e3},ht);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Le))throw new _(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Le)}}}i(Et,"createSupabaseIdempotencyStore");var Me="webhook_idempotency";function gt(){let e=new Map,t=i(async r=>{let o=e.get(r),n=Date.now();if(o?.status==="processed")return{state:"processed"};if(o&&n-o.at<x)return{state:"in_progress"};let s=O();return e.set(r,{status:"processing",ownerToken:s,at:n}),{state:"reserved",ownerToken:s}},"reserve");return{reserve:t,async checkAndReserve(r){return(await t(r)).state!=="reserved"},async markProcessed(r,o){let n=e.get(r);if(o!==void 0&&n?.ownerToken!==o)throw new _(r);e.set(r,{status:"processed",ownerToken:o??n?.ownerToken??O(),at:Date.now()})},async release(r,o){let n=e.get(r);return n?.status!=="processing"||n.ownerToken!==o?!1:(e.delete(r),!0)},async isProcessed(r){return e.get(r)?.status==="processed"}}}i(gt,"createInMemoryIdempotencyStore");var yt=Ee([G(),ge(me(e=>typeof e=="object"&&e!==null&&typeof e.toMillis=="function","expiresAt must be a Firestore Timestamp or a number"),pe(e=>e.toMillis()))]),_t=fe({status:$(T(["processing","processed"])),ownerToken:$(he()),reservedAt:$(G()),expiresAt:$(yt)});function j(e,t){let r=P(_t,t);if(!r.success)throw new Error(`Malformed ${Me}/${e}: ${r.issues.map(o=>o.message).join("; ")}`);return r.output}i(j,"parseEventDoc");function wt(){let e=null,t=i(async()=>{e||(e=await import("./server-32A5RH4C.js"));let o=e.getFirebaseAdminFirestore();return{firestore:o,Timestamp:e.Timestamp,refOf:i(n=>o.collection(Me).doc(n),"refOf")}},"load"),r=i(async o=>{let{firestore:n,Timestamp:s,refOf:a}=await t(),c=a(o);try{return await n.runTransaction(async u=>{let d=await u.get(c),m=Date.now();if(d.exists){let h=j(o,d.data());if(h.status==="processing"){if(m-(h.reservedAt??0)<x)return{state:"in_progress"}}else if((h.expiresAt??0)>=m)return{state:"processed"}}let f=O();return u.set(c,{eventId:o,status:"processing",ownerToken:f,reservedAt:m,expiresAt:s.fromMillis(m+H)}),{state:"reserved",ownerToken:f}})}catch(u){throw E(u)}},"reserve");return{reserve:r,async checkAndReserve(o){return(await r(o)).state!=="reserved"},async markProcessed(o,n){let{firestore:s,Timestamp:a,refOf:c}=await t(),u=c(o),d=Date.now(),m={eventId:o,status:"processed",processedAt:d,expiresAt:a.fromMillis(d+H)};try{if(n===void 0){await u.set(m);return}await s.runTransaction(async f=>{let h=await f.get(u);if((h.exists?j(o,h.data()):null)?.ownerToken!==n)throw new _(o);f.set(u,{...m,ownerToken:n})})}catch(f){throw f instanceof _?f:E(f)}},async release(o,n){let{firestore:s,refOf:a}=await t(),c=a(o);try{return await s.runTransaction(async u=>{let d=await u.get(c);if(!d.exists)return!1;let m=j(o,d.data());return m.status!=="processing"||m.ownerToken!==n?!1:(u.delete(c),!0)})}catch(u){throw E(u)}},async isProcessed(o){let{refOf:n}=await t();try{let s=await n(o).get();if(!s.exists)return!1;let a=j(o,s.data());return a.status!=="processing"&&(a.expiresAt??0)>=Date.now()}catch(s){throw E(s)}}}}i(wt,"createFirestoreIdempotencyStore");var N=null;function $e(){return N||(ie()?N=wt():(console.warn("[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store."),N=gt()),N)}i($e,"createIdempotencyStore");function Tr(){N=null}i(Tr,"resetIdempotencyStore");async function Fe(e,t,r,o,n){let s={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){p.info("[Webhook] Purchase awaiting async payment",{...s,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw E(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await De(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await De(t,r,o,n);return;case"checkout.session.async_payment_failed":p.warn("[Webhook] Async purchase payment failed, nothing granted",{...s,operation:"purchase_payment_failed"});return;case"checkout.session.expired":p.debug("[Webhook] Checkout session expired",s);return}}i(Fe,"handleTierCheckoutEvent");async function De(e,t,r,o){let{userId:n,billingConfigKey:s}=e.metadata||{};if(!n||!s)throw E(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${s}`));let a=t[s];if(!a)throw E(new Error(`Unknown billing config key: ${s}`));if(p.info("[Webhook] Processing purchase",{userId:n,configKey:s,type:a.type,operation:"purchase_processing"}),a.type==="StripePayment"){if(!o)throw E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:D.ACTIVE,subscriptionEnd:B(a.duration),customerId:e.customer},o),a.onPurchaseSuccess)try{await a.onPurchaseSuccess(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(a.type==="StripeSubscription"){if(!o)throw E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:D.ACTIVE,subscriptionEnd:B(a.duration),subscriptionId:e.subscription,customerId:e.customer},o),a.onSubscriptionCreated)try{await a.onSubscriptionCreated(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}p.info("[Webhook] Purchase processed",{userId:n,configKey:s,operation:"purchase_processed"})}i(De,"grantCheckoutPurchase");async function Be(e,t,r,o,n){let s=e.subscription;if(!s)return;let a=await o.subscriptions.retrieve(s),{userId:c,billingConfigKey:u}=a.metadata||{};if(!c||!u){p.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:s,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw E(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:D.ACTIVE,subscriptionEnd:B(d.duration),subscriptionId:s,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,a.metadata||{})}catch(m){p.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}p.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}i(Be,"handleInvoicePaymentSucceeded");async function We(e,t,r,o){let{userId:n,billingConfigKey:s}=e.metadata||{};if(!n||!s)return;let a=t[s];if(!(!a||a.type!=="StripeSubscription")){if(!o)throw E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:_e.FREE,status:D.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),a.onSubscriptionCancelled)try{await a.onSubscriptionCancelled(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}p.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:s,operation:"subscription_cancelled"})}}i(We,"handleSubscriptionDeleted");async function Ke(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){p.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){p.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(s){p.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(s){p.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}p.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}i(Ke,"handlePaymentFailed");var vt=3,St=200;async function Vr(e,t,r,o,n,s,a,c=$e()){try{we(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);p.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return p.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw p.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new A(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:f}=m;a||p.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await bt(d,u,s,o,a)}catch(h){throw p.error("[Webhook] Event processing failed, releasing reservation",{error:h instanceof Error?h:new Error(String(h)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await kt(c,d.id,f),h}return await It(c,d.id,f),{success:!0,message:"Webhook processed"}}catch(u){throw E(u)}}i(Vr,"processWebhook");async function kt(e,t,r){try{await e.release(t,r)||p.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){p.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}i(kt,"releaseReservation");async function It(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let s=n instanceof Error?n:new Error(String(n));if(n instanceof _)throw p.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:s,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=vt)throw p.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:s,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;p.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:s.message}),await new Promise(a=>setTimeout(a,St*o))}}i(It,"markProcessedWithRetry");async function bt(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await At(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await Be(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await We(e.data.object,t,r,n);break;case"invoice.payment_failed":await Ke(e.data.object,t);break;default:p.debug("[Webhook] Unhandled event type",{type:e.type})}}i(bt,"routeEvent");async function At(e,t,r,o,n,s,a,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await Re(e,t,r,o,u,d,a);return}await Fe(e,o,n,s,c)}i(At,"handleCheckoutSessionEvent");export{E as a,ve as b,xt as c,je as d,Ot as e,Ge as f,Xe as g,Nt as h,J as i,et as j,rt as k,ot as l,nt as m,ne as n,be as o,Z as p,F as q,q as r,at as s,ct as t,Re as u,pr as v,fr as w,ie as x,gr as y,_ as z,x as A,H as B,ft as C,Et as D,gt as E,wt as F,$e as G,Tr as H,Vr as I};
151
+ //# sourceMappingURL=chunk-UH4L3EF3.js.map