@donotdev/functions 0.0.20 → 0.1.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 (303) hide show
  1. package/LICENSE.md +3 -3
  2. package/guidelines/FUNCTIONS.md +9 -0
  3. package/guidelines/VERCEL.md +260 -0
  4. package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
  5. package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
  6. package/lib/firebase/auth/index.d.ts +1 -1
  7. package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
  8. package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
  9. package/lib/firebase/baseFunction.d.ts +1 -1
  10. package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
  11. package/lib/firebase/billing/changePlan.d.ts +1 -1
  12. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  13. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  14. package/lib/firebase/billing/index.d.ts +1 -1
  15. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
  16. package/lib/firebase/config/constants.d.ts +4 -4
  17. package/lib/firebase/config/index.d.ts +1 -1
  18. package/lib/firebase/crud/aggregate.d.ts +2 -2
  19. package/lib/firebase/crud/delete.d.ts +1 -1
  20. package/lib/firebase/crud/get.d.ts +1 -1
  21. package/lib/firebase/crud/index.d.ts +1 -1
  22. package/lib/firebase/crud/update.d.ts +1 -1
  23. package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
  24. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
  25. package/lib/firebase/helpers/index.d.ts +1 -1
  26. package/lib/firebase/index.d.ts +1 -1
  27. package/lib/firebase/index.js +3 -3
  28. package/lib/firebase/index.js.map +4 -4
  29. package/lib/firebase/oauth/disconnect.d.ts +1 -1
  30. package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
  31. package/lib/firebase/oauth/getConnections.d.ts +1 -1
  32. package/lib/firebase/oauth/githubAccess.d.ts +6 -6
  33. package/lib/firebase/oauth/index.d.ts +1 -1
  34. package/lib/firebase/oauth/refreshToken.d.ts +1 -1
  35. package/lib/firebase/scheduled/index.d.ts +1 -1
  36. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  37. package/lib/shared/ai/costTracker.d.ts +20 -0
  38. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  39. package/lib/shared/ai/index.d.ts +6 -0
  40. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  41. package/lib/shared/billing/createCheckout.d.ts +11 -5
  42. package/lib/shared/billing/helpers/index.d.ts +1 -1
  43. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
  44. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
  45. package/lib/shared/billing/idempotency.d.ts +2 -2
  46. package/lib/shared/billing/index.d.ts +1 -1
  47. package/lib/shared/billing/webhookHandler.d.ts +1 -1
  48. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  49. package/lib/shared/email/index.d.ts +3 -0
  50. package/lib/shared/email/provider.d.ts +30 -0
  51. package/lib/shared/email/resendProvider.d.ts +22 -0
  52. package/lib/shared/errorHandling.d.ts +1 -1
  53. package/lib/shared/firebase.d.ts +7 -7
  54. package/lib/shared/github.d.ts +16 -11
  55. package/lib/shared/index.d.ts +3 -1
  56. package/lib/shared/index.js +4 -3
  57. package/lib/shared/index.js.map +4 -4
  58. package/lib/shared/logger.d.ts +8 -6
  59. package/lib/shared/metadata.d.ts +3 -3
  60. package/lib/shared/oauth/exchangeToken.d.ts +3 -2
  61. package/lib/shared/oauth/grantAccess.d.ts +3 -2
  62. package/lib/shared/oauth/index.d.ts +1 -1
  63. package/lib/shared/schema.d.ts +2 -2
  64. package/lib/shared/utils/detectFirestore.d.ts +3 -3
  65. package/lib/shared/utils/external/date.d.ts +2 -2
  66. package/lib/shared/utils/external/index.d.ts +1 -1
  67. package/lib/shared/utils/external/references.d.ts +1 -1
  68. package/lib/shared/utils/external/subscription.d.ts +5 -5
  69. package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
  70. package/lib/shared/utils/functionWrapper.d.ts +4 -4
  71. package/lib/shared/utils/index.d.ts +1 -1
  72. package/lib/shared/utils/internal/auth.d.ts +4 -4
  73. package/lib/shared/utils/internal/idempotency.d.ts +3 -2
  74. package/lib/shared/utils/internal/index.d.ts +1 -1
  75. package/lib/shared/utils/internal/monitoring.d.ts +7 -7
  76. package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
  77. package/lib/shared/utils/internal/validation.d.ts +4 -4
  78. package/lib/shared/utils/schemaValidation.d.ts +6 -6
  79. package/lib/shared/utils/validation.d.ts +9 -9
  80. package/lib/shared/utils/vercelHelpers.d.ts +2 -2
  81. package/lib/shared/utils.d.ts +19 -19
  82. package/lib/shared/validation.d.ts +2 -2
  83. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  84. package/lib/supabase/auth/deleteAccount.d.ts +1 -1
  85. package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
  86. package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
  87. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  88. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  89. package/lib/supabase/baseFunction.d.ts +2 -2
  90. package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
  91. package/lib/supabase/billing/changePlan.d.ts +2 -2
  92. package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
  93. package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
  94. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
  95. package/lib/supabase/crud/aggregate.d.ts +2 -1
  96. package/lib/supabase/crud/create.d.ts +2 -1
  97. package/lib/supabase/crud/delete.d.ts +1 -0
  98. package/lib/supabase/crud/get.d.ts +2 -1
  99. package/lib/supabase/crud/index.d.ts +1 -1
  100. package/lib/supabase/crud/list.d.ts +2 -1
  101. package/lib/supabase/crud/update.d.ts +2 -1
  102. package/lib/supabase/edgeFunction.d.ts +56 -0
  103. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  104. package/lib/supabase/helpers/authProvider.d.ts +2 -2
  105. package/lib/supabase/index.d.ts +11 -2
  106. package/lib/supabase/index.js +3 -2
  107. package/lib/supabase/index.js.map +4 -4
  108. package/lib/supabase/oauth/disconnect.d.ts +13 -0
  109. package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
  110. package/lib/supabase/oauth/getConnections.d.ts +13 -0
  111. package/lib/supabase/oauth/index.d.ts +12 -0
  112. package/lib/supabase/oauth/refreshToken.d.ts +13 -0
  113. package/lib/supabase/utils/idempotency.d.ts +1 -1
  114. package/lib/supabase/utils/monitoring.d.ts +1 -1
  115. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  116. package/lib/vercel/api/ai/chat.d.ts +29 -0
  117. package/lib/vercel/api/ai/index.d.ts +1 -0
  118. package/lib/vercel/api/auth/index.d.ts +1 -1
  119. package/lib/vercel/api/billing/cancel.d.ts +1 -1
  120. package/lib/vercel/api/billing/change-plan.d.ts +1 -1
  121. package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
  122. package/lib/vercel/api/billing/index.d.ts +1 -1
  123. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
  124. package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
  125. package/lib/vercel/api/config/constants.d.ts +9 -9
  126. package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
  127. package/lib/vercel/api/config/index.d.ts +1 -1
  128. package/lib/vercel/api/crud/index.d.ts +1 -1
  129. package/lib/vercel/api/index.d.ts +2 -1
  130. package/lib/vercel/api/index.js +3 -2
  131. package/lib/vercel/api/index.js.map +4 -4
  132. package/lib/vercel/api/oauth/check-github-access.d.ts +1 -1
  133. package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
  134. package/lib/vercel/api/oauth/index.d.ts +1 -1
  135. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  136. package/lib/vercel/api/utils/cors.d.ts +4 -4
  137. package/lib/vercel/baseFunction.d.ts +2 -2
  138. package/package.json +38 -5
  139. package/src/firebase/auth/getCustomClaims.ts +3 -3
  140. package/src/firebase/auth/getUserAuthStatus.ts +3 -3
  141. package/src/firebase/auth/index.ts +1 -1
  142. package/src/firebase/auth/removeCustomClaims.ts +3 -3
  143. package/src/firebase/auth/setCustomClaims.ts +70 -69
  144. package/src/firebase/baseFunction.ts +2 -2
  145. package/src/firebase/billing/cancelSubscription.ts +3 -3
  146. package/src/firebase/billing/changePlan.ts +3 -3
  147. package/src/firebase/billing/createCheckoutSession.ts +79 -187
  148. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  149. package/src/firebase/billing/healthCheck.ts +1 -1
  150. package/src/firebase/billing/index.d.ts +11 -11
  151. package/src/firebase/billing/index.ts +1 -1
  152. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
  153. package/src/firebase/billing/webhookHandler.ts +1 -1
  154. package/src/firebase/config/constants.ts +4 -4
  155. package/src/firebase/config/index.ts +1 -1
  156. package/src/firebase/config/secrets.ts +1 -1
  157. package/src/firebase/crud/aggregate.ts +2 -2
  158. package/src/firebase/crud/create.ts +2 -2
  159. package/src/firebase/crud/delete.ts +3 -3
  160. package/src/firebase/crud/get.ts +1 -1
  161. package/src/firebase/crud/index.ts +1 -1
  162. package/src/firebase/crud/list.ts +1 -1
  163. package/src/firebase/crud/update.ts +2 -2
  164. package/src/firebase/helpers/githubAccessHelper.ts +4 -4
  165. package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
  166. package/src/firebase/helpers/index.ts +1 -1
  167. package/src/firebase/index.d.ts +9 -9
  168. package/src/firebase/index.ts +1 -1
  169. package/src/firebase/oauth/disconnect.ts +2 -2
  170. package/src/firebase/oauth/exchangeToken.ts +6 -6
  171. package/src/firebase/oauth/getConnections.ts +2 -2
  172. package/src/firebase/oauth/githubAccess.ts +10 -10
  173. package/src/firebase/oauth/index.ts +1 -1
  174. package/src/firebase/oauth/refreshToken.ts +6 -6
  175. package/src/firebase/registerCrudFunctions.ts +1 -1
  176. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
  177. package/src/firebase/scheduled/index.ts +1 -1
  178. package/src/shared/__tests__/auth.test.ts +46 -0
  179. package/src/shared/__tests__/errorHandling.test.ts +66 -1
  180. package/src/shared/__tests__/firebase.test.ts +293 -0
  181. package/src/shared/__tests__/internalValidation.test.ts +190 -0
  182. package/src/shared/__tests__/metadata.test.ts +66 -0
  183. package/src/shared/__tests__/schema.test.ts +219 -0
  184. package/src/shared/__tests__/schemaValidation.test.ts +72 -0
  185. package/src/shared/__tests__/subscription.test.ts +45 -0
  186. package/src/shared/__tests__/utils.test.ts +281 -0
  187. package/src/shared/__tests__/validation-env.test.ts +73 -0
  188. package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
  189. package/src/shared/ai/classifyAIError.ts +163 -0
  190. package/src/shared/ai/costTracker.ts +51 -0
  191. package/src/shared/ai/createAIRoute.ts +397 -0
  192. package/src/shared/ai/index.ts +8 -0
  193. package/src/shared/ai/resolveModelTier.ts +58 -0
  194. package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
  195. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
  196. package/src/shared/billing/createCheckout.ts +156 -11
  197. package/src/shared/billing/helpers/index.ts +1 -1
  198. package/src/shared/billing/helpers/subscriptionManagement.ts +13 -4
  199. package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
  200. package/src/shared/billing/idempotency.ts +9 -4
  201. package/src/shared/billing/index.ts +1 -1
  202. package/src/shared/billing/webhookHandler.ts +7 -7
  203. package/src/shared/email/createEmailRoute.ts +81 -0
  204. package/src/shared/email/index.ts +5 -0
  205. package/src/shared/email/provider.ts +31 -0
  206. package/src/shared/email/resendProvider.ts +56 -0
  207. package/src/shared/errorHandling.ts +12 -6
  208. package/src/shared/firebase.ts +7 -7
  209. package/src/shared/github.ts +49 -11
  210. package/src/shared/index.d.ts +9 -9
  211. package/src/shared/index.ts +3 -1
  212. package/src/shared/logger.ts +10 -8
  213. package/src/shared/metadata.ts +3 -3
  214. package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
  215. package/src/shared/oauth/exchangeToken.ts +3 -2
  216. package/src/shared/oauth/grantAccess.ts +3 -2
  217. package/src/shared/oauth/index.ts +1 -1
  218. package/src/shared/schema.ts +4 -4
  219. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  220. package/src/shared/utils/detectFirestore.ts +3 -3
  221. package/src/shared/utils/external/date.ts +5 -5
  222. package/src/shared/utils/external/index.ts +1 -1
  223. package/src/shared/utils/external/references.ts +2 -2
  224. package/src/shared/utils/external/subscription.ts +5 -5
  225. package/src/shared/utils/firebaseHelpers.ts +3 -3
  226. package/src/shared/utils/functionWrapper.ts +4 -4
  227. package/src/shared/utils/index.ts +1 -1
  228. package/src/shared/utils/internal/auth.ts +7 -7
  229. package/src/shared/utils/internal/firebase.ts +1 -1
  230. package/src/shared/utils/internal/idempotency.ts +4 -3
  231. package/src/shared/utils/internal/index.ts +1 -1
  232. package/src/shared/utils/internal/monitoring.ts +8 -8
  233. package/src/shared/utils/internal/rateLimiter.ts +12 -9
  234. package/src/shared/utils/internal/validation.ts +5 -5
  235. package/src/shared/utils/schemaValidation.ts +6 -6
  236. package/src/shared/utils/validation.ts +10 -10
  237. package/src/shared/utils/vercelHelpers.ts +3 -3
  238. package/src/shared/utils.ts +19 -19
  239. package/src/shared/validation.ts +3 -3
  240. package/src/supabase/ai/createAIFunction.ts +75 -0
  241. package/src/supabase/auth/deleteAccount.ts +2 -2
  242. package/src/supabase/auth/getCustomClaims.ts +2 -2
  243. package/src/supabase/auth/getUserAuthStatus.ts +2 -2
  244. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  245. package/src/supabase/auth/setCustomClaims.ts +66 -5
  246. package/src/supabase/baseFunction.ts +29 -5
  247. package/src/supabase/billing/cancelSubscription.ts +2 -2
  248. package/src/supabase/billing/changePlan.ts +8 -3
  249. package/src/supabase/billing/createCheckoutSession.ts +18 -4
  250. package/src/supabase/billing/createCustomerPortal.ts +2 -2
  251. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
  252. package/src/supabase/crud/aggregate.ts +2 -1
  253. package/src/supabase/crud/create.ts +2 -1
  254. package/src/supabase/crud/delete.ts +2 -1
  255. package/src/supabase/crud/get.ts +2 -1
  256. package/src/supabase/crud/index.ts +1 -1
  257. package/src/supabase/crud/list.ts +2 -1
  258. package/src/supabase/crud/update.ts +2 -1
  259. package/src/supabase/edgeFunction.ts +195 -0
  260. package/src/supabase/email/createEmailFunction.ts +75 -0
  261. package/src/supabase/helpers/authProvider.ts +2 -2
  262. package/src/supabase/index.ts +22 -2
  263. package/src/supabase/oauth/disconnect.ts +104 -0
  264. package/src/supabase/oauth/exchangeToken.ts +183 -0
  265. package/src/supabase/oauth/getConnections.ts +85 -0
  266. package/src/supabase/oauth/index.ts +15 -0
  267. package/src/supabase/oauth/refreshToken.ts +130 -0
  268. package/src/supabase/registerCrudFunctions.ts +30 -42
  269. package/src/supabase/utils/idempotency.ts +7 -3
  270. package/src/supabase/utils/monitoring.ts +1 -1
  271. package/src/supabase/utils/rateLimiter.ts +1 -1
  272. package/src/vercel/api/ai/chat.ts +77 -0
  273. package/src/vercel/api/ai/index.ts +1 -0
  274. package/src/vercel/api/auth/get-custom-claims.ts +1 -1
  275. package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
  276. package/src/vercel/api/auth/index.ts +1 -1
  277. package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
  278. package/src/vercel/api/auth/set-custom-claims.ts +2 -4
  279. package/src/vercel/api/billing/cancel.ts +3 -3
  280. package/src/vercel/api/billing/change-plan.ts +3 -3
  281. package/src/vercel/api/billing/create-checkout-session.ts +30 -7
  282. package/src/vercel/api/billing/customer-portal.ts +1 -1
  283. package/src/vercel/api/billing/index.ts +1 -1
  284. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  285. package/src/vercel/api/billing/webhook-handler.ts +11 -4
  286. package/src/vercel/api/config/constants.ts +9 -9
  287. package/src/vercel/api/config/firebase-admin.ts +3 -3
  288. package/src/vercel/api/config/index.ts +1 -1
  289. package/src/vercel/api/crud/create.ts +1 -1
  290. package/src/vercel/api/crud/delete.ts +1 -1
  291. package/src/vercel/api/crud/get.ts +1 -1
  292. package/src/vercel/api/crud/index.ts +1 -1
  293. package/src/vercel/api/crud/list.ts +1 -1
  294. package/src/vercel/api/crud/update.ts +1 -1
  295. package/src/vercel/api/index.d.ts +1 -1
  296. package/src/vercel/api/index.ts +2 -1
  297. package/src/vercel/api/oauth/check-github-access.ts +3 -3
  298. package/src/vercel/api/oauth/exchange-token.ts +25 -2
  299. package/src/vercel/api/oauth/grant-github-access.ts +3 -3
  300. package/src/vercel/api/oauth/index.ts +1 -1
  301. package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
  302. package/src/vercel/api/utils/cors.ts +10 -4
  303. package/src/vercel/baseFunction.ts +2 -2
@@ -18,6 +18,7 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- var oo=Object.defineProperty;var i=(e,t)=>oo(e,"name",{value:t,configurable:!0});var d=(e,t)=>()=>(e&&(t=e(e=0)),t);function Mt(e){return{lang:e?.lang??Ut?.lang,message:e?.message,abortEarly:e?.abortEarly??Ut?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ut?.abortPipeEarly}}function ao(e){return so?.get(e)}function co(e){return uo?.get(e)}function po(e,t){return lo?.get(e)?.get(t)}function Te(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function U(e,t,r,n,u){let o=u&&"input"in u?u.input:r.value,a=u?.expected??e.expects??null,p=u?.received??Te(o),c={kind:e.kind,type:e.type,input:o,expected:a,received:p,message:`Invalid ${t}: ${a?`Expected ${a} but r`:"R"}eceived ${p}`,requirement:e.requirement,path:u?.path,issues:u?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},y=e.kind==="schema",l=u?.message??e.message??po(e.reference,c.lang)??(y?co(c.lang):null)??n.message??ao(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),y&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function $(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},Mt())}}}function vr(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Lt(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function ce(e){return{kind:"validation",type:"email",reference:ce,expects:null,async:!1,requirement:fo,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&U(this,"email",t,r),t}}}function ee(e){return{kind:"validation",type:"iso_timestamp",reference:ee,async:!1,expects:null,requirement:mo,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&U(this,"timestamp",t,r),t}}}function dt(e,t){return{kind:"validation",type:"length",reference:dt,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length!==this.requirement&&U(this,"length",r,n,{received:`${r.value.length}`}),r}}}function pt(e,t){return{kind:"validation",type:"max_length",reference:pt,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length>this.requirement&&U(this,"length",r,n,{received:`${r.value.length}`}),r}}}function Ae(e,t){return{kind:"validation",type:"max_value",reference:Ae,async:!1,expects:`<=${e instanceof Date?e.toJSON():Te(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value<=this.requirement)&&U(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():Te(r.value)}),r}}}function S(e,t){return{kind:"validation",type:"min_length",reference:S,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&U(this,"length",r,n,{received:`${r.value.length}`}),r}}}function le(e,t){return{kind:"validation",type:"min_value",reference:le,async:!1,expects:`>=${e instanceof Date?e.toJSON():Te(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value>=this.requirement)&&U(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():Te(r.value)}),r}}}function ft(e,t){return{kind:"validation",type:"regex",reference:ft,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&U(this,"format",r,n),r}}}function z(e){return{kind:"validation",type:"url",reference:z,async:!1,expects:null,requirement(t){try{return new URL(t),!0}catch{return!1}},message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&U(this,"URL",t,r),t}}}function br(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Ve(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function Y(){return{kind:"schema",type:"any",reference:Y,expects:"any",async:!1,get"~standard"(){return $(this)},"~run"(e){return e.typed=!0,e}}}function D(e,t){return{kind:"schema",type:"array",reference:D,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){let u=r.value;if(Array.isArray(u)){r.typed=!0,r.value=[];for(let o=0;o<u.length;o++){let a=u[o],p=this.item["~run"]({value:a},n);if(p.issues){let c={type:"array",origin:"value",input:u,key:o,value:a};for(let y of p.issues)y.path?y.path.unshift(c):y.path=[c],r.issues?.push(y);if(r.issues||(r.issues=p.issues),n.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value.push(p.value)}}else U(this,"type",r,n);return r}}}function j(e){return{kind:"schema",type:"boolean",reference:j,expects:"boolean",async:!1,message:e,get"~standard"(){return $(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:U(this,"type",t,r),t}}}function qt(e,t){return{kind:"schema",type:"custom",reference:qt,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){return this.check(r.value)?r.typed=!0:U(this,"type",r,n),r}}}function ye(e,t){return{kind:"schema",type:"literal",reference:ye,expects:Te(e),async:!1,literal:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:U(this,"type",r,n),r}}}function jt(e,t){return{kind:"schema",type:"loose_object",reference:jt,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){let u=r.value;if(u&&typeof u=="object"){r.typed=!0,r.value={};for(let o in this.entries){let a=this.entries[o];if(o in u||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){let p=o in u?u[o]:Ve(a),c=a["~run"]({value:p},n);if(c.issues){let y={type:"object",origin:"value",input:u,key:o,value:p};for(let l of c.issues)l.path?l.path.unshift(y):l.path=[y],r.issues?.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[o]=c.value}else if(a.fallback!==void 0)r.value[o]=br(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(U(this,"key",r,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:u,key:o,value:u[o]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly)for(let o in u)vr(u,o)&&!(o in this.entries)&&(r.value[o]=u[o])}else U(this,"type",r,n);return r}}}function Vt(e){return{kind:"schema",type:"never",reference:Vt,expects:"never",async:!1,message:e,get"~standard"(){return $(this)},"~run"(t,r){return U(this,"type",t,r),t}}}function K(e,t){return{kind:"schema",type:"nullable",reference:K,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return $(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=Ve(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function te(e,t){return{kind:"schema",type:"nullish",reference:te,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return $(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=Ve(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function W(e){return{kind:"schema",type:"number",reference:W,expects:"number",async:!1,message:e,get"~standard"(){return $(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:U(this,"type",t,r),t}}}function m(e,t){return{kind:"schema",type:"object",reference:m,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){let u=r.value;if(u&&typeof u=="object"){r.typed=!0,r.value={};for(let o in this.entries){let a=this.entries[o];if(o in u||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){let p=o in u?u[o]:Ve(a),c=a["~run"]({value:p},n);if(c.issues){let y={type:"object",origin:"value",input:u,key:o,value:p};for(let l of c.issues)l.path?l.path.unshift(y):l.path=[y],r.issues?.push(l);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[o]=c.value}else if(a.fallback!==void 0)r.value[o]=br(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(U(this,"key",r,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:u,key:o,value:u[o]}]}),n.abortEarly))break}}else U(this,"type",r,n);return r}}}function f(e,t){return{kind:"schema",type:"optional",reference:f,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return $(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Ve(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function P(e,t){return{kind:"schema",type:"picklist",reference:P,expects:Lt(e.map(Te),"|"),async:!1,options:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:U(this,"type",r,n),r}}}function N(e,t,r){return{kind:"schema",type:"record",reference:N,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return $(this)},"~run"(n,u){let o=n.value;if(o&&typeof o=="object"){n.typed=!0,n.value={};for(let a in o)if(vr(o,a)){let p=o[a],c=this.key["~run"]({value:a},u);if(c.issues){let l={type:"object",origin:"key",input:o,key:a,value:p};for(let h of c.issues)h.path=[l],n.issues?.push(h);if(n.issues||(n.issues=c.issues),u.abortEarly){n.typed=!1;break}}let y=this.value["~run"]({value:p},u);if(y.issues){let l={type:"object",origin:"value",input:o,key:a,value:p};for(let h of y.issues)h.path?h.path.unshift(l):h.path=[l],n.issues?.push(h);if(n.issues||(n.issues=y.issues),u.abortEarly){n.typed=!1;break}}(!c.typed||!y.typed)&&(n.typed=!1),c.typed&&(n.value[c.value]=y.value)}}else U(this,"type",n,u);return n}}}function s(e){return{kind:"schema",type:"string",reference:s,expects:"string",async:!1,message:e,get"~standard"(){return $(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:U(this,"type",t,r),t}}}function Ie(e,t){return{kind:"schema",type:"tuple",reference:Ie,expects:"Array",async:!1,items:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){let u=r.value;if(Array.isArray(u)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){let a=u[o],p=this.items[o]["~run"]({value:a},n);if(p.issues){let c={type:"array",origin:"value",input:u,key:o,value:a};for(let y of p.issues)y.path?y.path.unshift(c):y.path=[c],r.issues?.push(y);if(r.issues||(r.issues=p.issues),n.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value.push(p.value)}}else U(this,"type",r,n);return r}}}function hr(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function $e(e,t){return{kind:"schema",type:"union",reference:$e,expects:Lt(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return $(this)},"~run"(r,n){let u,o,a;for(let p of this.options){let c=p["~run"]({value:r.value},n);if(c.typed)if(c.issues)o?o.push(c):o=[c];else{u=c;break}else a?a.push(c):a=[c]}if(u)return u;if(o){if(o.length===1)return o[0];U(this,"type",r,n,{issues:hr(o)}),r.typed=!0}else{if(a?.length===1)return a[0];U(this,"type",r,n,{issues:hr(a)})}return r}}}function re(){return{kind:"schema",type:"unknown",reference:re,expects:"unknown",async:!1,get"~standard"(){return $(this)},"~run"(e){return e.typed=!0,e}}}function $t(e,t,r){return{kind:"schema",type:"variant",reference:$t,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return $(this)},"~run"(n,u){let o=n.value;if(o&&typeof o=="object"){let a,p=0,c=this.key,y=[],l=i((h,v)=>{for(let x of h.options){if(x.type==="variant")l(x,new Set(v).add(x.key));else{let R=!0,I=0;for(let b of v){let E=x.entries[b];if(b in o?E["~run"]({typed:!1,value:o[b]},{abortEarly:!0}).issues:E.type!=="exact_optional"&&E.type!=="optional"&&E.type!=="nullish"){R=!1,c!==b&&(p<I||p===I&&b in o&&!(c in o))&&(p=I,c=b,y=[]),c===b&&y.push(x.entries[b].expects);break}I++}if(R){let b=x["~run"]({value:o},u);(!a||!a.typed&&b.typed)&&(a=b)}}if(a&&!a.issues)break}},"parseOptions");if(l(this,new Set([this.key])),a)return a;U(this,"type",n,u,{input:o[c],expected:Lt(y,"|"),path:[{type:"object",origin:"value",input:o,key:c,value:o[c]}]})}else U(this,"type",n,u);return n}}}function He(e,t,r){let n=e["~run"]({value:t},Mt(r));if(n.issues)throw new Bt(n.issues);return n.value}function g(...e){return{...e[0],pipe:e,get"~standard"(){return $(this)},"~run"(t,r){for(let n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}}}function Ge(e,t,r){let n=e["~run"]({value:t},Mt(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var Ut,so,uo,lo,Bt,fo,oa,mo,M=d(()=>{i(Mt,"getGlobalConfig");i(ao,"getGlobalMessage");i(co,"getSchemaMessage");i(po,"getSpecificMessage");i(Te,"_stringify");i(U,"_addIssue");i($,"_getStandardProps");i(vr,"_isValidObjectKey");i(Lt,"_joinExpects");Bt=class extends Error{static{i(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},fo=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,oa=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u"),mo=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z|[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;i(ce,"email");i(ee,"isoTimestamp");i(dt,"length");i(pt,"maxLength");i(Ae,"maxValue");i(S,"minLength");i(le,"minValue");i(ft,"regex");i(z,"url");i(br,"getFallback");i(Ve,"getDefault");i(Y,"any");i(D,"array");i(j,"boolean");i(qt,"custom");i(ye,"literal");i(jt,"looseObject");i(Vt,"never");i(K,"nullable");i(te,"nullish");i(W,"number");i(m,"object");i(f,"optional");i(P,"picklist");i(N,"record");i(s,"string");i(Ie,"tuple");i(hr,"_subIssues");i($e,"union");i(re,"unknown");i($t,"variant");i(He,"parse");i(g,"pipe");i(Ge,"safeParse")});var he,Er,Sr,xr,Ht=d(()=>{"use strict";he={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},Er={FREE:"free",PRO:"pro",PREMIUM:"premium"},Sr={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},xr={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"}});var Ke,Gt,la,Kt=d(()=>{"use strict";Ke={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},Gt={PAYMENT:"payment",SUBSCRIPTION:"subscription"},la={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});var kr,ma,ga,ya,ha,va,go,yo,ho,ba,Ea,Sa,wr=d(()=>{"use strict";M();Kt();kr=m({userId:f(s()),productId:f(s()),priceId:s(),successUrl:g(s(),z()),cancelUrl:g(s(),z()),customerEmail:f(g(s(),ce())),userEmail:f(g(s(),ce())),metadata:f(N(s(),s())),allowPromotionCodes:f(j()),mode:f(P([Gt.PAYMENT,Gt.SUBSCRIPTION]))}),ma=m({sessionId:s(),sessionUrl:K(g(s(),z()))}),ga=m({userId:s(),tier:s(),status:P(Object.values(Ke)),subscriptionId:K(s()),customerId:s(),subscriptionEnd:K(g(s(),ee())),cancelAtPeriodEnd:j(),updatedAt:g(s(),ee())}),ya=m({tier:s(),subscriptionId:K(s()),customerId:s(),status:P(Object.values(Ke)),subscriptionEnd:K(g(s(),ee())),cancelAtPeriodEnd:j(),updatedAt:g(s(),ee()),isDefault:f(j())}),ha=m({id:s(),type:s(),data:m({object:Y()}),created:g(s(),ee())}),va=jt({userId:f(s()),firebaseUid:f(s()),productType:f(s())}),go=m({type:ye("StripePayment"),name:g(s(),S(1,"Product name is required")),description:f(s()),price:s(),currency:f(g(s(),dt(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:g(s(),S(1,"Stripe price ID is required")),tier:g(s(),S(1,"Tier is required")),duration:g(s(),S(1,"Duration is required")),allowPromotionCodes:f(j()),metadata:f(N(s(),s()))}),yo=m({type:ye("StripeSubscription"),name:g(s(),S(1,"Product name is required")),description:f(s()),price:s(),currency:f(g(s(),dt(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:g(s(),S(1,"Stripe price ID is required")),tier:g(s(),S(1,"Tier is required")),duration:P(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:f(j()),metadata:f(N(s(),s()))}),ho=$t("type",[go,yo]),ba=N(s(),ho),Ea=N(s(),m({name:s(),price:s(),currency:s(),description:f(s()),features:f(D(s())),priceId:s(),allowPromotionCodes:f(j())})),Sa=N(s(),m({type:P(["StripePayment","StripeSubscription"]),name:s(),price:W(),currency:s(),priceId:s(),tier:s(),duration:s(),description:f(s()),metadata:f(N(s(),s())),allowPromotionCodes:f(j())}))});var Tr=d(()=>{"use strict"});var Wt=d(()=>{"use strict";Kt();wr();Tr()});var _a,vo,Pa,Rr=d(()=>{"use strict";M();Ht();Wt();_a=m({id:s(),email:f(K(g(s(),ce()))),displayName:f(K(s())),photoURL:f(K(g(s(),z()))),emailVerified:f(j()),lastLoginAt:f(s()),providerData:f(D(m({providerId:s(),uid:s(),email:f(K(g(s(),ce()))),displayName:f(K(s())),photoURL:f(K(g(s(),z()))),phoneNumber:f(K(s()))}))),role:f(P(Object.values(he))),customClaims:f(N(s(),Y()))}),vo=m({userId:s(),tier:P(Object.values(Er)),status:P(Object.values(Ke)),isActive:f(j()),features:f(D(s())),subscriptionId:K(s()),customerId:s(),subscriptionEnd:K(g(s(),ee())),cancelAtPeriodEnd:j(),updatedAt:g(s(),ee())}),Pa=m({role:f(P(Object.values(he))),subscription:f(vo),features:f(D(P(Object.values(Sr)))),permissions:f(D(P(Object.values(xr)))),githubAccess:f(m({username:f(s()),teamAccess:f(D(s())),repoAccess:f(D(s()))}))})});var Cr=d(()=>{"use strict"});var Ar=d(()=>{"use strict"});var Ir=d(()=>{"use strict";Ht();Rr();Cr();Ar()});var _r=d(()=>{"use strict"});var Pr=d(()=>{"use strict"});var Re,mt=d(()=>{"use strict";Re={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var Ha,Dr=d(()=>{"use strict";mt();Ha={EQ:Re.EQ,NEQ:Re.NEQ,LT:Re.LT,LTE:Re.LTE,GT:Re.GT,GTE:Re.GTE}});var Or=d(()=>{"use strict"});var Nr=d(()=>{"use strict"});var Xa,Za,Ja,Qa,eu,Fr=d(()=>{"use strict";M();mt();Xa=m({collection:g(s(),S(1,"Collection name is required")),data:N(s(),re()),idempotencyKey:f(s())}),Za=m({collection:g(s(),S(1,"Collection name is required")),id:g(s(),S(1,"Entity ID is required"))}),Ja=m({collection:g(s(),S(1,"Collection name is required")),id:g(s(),S(1,"Entity ID is required")),data:N(s(),re()),merge:f(j(),!1)}),Qa=m({collection:g(s(),S(1,"Collection name is required")),id:g(s(),S(1,"Entity ID is required"))}),eu=m({collection:g(s(),S(1,"Collection name is required")),limit:f(g(W(),le(1),Ae(1e3)),1e3),offset:f(g(W(),le(0)),0),orderBy:f(s()),orderDirection:f(P(["asc","desc"]),"desc"),where:f(D(m({field:s(),operator:P(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:re()})))})});var Ur=d(()=>{"use strict"});var Mr=d(()=>{"use strict";Pr();Dr();Or();mt();Nr();Fr();Ur()});var We,gt,zt,w,Lr=d(()=>{"use strict";We={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},gt={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},zt={[We.PERMISSION_DENIED]:{type:gt.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[We.NOT_FOUND]:{type:gt.NOT_FOUND,message:"The requested resource was not found"},[We.ALREADY_EXISTS]:{type:gt.ALREADY_EXISTS,message:"The resource already exists"},[We.INVALID_ARGUMENT]:{type:gt.VALIDATION_ERROR,message:"Invalid argument provided"}},w=class e extends Error{static{i(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=We.INTERNAL,n){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}}});var Br=d(()=>{"use strict";Lr()});var qr=d(()=>{"use strict"});var jr=d(()=>{"use strict"});var Vr=d(()=>{"use strict"});var $r=d(()=>{"use strict"});var Hr=d(()=>{"use strict"});var Gr=d(()=>{"use strict"});var Kr=d(()=>{"use strict";jr();Vr();$r();Hr();Gr()});var Wr=d(()=>{"use strict"});var zr=d(()=>{"use strict";Wr()});var Yr=d(()=>{"use strict"});var Xr=d(()=>{"use strict";Yr()});var Zr=d(()=>{"use strict"});var Jr=d(()=>{"use strict";Zr()});var Qr=d(()=>{"use strict"});var en=d(()=>{"use strict";Qr()});var tn=d(()=>{"use strict"});var rn=d(()=>{"use strict"});var nn=d(()=>{"use strict"});var on=d(()=>{"use strict";tn();rn();nn()});var sn=d(()=>{"use strict"});var an=d(()=>{"use strict";sn()});var un,Yt=d(()=>{"use strict";un=["pull","push","admin","maintain","triage"]});var cn=d(()=>{"use strict"});var Xt,Eo,Bu,qu,ju,Vu,$u,Hu,Gu,ln=d(()=>{"use strict";M();Yt();Xt=m({owner:g(s(),S(1,"Repository owner is required")),repo:g(s(),S(1,"Repository name is required"))}),Eo=P([...un]),Bu=m({userId:g(s(),S(1,"User ID is required")),githubUsername:g(s(),S(1,"GitHub username is required")),repoConfig:Xt,permission:f(Eo,"push"),customClaims:f(N(s(),Y()))}),qu=m({userId:g(s(),S(1,"User ID is required")),githubUsername:g(s(),S(1,"GitHub username is required")),repoConfig:Xt}),ju=m({userId:g(s(),S(1,"User ID is required")),githubUsername:g(s(),S(1,"GitHub username is required")),repoConfig:Xt}),Vu=m({provider:s(),purpose:P(["authentication","api-access"]),code:g(s(),S(1,"Authorization code is required")),redirectUri:g(s(),z("Valid redirect URI is required")),codeVerifier:f(s()),state:f(s()),instance:f(g(s(),z()))}),$u=m({provider:s(),refreshToken:g(s(),S(1,"Refresh token is required")),redirectUri:g(s(),z("Valid redirect URI is required"))}),Hu=m({provider:s()}),Gu=m({userId:g(s(),S(1,"User ID is required"))})});var dn=d(()=>{"use strict";Yt();cn();ln()});var pn=d(()=>{"use strict"});var fn,So,yt,xo,ko,wo,To,Ju,Qu,mn=d(()=>{"use strict";M();fn=m({name:s(),color:s(),icon:s(),customParameters:f(N(s(),s())),button:m({backgroundColor:s(),textColor:s(),borderColor:s(),hoverBackgroundColor:s(),focusOutlineColor:s(),fontWeight:f(s(),"500"),textKey:f(s())})}),So=m({...fn.entries,type:P(["auth","both"]),scopes:f(D(s())),firebaseProviderId:f(s())}),yt=$e([ye(""),g(s(),z())]),xo=m({authUrl:yt,tokenUrl:yt,profileUrl:yt,revokeUrl:f(yt)}),ko=m({authentication:f(D(s())),"api-access":D(s())}),wo=f(m({pkce:f(j(),!1),codeChallengeMethod:f(P(["S256","plain"]),"S256")})),To=m({...fn.entries,type:P(["oauth","both"]),scopes:ko,endpoints:xo,capabilities:wo}),Ju=N(s(),So),Qu=N(s(),To)});var gn=d(()=>{"use strict"});var yn=d(()=>{"use strict";pn();mn();gn()});var hn=d(()=>{"use strict"});var vn=d(()=>{"use strict"});var bn=d(()=>{"use strict";hn();vn()});var En=d(()=>{"use strict"});var Sn=d(()=>{"use strict";En()});var xn=d(()=>{"use strict"});var kn=d(()=>{"use strict";xn()});var wn,lc,Tn=d(()=>{"use strict";wn={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},lc={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:wn.ANALYTICS},marketing:{requiresConsent:wn.MARKETING}}});var Rn=d(()=>{"use strict";Tn()});var Cn=d(()=>{"use strict"});var An=d(()=>{"use strict"});var In=d(()=>{"use strict";Cn();An()});var de=d(()=>{"use strict";Ir();Wt();_r();Mr();Br();qr();Kr();zr();Xr();Jr();en();on();an();dn();yn();bn();Sn();kn();Rn();In()});var ze=d(()=>{"use strict";de()});function _n(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}var Zt=d(()=>{"use strict";i(_n,"detectErrorSource")});function pe(e){return(t,r)=>{if(t instanceof w)return t;if(typeof t!="object"||t===null){let p=typeof t=="string"?t:e.defaultErrorMessage;return new w(r||p,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let n;e.extractErrorCode?n=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(n=t.code);let u=e.defaultErrorCode;n&&e.errorCodeMapping&&n in e.errorCodeMapping&&(u=e.errorCodeMapping[n]);let o;e.extractErrorMessage?o=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(o=t.message),n&&e.friendlyMessageMapping&&n in e.friendlyMessageMapping&&(o=e.friendlyMessageMapping[n]),o||(o=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},n&&(a.originalCode=n)),"originalError"in a||(a.originalError=t),new w(r||o,u,{details:a,source:e.errorSource})}}var ht,Jt=d(()=>{"use strict";ze();i(pe,"createErrorHandler");ht={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"}});function er(e,t,r){return e instanceof w?e:(Pn[t]||Pn.unknown)(e,r)}var _e,Ro,Qt,ve,Co,Ao,Pn,tr=d(()=>{"use strict";M();de();ze();Jt();_e={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Ro={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},Qt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},ve={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...ht},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...ht},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(Ro).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:i(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:i(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:ht,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:_e.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:i(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:_e["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:_e.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:i(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},Co=i(e=>e instanceof Bt?new w(_e["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):pe(ve.validation)(e),"handleValidationError"),Ao=i(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Qt){let t=e,r=Qt[t.type]||"unknown";return new w(t.message||_e[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&zt[e.code]){let t=e,r=zt[t.code];if(r){let n=Qt[r.type]||"unknown";return new w(r.message||_e[n],n,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return pe(ve.entity)(e)},"handleEntityError"),Pn={auth:pe(ve.auth),oauth:pe(ve.oauth),api:pe(ve.api),firebase:pe(ve.firebase),ui:pe(ve.ui),validation:Co,entity:Ao,unknown:pe(ve.unknown)};i(er,"mapToDoNotDevError")});function Dn(e,t,r={}){let n=globalThis.Sentry;n&&n.withScope(u=>{u.setTag("errorSource",t),u.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([o,a])=>{if(typeof a!="function"&&o!=="originalError")try{u.setExtra(o,a)}catch{u.setExtra(o,`[${typeof a}]`)}}),Object.entries(r).forEach(([o,a])=>{if(typeof a!="function")try{u.setExtra(`context.${o}`,a)}catch{u.setExtra(`context.${o}`,`[${typeof a}]`)}}),(e.details?.userId||r.userId)&&u.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),n.captureException(e)})}var rr=d(()=>{"use strict";i(Dn,"captureErrorToSentry")});function Io(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function q(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:n,context:u={},log:o=!0,reportToSentry:a=!0,showNotification:p=!1,severity:c="error"}=r,y=_n(e),l=e instanceof w?e:er(e,y,n);if(n&&!l.userMessageProvided&&(l.message.includes("Error")||l.message.includes("Failed")||l.message.length<10?l=new w(n,l.code,{details:{...l.details,originalMessage:l.message},source:y,userMessageProvided:!0}):l=new w(l.message,l.code,{details:{...l.details,userMessage:n},source:y,userMessageProvided:!0})),o){let h=Io()||typeof window<"u"&&window.__DNDEV_DEBUG,v={code:l.code,message:l.message,source:y};switch(c){case"warning":console.warn(`[DoNotDev] ${l.code}: ${l.message}`,h?{...v,details:l.details}:v);break;case"info":console.info(`[DoNotDev] ${l.code}: ${l.message}`,h?{...v,details:l.details}:v);break;case"success":console.log(`[DoNotDev] ${l.code}: ${l.message}`,h?{...v,details:l.details}:v);break;default:console.error(`[DoNotDev] ${l.code}: ${l.message}`,h?{...v,details:l.details,stack:l.stack}:v)}}return a&&Dn(l,y,u),p&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),l}var On=d(()=>{"use strict";ze();Zt();tr();rr();i(Io,"isDev");i(q,"handleError")});var vt=d(()=>{"use strict";ze();On();Zt();tr();rr();Jt()});var Nn=d(()=>{"use strict";vt()});var Fn=d(()=>{"use strict";vt()});var Un=d(()=>{"use strict";Nn();Fn()});var Mn=d(()=>{"use strict"});var Ln=d(()=>{"use strict"});var Bn=d(()=>{"use strict"});var qn=d(()=>{"use strict"});var jn=d(()=>{"use strict"});var Vn=d(()=>{"use strict"});var $n=d(()=>{"use strict"});var Hn=d(()=>{"use strict"});var Gn=d(()=>{"use strict"});function fe(e,t){if(!e)return!1;let r=Kn[e]??-1,n=Kn[t]??1/0;return r>=n}var Kn,nr=d(()=>{"use strict";de();Kn={[he.GUEST]:0,[he.USER]:1,[he.ADMIN]:2,[he.SUPER]:3};i(fe,"hasRoleAccess")});var Wn=d(()=>{"use strict";de()});var zn=d(()=>{"use strict"});function Yn(e,...t){let r=null,n=!1;return i(function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{n=!1}},"getInstance")}var Xn=d(()=>{"use strict";i(Yn,"createSingleton")});var Zn=d(()=>{"use strict"});function _o(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function Po(e){if(_o(e))return e.visibility}function Do(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?fe(t,"admin"):r==="owner"?!1:fe(t,r)}function Oo(e,t,r){for(let n of r.ownerFields)if(e[n]===t)return!0;return!1}function Jn(e,t,r){let n=e;if(!n||typeof n!="object"||!n.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let u=n.entries,o=[],{documentData:a,uid:p,ownership:c}=r??{},y=c&&p!=null&&a&&Oo(a,p,c);for(let[l,h]of Object.entries(u)){let v=Po(h);if(v==="owner"){y&&o.push(l);continue}Do(v,t)&&o.push(l)}return o}var ir=d(()=>{"use strict";nr();i(_o,"hasVisibility");i(Po,"getFieldVisibility");i(Do,"isFieldVisible");i(Oo,"isOwnerVisible");i(Jn,"getVisibleFields")});function Pe(e,t,r,n){if(!e)return{};let u=n?.uid!=null&&n?.ownership!=null?{documentData:n.documentData??e,uid:n.uid,ownership:n.ownership}:void 0,o=Jn(t,r,u),a={};for(let p of o)Object.prototype.hasOwnProperty.call(e,p)&&(a[p]=e[p]);return a}var Qn=d(()=>{"use strict";ir();i(Pe,"filterVisibleFields")});function Ye(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let r=t,n=[...r.title??[],...r.subtitle??[],...r.content??[],...r.footer??[]];return[...new Set(n)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}var ei=d(()=>{"use strict";i(Ye,"getListCardFieldNames")});var ti=d(()=>{"use strict"});var ri=d(()=>{"use strict";Qn();ei();ir();ti()});var ni=d(()=>{"use strict"});var ii=d(()=>{"use strict";ni()});var oi=d(()=>{"use strict"});var si=d(()=>{"use strict";Un();Mn();Ln();Bn();qn();vt();jn();Vn();$n();Hn();Gn();nr();Wn();zn();Xn();Zn();ri();ii();oi()});var ai=d(()=>{"use strict"});var ui=d(()=>{"use strict"});var ci=d(()=>{"use strict"});var be=d(()=>{si();ai();ui();ci()});var li=d(()=>{"use strict"});var di=d(()=>{"use strict"});function T(e,t){yi.set(e,t)}function F(e,t){return t?e:te(e)}function Zo(){T("text",bt),T("textarea",bt),T("richtext",bt),T("color",bt),T("email",Fo),T("password",Uo),T("url",Mo),T("tel",Ko),T("iban",Wo),T("number",De),T("currency",De),T("price",Xo),T("range",De),T("year",De),T("rating",De),T("duration",De),T("boolean",pi),T("checkbox",pi),T("gdprConsent",Yo),T("date",Oe),T("datetime-local",Oe),T("time",Oe),T("week",Oe),T("month",Oe),T("timestamp",Oe),T("file",fi),T("files",mi),T("document",fi),T("documents",mi),T("image",Lo),T("images",Bo),T("geopoint",qo),T("address",jo),T("map",Vo),T("array",$o),T("select",or),T("multiselect",Ho),T("radio",or),T("combobox",or),T("switch",zo),T("reference",Go),T("hidden",sr),T("avatar",sr),T("badge",sr),T("submit",gi),T("reset",gi)}function Xe(e){if(e.validation?.schema){let n=e.validation.schema;return F(n,e.validation?.required)}let t=yi.get(e.type);if(t){let n=t(e);if(n!==null)return n}let r=re();return F(r,e.validation?.required)}var yi,bt,Fo,Uo,Mo,De,pi,Oe,hi,fi,mi,vi,Lo,Bo,qo,jo,Vo,$o,or,Ho,Go,sr,Ko,Wo,gi,zo,Yo,Xo,ar=d(()=>{"use strict";M();yi=new Map;i(T,"registerSchemaGenerator");i(F,"applyRequired");bt=i(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(S(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(pt(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(ft(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?g(s(),...t):s();return F(r,e.validation?.required)},"textSchema"),Fo=i(e=>{let t=g(s(),ce("Invalid email address"));return F(t,e.validation?.required)},"emailSchema"),Uo=i(e=>{let t=e.validation?.minLength!==void 0?g(s(),S(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):s();return F(t,e.validation?.required)},"passwordSchema"),Mo=i(e=>{let t=g(s(),z("Invalid URL"));return F(t,e.validation?.required)},"urlSchema"),De=i(e=>{let t=[];e.validation?.min!==void 0&&t.push(le(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(Ae(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?g(W(),...t):W();return F(r,e.validation?.required)},"numberSchema"),pi=i(e=>{let t=j();return F(t,e.validation?.required)},"booleanSchema"),Oe=i(e=>{let t=g(s(),ee("Invalid date format"));return F(t,e.validation?.required)},"dateSchema"),hi=m({url:s(),filename:s(),size:W(),mimeType:te(s()),uploadedAt:te(s())}),fi=i(e=>{let t=K(hi);return F(t,e.validation?.required)},"fileSchema"),mi=i(e=>{let t=D(hi);return F(t,e.validation?.required)},"filesSchema"),vi=m({fullUrl:s(),thumbUrl:s()}),Lo=i(e=>F(vi,e.validation?.required),"pictureSchema"),Bo=i(e=>{let t=D(vi);return F(t,e.validation?.required)},"picturesSchema"),qo=i(e=>{let t=m({lat:W(),lng:W()});return F(t,e.validation?.required)},"geopointSchema"),jo=i(e=>{let t=m({formatted_address:s(),latitude:W(),longitude:W(),street_number:te(s()),route:te(s()),locality:te(s()),administrative_area_level_1:te(s()),administrative_area_level_2:te(s()),country:te(s()),postal_code:te(s())});return F(t,e.validation?.required)},"addressSchema"),Vo=i(e=>{let t=N(s(),re());return F(t,e.validation?.required)},"mapSchema"),$o=i(e=>{let t=D(re());return F(t,e.validation?.required)},"arraySchema"),or=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(o=>o.value),u=P(n);return F(u,e.validation?.required)}let r=$e([s(),W()]);return F(r,e.validation?.required)},"selectSchema"),Ho=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(o=>o.value),u=D(P(n));return F(u,e.validation?.required)}let r=D(s());return F(r,e.validation?.required)},"multiselectSchema"),Go=i(e=>{let t=g(s(),S(1,"Invalid ID format"));return F(t,e.validation?.required)},"referenceSchema"),sr=i(e=>{let t=s();return F(t,e.validation?.required)},"stringSchema"),Ko=i(e=>{let t=s();return F(t,e.validation?.required)},"telSchema"),Wo=i(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,n=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",u=[];if(t!==void 0&&u.push(S(t,`IBAN must be at least ${t} characters`)),r!==void 0&&u.push(pt(r,`IBAN must not exceed ${r} characters`)),n){let a=typeof n=="string"?new RegExp(n):n;u.push(ft(a,"Invalid IBAN format"))}let o=u.length>0?g(s(),...u):s();return F(o,e.validation?.required)},"ibanSchema"),gi=i(()=>Vt(),"neverSchema"),zo=i(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let n=[t.checkedValue,t.uncheckedValue],u=P(n);return F(u,e.validation?.required)}let r=j();return F(r,e.validation?.required)},"switchSchema"),Yo=i(e=>qt(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),Xo=i(e=>{let t=m({amount:W(),currency:f(s()),vatIncluded:f(j()),discountPercent:f(g(W(),le(0),Ae(100)))});return F(t,e.validation?.required)},"priceSchema");i(Zo,"registerBuiltinSchemas");Zo();i(Xe,"getSchemaType")});var ur=d(()=>{"use strict";be()});var cr=d(()=>{"use strict";be()});var bi=d(()=>{"use strict";ur();cr()});var Ei=d(()=>{"use strict";di();ar();ur();bi();cr()});var Si=d(()=>{"use strict";be()});var xi,ki,Et,Ze,Ep,St,xt=d(()=>{"use strict";de();xi=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],ki="available",Et=["draft","deleted"],Ze=["id","createdAt","updatedAt","createdById","updatedById"],Ep=[...Ze,"status"],St={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...xi]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}}});var wi=d(()=>{"use strict";de();be();xt()});function Je(e,t){return Object.assign(e,{visibility:t})}function Ce(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},r}function Ti(e){let t=Xe(e);return Je(t,e.visibility)}function Ri(e){let t=Xe({...e,validation:{...e.validation,required:!1}});return Je(t,e.visibility)}function Ci(e){let t=e.fields,r={};for(let[b,E]of Object.entries(t))E.visibility!=="hidden"&&(r[b]=Ti(E));let n=Ce(m(r),e),u={};for(let[b,E]of Object.entries(t))E.visibility!=="hidden"&&(Ze.includes(b)||(u[b]=Ti(E)));let o=Ce(m(u),e),a={};for(let[b,E]of Object.entries(t))if(E.visibility!=="hidden"&&!Ze.includes(b))if(b==="status"){let C=ye("draft");a[b]=Je(C,E.visibility)}else a[b]=Ri(E);let p=Ce(m(a),e),c={};for(let[b,E]of Object.entries(t))E.visibility!=="hidden"&&(Ze.includes(b)||(c[b]=Ri(E)));c.id=Je(Xe(St.id),"technical");let y=Ce(m(c),e),l;if(e.listFields&&e.listFields.length>0){let b=["id","status"],E=[...new Set([...b,...e.listFields])];l={};for(let C of E){let O=r[C];O&&(l[C]=O)}}else l=r;let h=Ce(m(l),e),v,x=Ye(e);if(x.length>0){let b=["id","status"],E=[...new Set([...b,...x])];v={};for(let C of E){let O=r[C];O&&(v[C]=O)}}else v=r;let R=Ce(m(v),e),I=Ce(m({id:Je(Xe(St.id),"technical")}),e);return{create:o,draft:p,update:y,get:n,list:h,listCard:R,delete:I}}var Ai=d(()=>{"use strict";M();de();be();ar();xt();i(Je,"withVisibility");i(Ce,"withMetadata");i(Ti,"createFieldSchema");i(Ri,"createOptionalFieldSchema");i(Ci,"createSchemas")});var Ii=d(()=>{"use strict"});var _i=d(()=>{"use strict"});var Pi=d(()=>{"use strict";Ei();Si();xt();wi();Ai();Ii();_i()});var Di=d(()=>{"use strict";li();Pi()});var H=d(()=>{be();de();Di();be()});import{initializeApp as Ui,getApps as hs,cert as vs}from"firebase-admin/app";import{getAuth as bs}from"firebase-admin/auth";import{getFirestore as Es}from"firebase-admin/firestore";import{getFunctions as Ss}from"firebase-admin/functions";function xs(){let e=hs(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=Ui({credential:vs({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
22
- `)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=Ui():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:bs(t),firestore:Es(t),functions:Ss(t)}}async function Li(){let e=Mi();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function pr(){let e=Mi();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}var Mi,wt=d(()=>{"use strict";H();i(xs,"initializeFirebaseAdminServices");Mi=Yn(xs);i(Li,"getFirebaseAdminApp");i(pr,"getFirebaseAdminFirestore")});var Bi=d(()=>{"use strict";H();wt()});var Tt,Vf,Fe,$f,Qe=d(()=>{"use strict";H();wt();Tt={async getServerAdmin(){try{return Li()}catch(e){throw q(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return pr()}catch(e){throw q(e,"Error getting Admin Firestore")}},async generateServerId(){return(await Tt.getServerFirestore()).collection("_").doc().id}},Vf=Tt.getServerAdmin,Fe=Tt.getServerFirestore,$f=Tt.generateServerId});function Ts(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw q(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw q(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw q(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw q(t,"Failed to convert to ISO string")}}function Rs(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function Ue(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,n=r.data();return{id:r.id,...Ue(n)}}if(Array.isArray(e))return e.map(r=>Ue(r));if(Rs(e))return Ts(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,u]of Object.entries(e))r[n]=Ue(u);return r}return e}function et(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>et(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[n,u]of Object.entries(e))t.includes(n)||u!==void 0&&(r[n]=et(u,t));return r}return e}var Rt=d(()=>{"use strict";H();i(Ts,"firestoreToISOString");i(Rs,"isTimestamp");i(Ue,"transformFirestoreData");i(et,"prepareForFirestore")});var Me,oe,Le,Zf,Jf,Qf,em,tm,rm,qi=d(()=>{"use strict";M();H();Qe();Rt();Me=typeof window<"u",oe={async batchWrite(e,t,r,n,u={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:o="id",generateIds:a=!0,maxBatchSize:p=450,removeFields:c=[],validate:y=!!n}=u,l={successes:0,failures:0,failedItems:[]};try{let h=[],v=await Fe(),x=v.batch(),R=0;for(let b=0;b<t.length;b++){let E=t[b];if(!E){l.failures++,l.failedItems?.push({index:b,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!E[o])throw q(new Error(`Missing ID for delete operation (${o})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:o,operation:r}});let C=v.collection(e).doc(E[o]);x.delete(C)}else{if(y&&n)try{He(n,E)}catch(se){throw q(se,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:o,itemId:E[o]}})}let C=E[o];if(!C&&r==="create"&&a)C=v.collection(e).doc().id,E={...E,[o]:C};else if(!C)throw q(new Error(`Missing ID for ${r} operation (${o})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:o,operation:r}});let O=[o,...c],Q=et(E,O),A=v.collection(e).doc(C);r==="create"?x.create(A,Q):r==="update"&&x.update(A,Q)}R++,R>=p&&(h.push({batch:x,size:R}),x=v.batch(),R=0)}catch(C){l.failures++,l.failedItems?.push({index:b,error:C instanceof Error?C:new Error(String(C))})}}R>0&&h.push({batch:x,size:R});let I=0;for(let{batch:b,size:E}of h){try{await b.commit(),l.successes+=E}catch(C){let O=C instanceof Error?C:new Error(String(C));for(let Q=I;Q<I+E;Q++)l.failures++,l.failedItems?.push({index:Q,error:O})}I+=E}return l}catch(h){throw q(h,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:l.successes+l.failures,successCount:l.successes,failureCount:l.failures}})}},async batchCreate(e,t,r,n={}){return oe.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return oe.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let n=r.idField||"id",u=t.map(o=>({[n]:o}));return oe.batchWrite(e,u,"delete",void 0,r)}return oe.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await Fe()).runTransaction(e)}catch(t){throw q(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:u=!0}=r;try{let o=[];for(let c=0;c<t.length;c+=n)o.push(t.slice(c,c+n));let a=o.map(async c=>{let h=await(await Fe()).collection(e).where("__name__","in",c).get(),v=new Map;return h.forEach(x=>{v.set(x.id,x.data())}),c.map(x=>{let R=v.get(x);return R?u?Ue({id:x,...R}):{id:x,...R}:null})});return(await Promise.all(a)).flat()}catch(o){throw q(o,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},Le=i(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),Zf=Me?Le("batchWrite"):oe.batchWrite,Jf=Me?Le("batchCreate"):oe.batchCreate,Qf=Me?Le("batchUpdate"):oe.batchUpdate,em=Me?Le("batchDelete"):oe.batchDelete,tm=Me?Le("runTransaction"):oe.runTransaction,rm=Me?Le("bulkGet"):oe.bulkGet});var ji=d(()=>{"use strict";H()});var Vi=d(()=>{"use strict";H();Qe();Rt();ji()});var Ct=d(()=>{"use strict";H();Qe()});var $i=d(()=>{"use strict";H();Ct();Ct()});import{FieldValue as qm,Query as jm,Timestamp as Vm}from"firebase-admin/firestore";var Hi=d(()=>{"use strict";Bi();wt();Qe();qi();Vi();$i();Ct();Rt()});M();H();import{createClient as ts}from"@supabase/supabase-js";async function lr(e,t){try{let{error:r}=await e.from("operation_metrics").insert({operation:t.operation,user_id:t.userId||null,status:t.status,duration_ms:t.durationMs||null,metadata:t.metadata||null,error_code:t.errorCode||null,error_message:t.errorMessage||null});r&&console.error("[monitoring] Record failed:",r)}catch(r){console.error("[monitoring] Record failed:",r)}}i(lr,"recordOperationMetrics");async function Jo(e,t,r=24){try{let n=new Date;n.setHours(n.getHours()-r);let{data:u,error:o}=await e.from("operation_metrics").select("status").eq("operation",t).gte("timestamp",n.toISOString());return o||!u||u.length===0?0:u.filter(p=>p.status==="failed").length/u.length*100}catch(n){return console.error("[monitoring] Get failure rate failed:",n),0}}i(Jo,"getFailureRate");async function Qo(e,t,r=24){try{let n=new Date;n.setHours(n.getHours()-r);let{data:u,error:o}=await e.from("operation_metrics").select("operation").eq("user_id",t).gte("timestamp",n.toISOString());if(o||!u)return{};let a={};for(let p of u)a[p.operation]=(a[p.operation]||0)+1;return a}catch(n){return console.error("[monitoring] Get operation counts failed:",n),{}}}i(Qo,"getOperationCounts");async function es(e,t,r=24){try{let n=new Date;n.setHours(n.getHours()-r);let{data:u,error:o}=await e.from("operation_metrics").select("operation, duration_ms").gte("timestamp",n.toISOString()).not("duration_ms","is",null);if(o||!u)return[];let a={};for(let c of u)c.duration_ms&&(a[c.operation]||(a[c.operation]={sum:0,count:0}),a[c.operation].sum+=c.duration_ms,a[c.operation].count+=1);let p=[];for(let[c,y]of Object.entries(a)){let l=y.sum/y.count;l>=t&&p.push({operation:c,avgDuration:Math.round(l),count:y.count})}return p.sort((c,y)=>y.avgDuration-c.avgDuration)}catch(n){return console.error("[monitoring] Get slow operations failed:",n),[]}}i(es,"getSlowOperations");var kt={api:{maxAttempts:100,windowMs:6e4,blockDurationMs:3e5},create:{maxAttempts:20,windowMs:6e4,blockDurationMs:3e5},update:{maxAttempts:30,windowMs:6e4,blockDurationMs:3e5},delete:{maxAttempts:10,windowMs:6e4,blockDurationMs:6e5},read:{maxAttempts:200,windowMs:6e4,blockDurationMs:3e5}};async function dr(e,t,r){let n=Date.now(),u=i(()=>({allowed:!1,remaining:0,resetAt:new Date(n+r.windowMs),blockRemainingSeconds:Math.ceil(r.windowMs/1e3)}),"failClosed");try{let{data:o,error:a}=await e.rpc("rate_limit_check",{p_key:t,p_max_attempts:r.maxAttempts,p_window_ms:r.windowMs,p_block_duration_ms:r.blockDurationMs});if(a)return a.code==="42883"||a.message?.includes("function")&&a.message?.includes("does not exist")?console.error("[rateLimit] rate_limit_check function not found. Deploy the required SQL migration (see RATE_LIMIT_CHECK_SQL).",a.message):console.error("[rateLimit] rate_limit_check RPC failed (network/runtime error):",a.message,a.code),u();let p=o;return{allowed:p.allowed,remaining:p.remaining,resetAt:new Date(p.reset_at_epoch_ms),blockRemainingSeconds:p.block_remaining_seconds}}catch(o){return console.error("[rateLimit] Unexpected error in checkRateLimitWithPostgres:",o),u()}}i(dr,"checkRateLimitWithPostgres");function _(e,t,r,n="user",u){return async o=>{try{let a=Ne("ALLOWED_ORIGIN","*"),p=i((G,V)=>Oi(G,V,a),"respond");if(o.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":a,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"authorization, content-type, x-client-info, apikey"}});if(o.method!=="POST")return p({error:"Method not allowed"},405);let c=o.headers.get("authorization");if(!c?.startsWith("Bearer "))return p({error:"Missing or invalid authorization header"},401);let y=c.slice(7),l=rs("SUPABASE_URL"),h=Ne("SUPABASE_SECRET_KEY")||Ne("SUPABASE_SERVICE_ROLE_KEY");if(!h)throw new Error("Missing environment variable: SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY");let v=ts(l,h,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:x},error:R}=await v.auth.getUser(y);if(R||!x)return p({error:"Invalid or expired token"},401);let b=(x.app_metadata??{}).role||"user";if(n!=="guest"){if(!fe(b,n))return p({error:`Access denied. Required role: ${n}, your role: ${b}`},403)}if(!(Ne("DISABLE_RATE_LIMITING")==="true")){let G=n==="guest"&&x.id==="guest"?`ip_${is(o)}`:`uid_${x.id}`,V=`${e}_${G}`,ke=kt[e]||kt.api,ge=await dr(v,V,ke);if(!ge.allowed)return u?.audit({type:"rate_limit.exceeded",userId:x.id,metadata:{operation:e,remaining:0}}),p({error:`Rate limit exceeded. Try again in ${ge.blockRemainingSeconds} seconds.`},429)}let C=o.headers.get("content-length"),O=1048576;if(C&&parseInt(C,10)>O)return p({error:`Request body too large. Maximum size: ${O} bytes`},413);let Q=await o.json().catch(()=>({})),A=Ge(t,Q);if(!A.success){let G=A.issues.map(V=>V.message).join(", ");return p({error:`Validation failed: ${G}`},400)}let se=Ne("ENABLE_METRICS")==="true",ae=se?Date.now():0,xe,X=null;try{xe=await r(A.output,{uid:x.id,userRole:b,supabaseAdmin:v})}catch(G){throw X=G instanceof Error?G:new Error(String(G)),G}finally{if(se){let G=Date.now()-ae;await lr(v,{operation:e,userId:x.id,status:X?"failed":"success",durationMs:G,metadata:{requestId:o.headers.get("x-request-id")||void 0},errorCode:X?os(X.message):void 0,errorMessage:X?X.message:void 0})}}return p(xe,200)}catch(a){console.error(`[${e}] Error:`,a);let p=a instanceof Error?a.message:"Internal server error",c=ss(p),y=Ne("ALLOWED_ORIGIN","*");return Oi({error:p},c,y)}}}i(_,"createSupabaseHandler");function Oi(e,t,r="*"){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":r}})}i(Oi,"jsonResponse");function rs(e){let t=typeof Deno<"u"?Deno.env.get(e):process.env[e];if(!t)throw new Error(`Missing environment variable: ${e}`);return t}i(rs,"getEnvOrThrow");function Ne(e,t=""){return(typeof Deno<"u"?Deno.env.get(e):process.env[e])||t}i(Ne,"getEnv");var ns=/^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;function Ni(e){return ns.test(e)}i(Ni,"isValidIp");function is(e){let t=e.headers.get("x-forwarded-for");if(t){let n=t.split(",").map(o=>o.trim()).filter(Boolean),u=n[n.length-1];if(u&&Ni(u))return u}let r=e.headers.get("cf-connecting-ip");return r&&Ni(r)?r:"unknown"}i(is,"getClientIp");function os(e){return e.includes("Rate limit")?"rate-limit-exceeded":e.includes("not found")||e.includes("No active")?"not-found":e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?"permission-denied":e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?"invalid-argument":e.includes("already-exists")||e.includes("Duplicate")?"already-exists":"internal"}i(os,"getErrorCode");function ss(e){return e.includes("Rate limit")?429:e.includes("not found")||e.includes("No active")?404:e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?403:e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?400:500}i(ss,"getErrorStatus");function ne(e){return{async getUser(t){let{data:r,error:n}=await e.auth.admin.getUserById(t);if(n)throw n;return{customClaims:r.user?.app_metadata??{}}},async setCustomUserClaims(t,r){let{error:n}=await e.auth.admin.updateUserById(t,{app_metadata:r});if(n)throw n}}}i(ne,"createSupabaseAuthProvider");M();var as=m({});function us(){return _("delete-account",as,async(e,t)=>{let{error:r}=await t.supabaseAdmin.auth.admin.deleteUser(t.uid);if(r)throw r;return{success:!0}})}i(us,"createDeleteAccount");M();var cs=m({customClaims:N(s(),re()),idempotencyKey:f(s())});function ls(){return _("set-custom-claims",cs,async(e,t)=>{let{data:{user:r},error:n}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(n||!r)throw new Error("User not found");let o={...r.app_metadata??{},...e.customClaims},{error:a}=await t.supabaseAdmin.auth.admin.updateUserById(t.uid,{app_metadata:o});if(a)throw a;return{success:!0,customClaims:o}},"user")}i(ls,"createSetCustomClaims");M();var ds=m({});function ps(){return _("get-custom-claims",ds,async(e,t)=>{let{data:{user:r},error:n}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(n||!r)throw new Error("User not found");return{customClaims:r.app_metadata??{}}},"user")}i(ps,"createGetCustomClaims");M();var fs=m({claimsToRemove:g(D(s()),S(1,"At least one claim key is required"))});function ms(){return _("remove-custom-claims",fs,async(e,t)=>{let{data:{user:r},error:n}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(n||!r)throw new Error("User not found");let u={...r.app_metadata??{}};for(let a of e.claimsToRemove)delete u[a];let{error:o}=await t.supabaseAdmin.auth.admin.updateUserById(t.uid,{app_metadata:u});if(o)throw o;return{success:!0,customClaims:u}},"user")}i(ms,"createRemoveCustomClaims");M();var gs=m({});function ys(){return _("get-user-auth-status",gs,async(e,t)=>{let{data:{user:r},error:n}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(n||!r)throw new Error("User not found");return{uid:r.id,email:r.email,emailVerified:r.email_confirmed_at!=null,customClaims:r.app_metadata??{},disabled:r.banned_until!=null}},"user")}i(ys,"createGetUserAuthStatus");H();async function Fi(e,t,r,n){let{priceId:u,userId:o,customerEmail:a,metadata:p={},allowPromotionCodes:c=!0,successUrl:y,cancelUrl:l,mode:h="payment"}=e,v=p.billingConfigKey;if(!v)throw new Error("Missing billingConfigKey in metadata");let x=n[v];if(!x)throw new Error(`Invalid billing config key: ${v}`);if(x.priceId!==u)throw new Error("Price ID mismatch with configuration");if(!o)throw new Error("Missing userId in request");await r.getUser(o);let R=await t.createCheckoutSession({priceId:u,customerEmail:a,metadata:{...p,userId:o,billingConfigKey:v},allowPromotionCodes:c,successUrl:y||`${process.env.FRONTEND_URL}/billing/success`,cancelUrl:l||`${process.env.FRONTEND_URL}/billing/cancel`,mode:h});return{sessionId:R.id,sessionUrl:R.url}}i(Fi,"createCheckoutAlgorithm");M();H();Hi();import As from"stripe";var At=null;function ie(e){if(!e)throw new Error("Stripe API key is required");let t=process.env.STRIPE_API_VERSION||"2024-12-18.acacia";return At=new As(e,{apiVersion:t}),At}i(ie,"initStripe");function Is(){if(!At){let e=process.env.STRIPE_SECRET_KEY;if(e)ie(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return At}i(Is,"getStripe");var me=new Proxy({},{get(e,t){return Is()[t]}});function Ee(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}i(Ee,"validateStripeEnvironment");function It(e,t){if(!e||typeof e!="object")throw new Error("Invalid document data");if(Array.isArray(e))throw new Error("Document data cannot be an array");if(t)try{He(t,e)}catch(r){if(r?.issues){let n=r.issues.map(u=>`${u.path?.map(o=>o.key).join(".")||"root"}: ${u.message}`).join("; ");throw new w(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:r.issues}})}throw r}}i(It,"validateDocument");function _s(e){return _("create-checkout-session",kr,async(t,r)=>{ie(Ps()),Ee();let n=ne(r.supabaseAdmin);return Fi(t,{async createCheckoutSession(o){let a=await me.checkout.sessions.create({mode:o.mode||"payment",line_items:[{price:o.priceId,quantity:1}],customer_email:o.customerEmail||void 0,success_url:o.successUrl,cancel_url:o.cancelUrl,allow_promotion_codes:o.allowPromotionCodes,metadata:o.metadata,...o.mode==="subscription"&&{subscription_data:{metadata:o.metadata}}});return{id:a.id,url:a.url}}},n,e)})}i(_s,"createCheckoutSession");function Ps(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Ps,"getStripeKey");M();H();async function fr(e,t,r){let u=(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 o={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={...u,subscription:o};await r.setCustomUserClaims(e,a)}i(fr,"updateUserSubscription");H();function Be(e){let t,r,n;if(e instanceof w)t=e.code,r=e.message,n=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",n={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let u=e;switch(u.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=u.message,n=void 0}else t="internal",r=e instanceof Error?e.message:"An unexpected error occurred",n=void 0;throw new w(r,t,n?{details:n}:void 0)}i(Be,"handleError");async function Gi(e,t){Ee();let u=((await t.getUser(e)).customClaims||{}).subscription,o=u?.subscriptionId;if(!o)throw Be(new Error("No active subscription found"));let a=await me.subscriptions.update(o,{cancel_at_period_end:!0}),c=["active","canceled","past_due","trialing","incomplete"].includes(a.status)?a.status:"incomplete";return await fr(e,{tier:u?.tier||"free",status:c,subscriptionEnd:new Date(a.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:a.id,customerId:a.customer},t),{success:!0,endsAt:new Date(a.current_period_end*1e3).toISOString()}}i(Gi,"cancelUserSubscription");async function Ki(e,t,r,n,u){Ee();let o=n[r];if(!o||o.type!=="StripeSubscription")throw Be(new Error("Invalid plan"));if(o.priceId!==t)throw Be(new Error("Price ID mismatch with configuration"));let y=((await u.getUser(e)).customClaims||{}).subscription?.subscriptionId;if(!y)throw Be(new Error("No active subscription found"));let l=await me.subscriptions.retrieve(y),h=await me.subscriptions.update(y,{items:[{id:l.items.data[0]?.id,price:t}],proration_behavior:"create_prorations"}),x=["active","canceled","past_due","trialing","incomplete"].includes(h.status)?h.status:"incomplete";return await fr(e,{tier:o.tier,status:x,subscriptionEnd:new Date(h.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:h.cancel_at_period_end,subscriptionId:h.id,customerId:h.customer},u),{success:!0,newTier:o.tier,newPrice:o.price}}i(Ki,"changeUserPlan");async function Wi(e,t,r){Ee();let a=((await t.getUser(e)).customClaims||{}).subscription?.customerId;if(!a)throw Be(new Error("No customer found"));return{url:(await me.billingPortal.sessions.create({customer:a,return_url:r||`${process.env.FRONTEND_URL}/billing`})).url}}i(Wi,"createCustomerPortalSession");var Ds=m({userId:g(s(),S(1,"User ID is required"))});function Os(){return _("cancel-subscription",Ds,async(e,t)=>{ie(Ns());let r=ne(t.supabaseAdmin);return Gi(e.userId,r)})}i(Os,"createCancelSubscription");function Ns(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Ns,"getStripeKey");M();var Fs=m({userId:g(s(),S(1,"User ID is required")),newPriceId:g(s(),S(1,"Price ID is required")),billingConfigKey:g(s(),S(1,"Billing config key is required"))});function Us(e){return _("change-plan",Fs,async(t,r)=>{ie(Ms());let n=ne(r.supabaseAdmin);return Ki(t.userId,t.newPriceId,t.billingConfigKey,e,n)})}i(Us,"createChangePlan");function Ms(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Ms,"getStripeKey");M();var Ls=m({userId:g(s(),S(1,"User ID is required")),returnUrl:f(g(s(),z()))});function Bs(){return _("create-customer-portal",Ls,async(e,t)=>{ie(qs());let r=ne(t.supabaseAdmin);return Wi(e.userId,r,e.returnUrl)})}i(Bs,"createCustomerPortal");function qs(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(qs,"getStripeKey");M();var js=m({userId:g(s(),S(1,"User ID is required"))});function Vs(){return _("refresh-subscription-status",js,async(e,t)=>{ie($s()),Ee();let r=ne(t.supabaseAdmin),u=(await r.getUser(e.userId)).customClaims||{},o=u.subscription?.subscriptionId;if(!o)throw new Error("No active subscription found");let a=await me.subscriptions.retrieve(o),p={...u,subscription:{...u.subscription,status:a.status,currentPeriodStart:new Date(a.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(a.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:a.cancel_at_period_end}};return await r.setCustomUserClaims(e.userId,p),{success:!0,userId:e.userId,status:a.status,currentPeriodEnd:new Date(a.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:a.cancel_at_period_end}})}i(Vs,"createRefreshSubscriptionStatus");function $s(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i($s,"getStripeKey");M();H();H();import{createClient as Lg}from"@supabase/supabase-js";function _t(e){return typeof e!="string"?String(e):e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}i(_t,"camelToSnake");function zi(e){return typeof e!="string"?String(e):e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}i(zi,"snakeToCamel");var Yi=new Set(["createdAt","updatedAt"]);function Xi(e){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e))return new Date(e.replace(" ","T")).toISOString()}return e}i(Xi,"toIsoString");function Hs(){return{toBackendField:i(n=>{if(typeof n!="string")throw new TypeError(`Supabase field mapper: field name must be a string (e.g. "createdById"), got ${typeof n}. Check where query options (orderBy/where) are built \u2014 ensure "field" is the field name string, not a schema or other value.`);return _t(n)},"toBackendField"),toBackendKeys:i(n=>{let u={};for(let[o,a]of Object.entries(n))u[_t(o)]=a;return u},"toBackendKeys"),fromBackendRow:i(n=>{let u={};for(let[o,a]of Object.entries(n)){let p=zi(o);u[p]=Yi.has(p)?Xi(a):a}return u},"fromBackendRow")}}i(Hs,"createFieldMapperInternal");var J=Hs(),Gs=["id","createdAt","updatedAt","createdById","updatedById","status"];function tt(e){if(!e||typeof e!="object")return[];let t=e.entries;return!t||typeof t!="object"?[]:Object.keys(t)}i(tt,"getEntityFieldNames");function rt(e){let t=new Map;for(let r of e)t.set(_t(r),r);for(let r of Gs)t.set(_t(r),r);return{toBackendField:J.toBackendField,toBackendKeys:J.toBackendKeys,fromBackendRow:i(r=>{let n={};for(let[u,o]of Object.entries(r)){let a=t.get(u)??zi(u);n[a]=Yi.has(a)?Xi(o):o}return n},"fromBackendRow")}}i(rt,"createEntityAwareMapper");function Pt(e,t,r,n){let u=m({id:g(s(),S(1))});return _(`get_${e}`,u,async(o,a)=>{let{id:p}=o,{userRole:c,uid:y,supabaseAdmin:l}=a,{data:h,error:v}=await l.from(e).select("*").eq("id",p).single();if(v||!h)throw new w("Entity not found","not-found");if(!fe(c,"admin")&&Et.includes(h.status))throw new w("Entity not found","not-found");let R=tt(t),b=(R.length>0?rt(R):J).fromBackendRow(h),C=Pe(b,t,c,n&&y?{documentData:b,uid:y,ownership:n}:void 0);return{id:h.id,...C}},r)}i(Pt,"createSupabaseGetEntity");M();H();function Zi(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}i(Zi,"createMetadata");function Ji(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}i(Ji,"updateMetadata");var Qi={create:24,update:12,delete:1,default:24};async function nt(e,t,r){try{let n=`${r}_${t}`,{data:u,error:o}=await e.from("idempotency").select("result").eq("idempotency_key",t).eq("operation",r).gt("expires_at",new Date().toISOString()).single();return o||!u?null:u.result}catch(n){return console.error("[idempotency] Check failed:",n),null}}i(nt,"checkIdempotency");async function it(e,t,r,n,u,o){try{let a=`${r}_${t}`,p=o??Qi[r]??Qi.default,c=new Date;c.setHours(c.getHours()+p);let{error:y}=await e.from("idempotency").upsert({id:a,operation:r,idempotency_key:t,result:n,processed_by:u,expires_at:c.toISOString()},{onConflict:"idempotency_key"});y&&console.error("[idempotency] Store failed:",y)}catch(a){console.error("[idempotency] Store failed:",a)}}i(it,"storeIdempotency");async function Ks(e){try{let{data:t,error:r}=await e.from("idempotency").delete().lt("expires_at",new Date().toISOString()).select("id");return r?(console.error("[idempotency] Cleanup failed:",r),0):t?.length??0}catch(t){return console.error("[idempotency] Cleanup failed:",t),0}}i(Ks,"cleanupExpiredIdempotency");var ot=J;function Ws(e){return typeof e=="string"?e.toLowerCase():e}i(Ws,"normalizeValue");function zs(e,t){let r={...e};for(let n of t)for(let u of n.fields)typeof r[u]=="string"&&(r[u]=r[u].toLowerCase());return r}i(zs,"normalizePayloadForUniqueKeys");async function Ys(e,t,r,n,u){for(let o of r){if(n&&o.skipForDrafts===!0||!o.fields.every(l=>t[l]!=null&&t[l]!==""))continue;let p=u.from(e).select("*");for(let l of o.fields)p=p.eq(ot.toBackendField(l),Ws(t[l]));let{data:c,error:y}=await p.limit(1);if(!y&&c&&c.length>0){let l=ot.fromBackendRow(c[0]);if(o.findOrCreate)return{found:!0,existingDoc:l,findOrCreate:!0};let h=o.fields.join(" + ");throw new w(o.errorMessage||`Duplicate ${h}`,"already-exists",{details:{fields:o.fields,existingId:l.id}})}}return{found:!1}}i(Ys,"checkUniqueKeys");function Dt(e,t,r){let n=m({payload:N(s(),Y()),idempotencyKey:f(s())});return _(`create_${e}`,n,async(u,o)=>{let{payload:a,idempotencyKey:p}=u,{uid:c,userRole:y,supabaseAdmin:l}=o;if(p){let V=await nt(l,p,"create");if(V)return V}let h=a.status??ki,v=h==="draft",R=t.metadata?.uniqueKeys;if(R&&R.length>0){let V=await Ys(e,a,R,v,l);if(V.found&&V.findOrCreate)return Pe(V.existingDoc,t,y)}let I=R&&R.length>0?zs(a,R):a;v||It(I,t);let b=Zi(c),E=ot.toBackendKeys(b),{createdAt:C,updatedAt:O,created_at:Q,updated_at:A,...se}=I,ae=ot.toBackendKeys(se),{data:xe,error:X}=await l.from(e).insert({...ae,status:h,...E}).select().single();if(X)throw new w(`Failed to create entity: ${X.message}`,"internal");let G=ot.fromBackendRow(xe);return p&&await it(l,p,"create",G,c),G},r)}i(Dt,"createSupabaseCreateEntity");M();var st=J;function Xs(e){return typeof e=="string"?e.toLowerCase():e}i(Xs,"normalizeValue");async function Zs(e,t,r,n,u,o){for(let a of n){if(u&&a.skipForDrafts===!0||a.fields.filter(v=>v in r).length===0||!a.fields.every(v=>r[v]!=null&&r[v]!==""))continue;let y=o.from(e).select("*");for(let v of a.fields)y=y.eq(st.toBackendField(v),Xs(r[v]));y=y.neq("id",t);let{data:l,error:h}=await y.limit(1);if(!h&&l&&l.length>0){let v=a.fields.join(" + ");throw new w(a.errorMessage||`Duplicate ${v}`,"already-exists",{details:{fields:a.fields,existingId:l[0].id}})}}}i(Zs,"checkUniqueKeys");function Ot(e,t,r){let n=m({id:g(s(),S(1)),payload:N(s(),Y()),idempotencyKey:f(s())});return _(`update_${e}`,n,async(u,o)=>{let{id:a,payload:p,idempotencyKey:c}=u,{uid:y,supabaseAdmin:l}=o;if(c){let qe=await nt(l,c,"update");if(qe)return qe}let{data:h,error:v}=await l.from(e).select("*").eq("id",a).single();if(v||!h)throw new w("Entity not found","not-found");let x={...st.fromBackendRow(h),...p},I=(x.status??h.status)==="draft",E=t.metadata?.uniqueKeys;E&&E.length>0&&await Zs(e,a,x,E,I,l),I||It(x,t);let C=Ji(y),O=st.toBackendKeys(C),{createdAt:Q,updatedAt:A,created_at:se,updated_at:ae,id:xe,...X}=p,G=st.toBackendKeys(X),{data:V,error:ke}=await l.from(e).update({...G,...O}).eq("id",a).select().single();if(ke)throw new w(`Failed to update entity: ${ke.message}`,"internal");let ge=st.fromBackendRow(V);return c&&await it(l,c,"update",ge,y),ge},r)}i(Ot,"createSupabaseUpdateEntity");M();async function Js(e,t,r,n){let u=[];if(!n)return u;if(n.incoming)for(let o of n.incoming){let{count:a,error:p}=await e.from(o.sourceCollection).select("*",{count:"exact",head:!0}).eq(o.sourceField,r);!p&&a&&a>0&&u.push({collection:o.sourceCollection,field:o.sourceField,count:a})}return n.outgoing,u}i(Js,"findReferences");function Nt(e,t,r){let n=m({id:g(s(),S(1))});return _(`delete_${e}`,n,async(u,o)=>{let{id:a}=u,{supabaseAdmin:p}=o;r&&!r.incoming&&console.warn(`[delete_${e}] referenceMetadata provided but incoming is undefined \u2014 reference check skipped`);let y=(await Js(p,e,a,r)).filter(h=>r?.incoming?.find(x=>x.sourceCollection===h.collection&&x.sourceField===h.field)?.required===!0);if(y.length>0)throw new w("Cannot delete: item is referenced by other entities","permission-denied",{details:{references:y}});let{error:l}=await p.from(e).delete().eq("id",a);if(l)throw new w(`Failed to delete entity: ${l.message}`,"internal");return{success:!0}},t)}i(Nt,"createSupabaseDeleteEntity");M();H();var mr=J;function Se(e){return mr.toBackendField(typeof e=="string"?e:String(e))}i(Se,"toBackendColumn");function eo(e,t){let r={id:e,orderBy:t};return Buffer.from(JSON.stringify(r)).toString("base64")}i(eo,"encodeCursor");function to(e){try{let t=JSON.parse(Buffer.from(e,"base64").toString());if(!t||typeof t!="object"||typeof t.id!="string"||!t.id||typeof t.orderBy!="object"||t.orderBy===null||Array.isArray(t.orderBy))throw new w("Invalid cursor content","invalid-argument");return t}catch(t){throw t instanceof w?t:new w("Invalid cursor format","invalid-argument")}}i(to,"decodeCursor");var Qs=/^[a-zA-Z][a-zA-Z0-9_]*$/;function ro(e,t,r,n){if(!Qs.test(t))throw new w(`Invalid field name: '${t}'`,"invalid-argument");switch(r){case"==":return e.eq(t,n);case"!=":return e.neq(t,n);case">":return e.gt(t,n);case">=":return e.gte(t,n);case"<":return e.lt(t,n);case"<=":return e.lte(t,n);case"in":return e.in(t,Array.isArray(n)?n:[n]);case"not-in":return e.not(t,"in",Array.isArray(n)?n:[n]);case"array-contains":return e.contains(t,[n]);case"array-contains-any":return e.contains(t,Array.isArray(n)?n:[n]);default:return e.eq(t,n)}}i(ro,"applyOperator");function ea(e,t){let r=e;for(let n of t)r=ro(r,Se(n.field),n.op,n.value);return r}i(ea,"applyPublicCondition");function at(e,t,r,n,u,o){let a=m({where:f(D(Ie([s(),Y(),Y()]))),orderBy:f(D(Ie([g(s(),S(1)),P(["asc","desc"])]))),limit:f(g(W(),le(1))),startAfterId:f(s()),startAfterCursor:f(s()),search:f(m({field:s(),query:s()}))});return _(o?`listCard_${e}`:`list_${e}`,a,async(p,c)=>{let{where:y=[],orderBy:l=[],limit:h=1e3,startAfterId:v,startAfterCursor:x,search:R}=p,{userRole:I,uid:b,supabaseAdmin:E}=c,C=fe(I,"admin"),O=n?.filter(k=>typeof k=="string"),Q=O&&O.length>0?O.map(k=>Se(k)).join(", ")+", id, status":"*",A=E.from(e).select(Q,{count:"exact"});if(C||(A=A.not("status","in",[...Et])),u&&!C){if(o&&u.publicCondition&&u.publicCondition.length>0)A=ea(A,u.publicCondition);else if(!o&&u.ownerFields.length>0){let k=u.ownerFields[0];A=A.eq(Se(k),b)}}if(R){if(O&&O.length>0){if(!O.includes(R.field))throw new w(`Search field '${R.field}' is not allowed`,"invalid-argument")}else if(R.field.startsWith("_")||R.field.includes("."))throw new w(`Search field '${R.field}' is not allowed`,"invalid-argument");let k=R.query.replace(/%/g,"\\%").replace(/_/g,"\\_");A=A.ilike(Se(R.field),`%${k}%`)}for(let[k,L,Z]of y){if(O&&O.length>0){if(!O.includes(k)&&k!=="status"&&k!=="id")throw new w(`Where field '${k}' is not allowed`,"invalid-argument")}else if(k.startsWith("_")||k.includes("."))throw new w(`Where field '${k}' is not allowed`,"invalid-argument");A=ro(A,Se(k),L,Z)}let se=l.some(([k])=>Se(k)==="id");for(let[k,L]of l)A=A.order(Se(k),{ascending:L==="asc"});!se&&l.length>0&&(A=A.order("id",{ascending:!0}));let ae=!1;if(x){ae=!0;try{let k=to(x);if(l.length===0)A=A.gt("id",k.id);else{let L=l[0][0],Z=l[0][1],we=Se(L),ue=k.orderBy[L];Z==="asc"?A=A.gte(we,ue):A=A.lte(we,ue)}}catch{throw new w("Invalid cursor format","invalid-argument")}A=A.limit(h+1)}else if(v){let k=parseInt(v,10);if(isNaN(k))throw new w("Invalid startAfterId","invalid-argument");A=A.range(k,k+h-1)}else A=A.range(0,h-1);let{data:xe,error:X,count:G}=await A;if(X)throw new w(`Failed to list entities: ${X.message}`,"internal");let V=xe||[];if(ae&&x&&V.length>0)try{let k=to(x);V=V.filter(L=>{if(l.length===0)return L.id!==k.id;let Z=l[0][0],we=k.orderBy[Z],ue=L[mr.toBackendField(Z)];return!(L.id===k.id&&ue===we)})}catch{}let ke=i(k=>typeof k=="object"&&k!==null&&"thumbUrl"in k&&"fullUrl"in k,"isPictureObject"),ge=i(k=>{if(Array.isArray(k)&&k.length>0){let L=k[0];if(ke(L))return L.thumbUrl||L.fullUrl||null;if(typeof L=="string")return L}else if(ke(k))return k.thumbUrl||k.fullUrl||null;return k},"optimizePictureField"),qe=u&&b?{uid:b,ownership:u}:void 0,gr=tt(t),no=gr.length>0?rt(gr):mr,ct=V.map(k=>{let L=no.fromBackendRow(k),Z=Pe(L,t,I,qe?{...qe,documentData:L}:void 0);if(O&&O.length>0){let ue={id:L.id};for(let je of O)if(je in Z){let io=Z[je];ue[je]=ge(io)}return ue}let we={id:L.id};for(let[ue,je]of Object.entries(Z))we[ue]=ge(je);return we}),yr=V.length===h,lt=null;if(yr&&ct.length>0){let k=ct[ct.length-1];if(ae&&l.length>0){let L=l[0][0],Z={};Z[L]=k[L],lt=eo(k.id,Z)}else if(ae)lt=eo(k.id,{});else{let L=v?parseInt(v,10):0;lt=String(L+V.length)}}return{items:ct,lastVisible:lt,count:G??void 0,hasMore:yr}},r)}i(at,"createSupabaseListEntities");M();var ut=J;function ta(e,t,r,n){switch(r){case"==":return e.eq(t,n);case"!=":return e.neq(t,n);case">":return e.gt(t,n);case">=":return e.gte(t,n);case"<":return e.lt(t,n);case"<=":return e.lte(t,n);case"in":return e.in(t,Array.isArray(n)?n:[n]);case"not-in":return e.not(t,"in",Array.isArray(n)?n:[n]);case"array-contains":return e.contains(t,[n]);default:return e.eq(t,n)}}i(ta,"applyOperator");function Ft(e,t,r){let n=m({where:f(D(Ie([s(),Y(),Y()]))),aggregate:m({field:s(),operation:P(["count","sum","avg","min","max"])}),groupBy:f(D(s()))});return _(`aggregate_${e}`,n,async(u,o)=>{let{where:a=[],aggregate:p,groupBy:c}=u,{supabaseAdmin:y}=o,l=ut.toBackendField(p.field),h=y.from(e);for(let[I,b,E]of a)h=ta(h,ut.toBackendField(I),b,E);if(c&&c.length>0){let b=`${c.map(E=>ut.toBackendField(E)).join(", ")}, ${p.operation}(${l})`;h=h.select(b);for(let E of c)h=h.group(ut.toBackendField(E))}else p.operation==="count"?h=h.select("*",{count:"exact",head:!0}):h=h.select(l);let{data:v,error:x,count:R}=await h;if(x)throw new w(`Failed to aggregate entities: ${x.message}`,"internal");if(c&&c.length>0){let I={};for(let b of v||[]){let E=c.map(C=>b[ut.toBackendField(C)]).join("|");I[E]=b[`${p.operation}`]||0}return{value:I}}else{if(p.operation==="count")return{value:R??0};{let I=(v||[]).map(E=>E[l]).filter(E=>E!=null&&!isNaN(Number(E))).map(E=>Number(E));if(I.length===0)return{value:0};let b;switch(p.operation){case"sum":b=I.reduce((E,C)=>E+C,0);break;case"avg":b=I.reduce((E,C)=>E+C,0)/I.length;break;case"min":b=Math.min(...I);break;case"max":b=Math.max(...I);break;default:b=0}return{value:b}}}},r)}i(Ft,"createSupabaseAggregateEntities");H();function ra(e){let t={};for(let[n,u]of Object.entries(e)){if(!na(u))continue;let o=u,a=o.collection,p=Ci(o),c=o.access;t[`create_${a}`]=Dt(a,p.create,c.create),t[`get_${a}`]=Pt(a,p.get,c.read,o.ownership),t[`list_${a}`]=at(a,p.get,c.read,o.listFields,o.ownership,!1),t[`listCard_${a}`]=at(a,p.get,c.read,Ye(o),o.ownership,!0),t[`update_${a}`]=Ot(a,p.update,c.update);let l=p.get.metadata?.references;t[`delete_${a}`]=Nt(a,c.delete,l),t[`aggregate_${a}`]=Ft(a,p.get,c.read)}return{handlers:t,serve:i(async n=>{try{let u=await n.json().catch(()=>({})),o=u._functionName;if(!o)return new Response(JSON.stringify({error:"Missing _functionName in request body"}),{status:400,headers:{"Content-Type":"application/json"}});let a=t[o];if(!a)return new Response(JSON.stringify({error:`Unknown function: ${o}`}),{status:404,headers:{"Content-Type":"application/json"}});let{_functionName:p,...c}=u,y=new Request(n.url,{method:n.method,headers:n.headers,body:JSON.stringify(c)});return a(y)}catch(u){let o=u instanceof Error?u.message:"Internal server error";return new Response(JSON.stringify({error:o}),{status:500,headers:{"Content-Type":"application/json"}})}},"serve")}}i(ra,"createSupabaseCrudFunctions");function na(e){return typeof e=="object"&&e!==null&&"collection"in e&&"fields"in e}i(na,"isEntity");export{kt as DEFAULT_RATE_LIMITS,nt as checkIdempotency,dr as checkRateLimitWithPostgres,Ks as cleanupExpiredIdempotency,Os as createCancelSubscription,Us as createChangePlan,_s as createCheckoutSession,Bs as createCustomerPortal,us as createDeleteAccount,ps as createGetCustomClaims,ys as createGetUserAuthStatus,Vs as createRefreshSubscriptionStatus,ms as createRemoveCustomClaims,ls as createSetCustomClaims,Ft as createSupabaseAggregateEntities,ne as createSupabaseAuthProvider,Dt as createSupabaseCreateEntity,ra as createSupabaseCrudFunctions,Nt as createSupabaseDeleteEntity,Pt as createSupabaseGetEntity,_ as createSupabaseHandler,at as createSupabaseListEntities,Ot as createSupabaseUpdateEntity,Jo as getFailureRate,Qo as getOperationCounts,es as getSlowOperations,lr as recordOperationMetrics,it as storeIdempotency};
21
+ var os=Object.defineProperty;var i=(e,t)=>os(e,"name",{value:t,configurable:!0});var f=(e,t)=>()=>(e&&(t=e(e=0)),t);function Gt(e){return{lang:e?.lang??Ht?.lang,message:e?.message,abortEarly:e?.abortEarly??Ht?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ht?.abortPipeEarly}}function as(e){return ss?.get(e)}function cs(e){return us?.get(e)}function ps(e,t){return ls?.get(e)?.get(t)}function _e(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function B(e,t,r,n,a){let o=a&&"input"in a?a.input:r.value,s=a?.expected??e.expects??null,c=a?.received??_e(o),p={kind:e.kind,type:e.type,input:o,expected:s,received:c,message:`Invalid ${t}: ${s?`Expected ${s} but r`:"R"}eceived ${c}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},m=e.kind==="schema",l=a?.message??e.message??ps(e.reference,p.lang)??(m?cs(p.lang):null)??n.message??as(p.lang);l!==void 0&&(p.message=typeof l=="function"?l(p):l),m&&(r.typed=!1),r.issues?r.issues.push(p):r.issues=[p]}function W(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},Gt())}}}function Lr(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Kt(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function We(e,t){return{kind:"validation",type:"check",reference:We,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&B(this,"input",r,n),r}}}function se(e){return{kind:"validation",type:"email",reference:se,expects:null,async:!1,requirement:ds,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&B(this,"email",t,r),t}}}function le(e){return{kind:"validation",type:"integer",reference:le,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&B(this,"integer",t,r),t}}}function pe(e){return{kind:"validation",type:"iso_timestamp",reference:pe,async:!1,expects:null,requirement:fs,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&B(this,"timestamp",t,r),t}}}function Ye(e,t){return{kind:"validation",type:"length",reference:Ye,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length!==this.requirement&&B(this,"length",r,n,{received:`${r.value.length}`}),r}}}function De(e,t){return{kind:"validation",type:"max_length",reference:De,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length>this.requirement&&B(this,"length",r,n,{received:`${r.value.length}`}),r}}}function ye(e,t){return{kind:"validation",type:"max_value",reference:ye,async:!1,expects:`<=${e instanceof Date?e.toJSON():_e(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value<=this.requirement)&&B(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():_e(r.value)}),r}}}function S(e,t){return{kind:"validation",type:"min_length",reference:S,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&B(this,"length",r,n,{received:`${r.value.length}`}),r}}}function Y(e,t){return{kind:"validation",type:"min_value",reference:Y,async:!1,expects:`>=${e instanceof Date?e.toJSON():_e(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value>=this.requirement)&&B(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():_e(r.value)}),r}}}function vt(e,t){return{kind:"validation",type:"regex",reference:vt,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&B(this,"format",r,n),r}}}function X(e){return{kind:"validation",type:"url",reference:X,async:!1,expects:null,requirement(t){try{return new URL(t),!0}catch{return!1}},message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&B(this,"URL",t,r),t}}}function Br(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Xe(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function J(){return{kind:"schema",type:"any",reference:J,expects:"any",async:!1,get"~standard"(){return W(this)},"~run"(e){return e.typed=!0,e}}}function D(e,t){return{kind:"schema",type:"array",reference:D,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){let a=r.value;if(Array.isArray(a)){r.typed=!0,r.value=[];for(let o=0;o<a.length;o++){let s=a[o],c=this.item["~run"]({value:s},n);if(c.issues){let p={type:"array",origin:"value",input:a,key:o,value:s};for(let m of c.issues)m.path?m.path.unshift(p):m.path=[p],r.issues?.push(m);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else B(this,"type",r,n);return r}}}function V(e){return{kind:"schema",type:"boolean",reference:V,expects:"boolean",async:!1,message:e,get"~standard"(){return W(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:B(this,"type",t,r),t}}}function Wt(e,t){return{kind:"schema",type:"custom",reference:Wt,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){return this.check(r.value)?r.typed=!0:B(this,"type",r,n),r}}}function Yt(e){return{kind:"schema",type:"lazy",reference:Yt,expects:"unknown",async:!1,getter:e,get"~standard"(){return W(this)},"~run"(t,r){return this.getter(t.value)["~run"](t,r)}}}function de(e,t){return{kind:"schema",type:"literal",reference:de,expects:_e(e),async:!1,literal:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:B(this,"type",r,n),r}}}function Xt(e,t){return{kind:"schema",type:"loose_object",reference:Xt,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let o in this.entries){let s=this.entries[o];if(o in a||(s.type==="exact_optional"||s.type==="optional"||s.type==="nullish")&&s.default!==void 0){let c=o in a?a[o]:Xe(s),p=s["~run"]({value:c},n);if(p.issues){let m={type:"object",origin:"value",input:a,key:o,value:c};for(let l of p.issues)l.path?l.path.unshift(m):l.path=[m],r.issues?.push(l);if(r.issues||(r.issues=p.issues),n.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value[o]=p.value}else if(s.fallback!==void 0)r.value[o]=Br(s);else if(s.type!=="exact_optional"&&s.type!=="optional"&&s.type!=="nullish"&&(B(this,"key",r,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:a,key:o,value:a[o]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly)for(let o in a)Lr(a,o)&&!(o in this.entries)&&(r.value[o]=a[o])}else B(this,"type",r,n);return r}}}function Zt(e){return{kind:"schema",type:"never",reference:Zt,expects:"never",async:!1,message:e,get"~standard"(){return W(this)},"~run"(t,r){return B(this,"type",t,r),t}}}function Z(e,t){return{kind:"schema",type:"nullable",reference:Z,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return W(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=Xe(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function oe(e,t){return{kind:"schema",type:"nullish",reference:oe,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return W(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=Xe(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function U(e){return{kind:"schema",type:"number",reference:U,expects:"number",async:!1,message:e,get"~standard"(){return W(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:B(this,"type",t,r),t}}}function y(e,t){return{kind:"schema",type:"object",reference:y,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let o in this.entries){let s=this.entries[o];if(o in a||(s.type==="exact_optional"||s.type==="optional"||s.type==="nullish")&&s.default!==void 0){let c=o in a?a[o]:Xe(s),p=s["~run"]({value:c},n);if(p.issues){let m={type:"object",origin:"value",input:a,key:o,value:c};for(let l of p.issues)l.path?l.path.unshift(m):l.path=[m],r.issues?.push(l);if(r.issues||(r.issues=p.issues),n.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value[o]=p.value}else if(s.fallback!==void 0)r.value[o]=Br(s);else if(s.type!=="exact_optional"&&s.type!=="optional"&&s.type!=="nullish"&&(B(this,"key",r,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:a,key:o,value:a[o]}]}),n.abortEarly))break}}else B(this,"type",r,n);return r}}}function d(e,t){return{kind:"schema",type:"optional",reference:d,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return W(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Xe(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function O(e,t){return{kind:"schema",type:"picklist",reference:O,expects:Kt(e.map(_e),"|"),async:!1,options:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:B(this,"type",r,n),r}}}function N(e,t,r){return{kind:"schema",type:"record",reference:N,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return W(this)},"~run"(n,a){let o=n.value;if(o&&typeof o=="object"){n.typed=!0,n.value={};for(let s in o)if(Lr(o,s)){let c=o[s],p=this.key["~run"]({value:s},a);if(p.issues){let l={type:"object",origin:"key",input:o,key:s,value:c};for(let v of p.issues)v.path=[l],n.issues?.push(v);if(n.issues||(n.issues=p.issues),a.abortEarly){n.typed=!1;break}}let m=this.value["~run"]({value:c},a);if(m.issues){let l={type:"object",origin:"value",input:o,key:s,value:c};for(let v of m.issues)v.path?v.path.unshift(l):v.path=[l],n.issues?.push(v);if(n.issues||(n.issues=m.issues),a.abortEarly){n.typed=!1;break}}(!p.typed||!m.typed)&&(n.typed=!1),p.typed&&(n.value[p.value]=m.value)}}else B(this,"type",n,a);return n}}}function u(e){return{kind:"schema",type:"string",reference:u,expects:"string",async:!1,message:e,get"~standard"(){return W(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:B(this,"type",t,r),t}}}function Ne(e,t){return{kind:"schema",type:"tuple",reference:Ne,expects:"Array",async:!1,items:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){let a=r.value;if(Array.isArray(a)){r.typed=!0,r.value=[];for(let o=0;o<this.items.length;o++){let s=a[o],c=this.items[o]["~run"]({value:s},n);if(c.issues){let p={type:"array",origin:"value",input:a,key:o,value:s};for(let m of c.issues)m.path?m.path.unshift(p):m.path=[p],r.issues?.push(m);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value.push(c.value)}}else B(this,"type",r,n);return r}}}function Mr(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function Ze(e,t){return{kind:"schema",type:"union",reference:Ze,expects:Kt(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return W(this)},"~run"(r,n){let a,o,s;for(let c of this.options){let p=c["~run"]({value:r.value},n);if(p.typed)if(p.issues)o?o.push(p):o=[p];else{a=p;break}else s?s.push(p):s=[p]}if(a)return a;if(o){if(o.length===1)return o[0];B(this,"type",r,n,{issues:Mr(o)}),r.typed=!0}else{if(s?.length===1)return s[0];B(this,"type",r,n,{issues:Mr(s)})}return r}}}function ee(){return{kind:"schema",type:"unknown",reference:ee,expects:"unknown",async:!1,get"~standard"(){return W(this)},"~run"(e){return e.typed=!0,e}}}function Jt(e,t,r){return{kind:"schema",type:"variant",reference:Jt,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return W(this)},"~run"(n,a){let o=n.value;if(o&&typeof o=="object"){let s,c=0,p=this.key,m=[],l=i((v,E)=>{for(let k of v.options){if(k.type==="variant")l(k,new Set(E).add(k.key));else{let A=!0,C=0;for(let h of E){let b=k.entries[h];if(h in o?b["~run"]({typed:!1,value:o[h]},{abortEarly:!0}).issues:b.type!=="exact_optional"&&b.type!=="optional"&&b.type!=="nullish"){A=!1,p!==h&&(c<C||c===C&&h in o&&!(p in o))&&(c=C,p=h,m=[]),p===h&&m.push(k.entries[h].expects);break}C++}if(A){let h=k["~run"]({value:o},a);(!s||!s.typed&&h.typed)&&(s=h)}}if(s&&!s.issues)break}},"parseOptions");if(l(this,new Set([this.key])),s)return s;B(this,"type",n,a,{input:o[p],expected:Kt(m,"|"),path:[{type:"object",origin:"value",input:o,key:p,value:o[p]}]})}else B(this,"type",n,a);return n}}}function Je(e,t,r){let n=e["~run"]({value:t},Gt(r));if(n.issues)throw new zt(n.issues);return n.value}function g(...e){return{...e[0],pipe:e,get"~standard"(){return W(this)},"~run"(t,r){for(let n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}}}function he(e,t,r){let n=e["~run"]({value:t},Gt(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var Ht,ss,us,ls,zt,ds,Pu,fs,F=f(()=>{i(Gt,"getGlobalConfig");i(as,"getGlobalMessage");i(cs,"getSchemaMessage");i(ps,"getSpecificMessage");i(_e,"_stringify");i(B,"_addIssue");i(W,"_getStandardProps");i(Lr,"_isValidObjectKey");i(Kt,"_joinExpects");zt=class extends Error{static{i(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},ds=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,Pu=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u"),fs=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;i(We,"check");i(se,"email");i(le,"integer");i(pe,"isoTimestamp");i(Ye,"length");i(De,"maxLength");i(ye,"maxValue");i(S,"minLength");i(Y,"minValue");i(vt,"regex");i(X,"url");i(Br,"getFallback");i(Xe,"getDefault");i(J,"any");i(D,"array");i(V,"boolean");i(Wt,"custom");i(Yt,"lazy");i(de,"literal");i(Xt,"looseObject");i(Zt,"never");i(Z,"nullable");i(oe,"nullish");i(U,"number");i(y,"object");i(d,"optional");i(O,"picklist");i(N,"record");i(u,"string");i(Ne,"tuple");i(Mr,"_subIssues");i(Ze,"union");i(ee,"unknown");i(Jt,"variant");i(Je,"parse");i(g,"pipe");i(he,"safeParse")});var fe,bt,qr,Qt,jr,$r,er=f(()=>{"use strict";fe={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},bt={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},qr={[fe.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[fe.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[fe.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},Qt={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},jr=4,$r={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}}});function Hr(e){return he(rr,e)}var Vr,tr,ms,gs,rr,ys,Fu,Mu,Gr=f(()=>{"use strict";F();er();Vr=y({role:O([bt.USER,bt.ASSISTANT,bt.SYSTEM]),content:g(u(),S(1)),id:d(u()),createdAt:d(u())}),tr=Yt(()=>y({type:O(["string","number","boolean","array","object"]),description:d(u()),enum:d(D(u())),items:d(tr),properties:d(N(u(),tr)),required:d(D(u()))})),ms=y({description:g(u(),S(1)),parameters:y({type:de("object"),properties:N(u(),tr),required:d(D(u()))})}),gs=y({id:u(),name:u(),args:N(u(),ee())}),rr=y({messages:g(D(Vr),S(1)),provider:d(O([fe.ANTHROPIC,fe.OPENAI,fe.GOOGLE])),model:d(u()),maxTokens:d(g(U(),le(),Y(1))),temperature:d(g(U(),Y(0),ye(2))),systemPrompt:d(u()),stream:d(V()),tools:d(N(u(),ms))}),ys=y({promptTokens:U(),completionTokens:U(),totalTokens:U()}),Fu=y({message:Vr,usage:d(ys),finishReason:d(u()),toolCalls:d(D(gs))}),Mu=y({provider:O([fe.ANTHROPIC,fe.OPENAI,fe.GOOGLE]),model:d(u()),maxTokens:d(g(U(),le(),Y(1))),temperature:d(g(U(),Y(0),ye(2))),systemPrompt:d(u())});i(Hr,"validateAIChatRequest")});var Kr=f(()=>{"use strict"});var zr=f(()=>{"use strict";er();Gr();Kr()});var xe,Wr,Yr,Xr,nr=f(()=>{"use strict";xe={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},Wr={FREE:"free",PRO:"pro",PREMIUM:"premium"},Yr={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},Xr={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"}});var Qe,ir,Ku,or=f(()=>{"use strict";Qe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},ir={PAYMENT:"payment",SUBSCRIPTION:"subscription"},Ku={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});var Zr,Xu,Zu,Ju,Qu,ec,hs,vs,bs,tc,rc,nc,Jr=f(()=>{"use strict";F();or();Zr=g(y({userId:d(u()),productId:d(u()),priceId:d(u()),unitAmount:d(g(U(),le(),Y(1))),productName:d(g(u(),S(1))),currency:d(g(u(),Ye(3,"Currency must be 3-letter ISO code"))),successUrl:g(u(),X()),cancelUrl:g(u(),X()),customerEmail:d(g(u(),se())),userEmail:d(g(u(),se())),metadata:d(N(u(),u())),allowPromotionCodes:d(V()),mode:d(O([ir.PAYMENT,ir.SUBSCRIPTION]))}),We(e=>!!(e.priceId||e.unitAmount&&e.productName),"Either priceId or (unitAmount + productName) is required")),Xu=y({sessionId:u(),sessionUrl:Z(g(u(),X()))}),Zu=y({userId:u(),tier:u(),status:O(Object.values(Qe)),subscriptionId:Z(u()),customerId:u(),subscriptionEnd:Z(g(u(),pe())),cancelAtPeriodEnd:V(),updatedAt:g(u(),pe())}),Ju=y({tier:u(),subscriptionId:Z(u()),customerId:u(),status:O(Object.values(Qe)),subscriptionEnd:Z(g(u(),pe())),cancelAtPeriodEnd:V(),updatedAt:g(u(),pe()),isDefault:d(V())}),Qu=y({id:u(),type:u(),data:y({object:J()}),created:g(u(),pe())}),ec=Xt({userId:d(u()),firebaseUid:d(u()),productType:d(u())}),hs=y({type:de("StripePayment"),name:g(u(),S(1,"Product name is required")),description:d(u()),price:u(),currency:d(g(u(),Ye(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:d(g(u(),S(1,"Stripe price ID is required"))),unitAmount:d(g(U(),le(),Y(1))),productName:d(g(u(),S(1))),maxUnitAmount:d(g(U(),le(),Y(1))),tier:g(u(),S(1,"Tier is required")),duration:g(u(),S(1,"Duration is required")),allowPromotionCodes:d(V()),metadata:d(N(u(),u()))}),vs=y({type:de("StripeSubscription"),name:g(u(),S(1,"Product name is required")),description:d(u()),price:u(),currency:d(g(u(),Ye(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:g(u(),S(1,"Stripe price ID is required")),tier:g(u(),S(1,"Tier is required")),duration:O(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:d(V()),metadata:d(N(u(),u()))}),bs=Jt("type",[hs,vs]),tc=N(u(),bs),rc=N(u(),y({name:u(),price:u(),currency:u(),description:d(u()),features:d(D(u())),priceId:d(u()),unitAmount:d(U()),productName:d(u()),allowPromotionCodes:d(V())})),nc=N(u(),y({type:O(["StripePayment","StripeSubscription"]),name:u(),price:U(),currency:u(),priceId:d(u()),unitAmount:d(g(U(),le(),Y(1))),productName:d(g(u(),S(1))),maxUnitAmount:d(g(U(),le(),Y(1))),tier:u(),duration:u(),description:d(u()),metadata:d(N(u(),u())),allowPromotionCodes:d(V())}))});var Qr=f(()=>{"use strict"});var sr=f(()=>{"use strict";or();Jr();Qr()});var dc,Es,fc,en=f(()=>{"use strict";F();nr();sr();dc=y({id:u(),email:d(Z(g(u(),se()))),displayName:d(Z(u())),photoURL:d(Z(g(u(),X()))),emailVerified:d(V()),lastLoginAt:d(u()),providerData:d(D(y({providerId:u(),uid:u(),email:d(Z(g(u(),se()))),displayName:d(Z(u())),photoURL:d(Z(g(u(),X()))),phoneNumber:d(Z(u()))}))),role:d(O(Object.values(xe))),customClaims:d(N(u(),J()))}),Es=y({userId:u(),tier:O(Object.values(Wr)),status:O(Object.values(Qe)),isActive:d(V()),features:d(D(u())),subscriptionId:Z(u()),customerId:u(),subscriptionEnd:Z(g(u(),pe())),cancelAtPeriodEnd:V(),updatedAt:g(u(),pe())}),fc=y({role:d(O(Object.values(xe))),subscription:d(Es),features:d(D(O(Object.values(Yr)))),permissions:d(D(O(Object.values(Xr)))),githubAccess:d(y({username:d(u()),teamAccess:d(D(u())),repoAccess:d(D(u()))}))})});var tn=f(()=>{"use strict"});var rn=f(()=>{"use strict"});var nn=f(()=>{"use strict";nr();en();tn();rn()});var on=f(()=>{"use strict"});var sn=f(()=>{"use strict"});var Pe,Et=f(()=>{"use strict";Pe={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var Rc,an=f(()=>{"use strict";Et();Rc={EQ:Pe.EQ,NEQ:Pe.NEQ,LT:Pe.LT,LTE:Pe.LTE,GT:Pe.GT,GTE:Pe.GTE}});var un=f(()=>{"use strict"});var cn=f(()=>{"use strict"});var Oc,Dc,Nc,Uc,Fc,ln=f(()=>{"use strict";F();Et();Oc=y({collection:g(u(),S(1,"Collection name is required")),data:N(u(),ee()),idempotencyKey:d(u())}),Dc=y({collection:g(u(),S(1,"Collection name is required")),id:g(u(),S(1,"Entity ID is required"))}),Nc=y({collection:g(u(),S(1,"Collection name is required")),id:g(u(),S(1,"Entity ID is required")),data:N(u(),ee()),merge:d(V(),!1)}),Uc=y({collection:g(u(),S(1,"Collection name is required")),id:g(u(),S(1,"Entity ID is required"))}),Fc=y({collection:g(u(),S(1,"Collection name is required")),limit:d(g(U(),Y(1),ye(1e3)),1e3),offset:d(g(U(),Y(0)),0),orderBy:d(u()),orderDirection:d(O(["asc","desc"]),"desc"),where:d(D(y({field:u(),operator:O(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:ee()})))})});var pn=f(()=>{"use strict"});var dn=f(()=>{"use strict";sn();an();un();Et();cn();ln();pn()});var fn=f(()=>{"use strict"});function mn(e){return he(ar,e)}var ar,zc,gn=f(()=>{"use strict";F();ar=y({templateId:g(u(),S(1)),to:g(u(),se()),data:N(u(),ee()),locale:d(g(u(),S(2),De(5)),"fr"),from:d(u()),replyTo:d(u())}),zc=y({success:V(),messageId:d(u()),error:d(u())});i(mn,"validateSendEmailRequest")});var yn=f(()=>{"use strict"});var hn=f(()=>{"use strict";fn();gn();yn()});var et,St,ur,T,vn=f(()=>{"use strict";et={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},St={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},ur={[et.PERMISSION_DENIED]:{type:St.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[et.NOT_FOUND]:{type:St.NOT_FOUND,message:"The requested resource was not found"},[et.ALREADY_EXISTS]:{type:St.ALREADY_EXISTS,message:"The resource already exists"},[et.INVALID_ARGUMENT]:{type:St.VALIDATION_ERROR,message:"Invalid argument provided"}},T=class e extends Error{static{i(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=et.INTERNAL,n){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}}});var bn=f(()=>{"use strict";vn()});var En=f(()=>{"use strict"});var Sn=f(()=>{"use strict"});var xn=f(()=>{"use strict"});var kn=f(()=>{"use strict"});var wn=f(()=>{"use strict"});var An=f(()=>{"use strict"});var Rn=f(()=>{"use strict";Sn();xn();kn();wn();An()});var Tn=f(()=>{"use strict"});var Cn=f(()=>{"use strict";Tn()});var In=f(()=>{"use strict"});var _n=f(()=>{"use strict";In()});var Pn=f(()=>{"use strict"});var On=f(()=>{"use strict";Pn()});var Dn=f(()=>{"use strict"});var Nn=f(()=>{"use strict";Dn()});var Un=f(()=>{"use strict"});var Fn=f(()=>{"use strict"});var Mn=f(()=>{"use strict";Fn()});var Ln=f(()=>{"use strict"});var Bn=f(()=>{"use strict";Un();Mn();Ln()});var qn=f(()=>{"use strict"});var jn=f(()=>{"use strict";qn()});var $n,cr=f(()=>{"use strict";$n=["pull","push","admin","maintain","triage"]});var Vn=f(()=>{"use strict"});var lr,xs,Nl,Ul,Fl,Hn,Ml,Ll,Bl,Gn=f(()=>{"use strict";F();cr();lr=y({owner:g(u(),S(1,"Repository owner is required")),repo:g(u(),S(1,"Repository name is required"))}),xs=O([...$n]),Nl=y({userId:g(u(),S(1,"User ID is required")),githubUsername:g(u(),S(1,"GitHub username is required")),repoConfig:lr,permission:d(xs,"push"),customClaims:d(N(u(),J()))}),Ul=y({userId:g(u(),S(1,"User ID is required")),githubUsername:g(u(),S(1,"GitHub username is required")),repoConfig:lr}),Fl=y({userId:g(u(),S(1,"User ID is required")),githubUsername:g(u(),S(1,"GitHub username is required")),repoConfig:lr}),Hn=y({provider:u(),purpose:O(["authentication","api-access"]),code:g(u(),S(1,"Authorization code is required")),redirectUri:g(u(),X("Valid redirect URI is required")),codeVerifier:d(u()),state:d(u()),instance:d(g(u(),X()))}),Ml=y({provider:u(),refreshToken:g(u(),S(1,"Refresh token is required")),redirectUri:g(u(),X("Valid redirect URI is required"))}),Ll=y({provider:u()}),Bl=y({userId:g(u(),S(1,"User ID is required"))})});var Kn=f(()=>{"use strict";cr();Vn();Gn()});var zn=f(()=>{"use strict"});var Wn,ks,xt,ws,As,Rs,Ts,Ue,Kl,zl,Yn=f(()=>{"use strict";F();Wn=y({name:u(),color:u(),icon:u(),customParameters:d(N(u(),u())),button:y({backgroundColor:u(),textColor:u(),borderColor:u(),hoverBackgroundColor:u(),focusOutlineColor:u(),fontWeight:d(u(),"500"),textKey:d(u())})}),ks=y({...Wn.entries,type:O(["auth","both"]),scopes:d(D(u())),firebaseProviderId:d(u())}),xt=Ze([de(""),g(u(),X())]),ws=y({authUrl:xt,tokenUrl:xt,profileUrl:xt,revokeUrl:d(xt)}),As=y({authentication:d(D(u())),"api-access":D(u())}),Rs=d(y({pkce:d(V(),!1),codeChallengeMethod:d(O(["S256","plain"]),"S256")})),Ts=y({...Wn.entries,type:O(["oauth","both"]),scopes:As,endpoints:ws,capabilities:Rs}),Ue={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},Kl=N(u(),ks),zl=N(u(),Ts)});var Xn=f(()=>{"use strict"});var Zn=f(()=>{"use strict";zn();Yn();Xn()});var Jn=f(()=>{"use strict"});var Qn=f(()=>{"use strict"});var ei=f(()=>{"use strict";Jn();Qn()});var ti=f(()=>{"use strict"});var ri=f(()=>{"use strict";ti()});var ni=f(()=>{"use strict"});var ii=f(()=>{"use strict";ni()});var oi,ip,si=f(()=>{"use strict";oi={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},ip={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:oi.ANALYTICS},marketing:{requiresConsent:oi.MARKETING}}});var ai=f(()=>{"use strict";si()});var ui=f(()=>{"use strict"});var ci=f(()=>{"use strict"});var li=f(()=>{"use strict";ui();ci()});var ve=f(()=>{"use strict";zr();nn();sr();on();dn();hn();bn();En();Rn();Cn();_n();On();Nn();Bn();jn();Kn();Zn();ei();ri();ii();ai();li()});var tt=f(()=>{"use strict";ve()});function pi(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}var pr=f(()=>{"use strict";i(pi,"detectErrorSource")});function be(e){return(t,r)=>{if(t instanceof T)return t;if(typeof t!="object"||t===null){let c=typeof t=="string"?t:e.defaultErrorMessage;return new T(r||c,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let n;e.extractErrorCode?n=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(n=t.code);let a=e.defaultErrorCode;n&&e.errorCodeMapping&&n in e.errorCodeMapping&&(a=e.errorCodeMapping[n]);let o;e.extractErrorMessage?o=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(o=t.message),n&&e.friendlyMessageMapping&&n in e.friendlyMessageMapping&&(o=e.friendlyMessageMapping[n]),o||(o=e.defaultErrorMessage);let s;return e.processMetadata?s=e.processMetadata(t):(s={originalError:t},n&&(s.originalCode=n)),"originalError"in s||(s.originalError=t),new T(r||o,a,{details:s,source:e.errorSource})}}var kt,dr=f(()=>{"use strict";tt();i(be,"createErrorHandler");kt={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"}});function mr(e,t,r){return e instanceof T?e:(di[t]||di.unknown)(e,r)}var Fe,Cs,fr,ke,Is,_s,di,gr=f(()=>{"use strict";F();ve();tt();dr();Fe={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},Cs={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},fr={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},ke={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...kt},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...kt},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(Cs).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:i(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:i(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:kt,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:Fe.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:i(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:Fe["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:Fe.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:i(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},Is=i(e=>e instanceof zt?new T(Fe["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):be(ke.validation)(e),"handleValidationError"),_s=i(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in fr){let t=e,r=fr[t.type]||"unknown";return new T(t.message||Fe[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&ur[e.code]){let t=e,r=ur[t.code];if(r){let n=fr[r.type]||"unknown";return new T(r.message||Fe[n],n,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return be(ke.entity)(e)},"handleEntityError"),di={auth:be(ke.auth),oauth:be(ke.oauth),api:be(ke.api),firebase:be(ke.firebase),ui:be(ke.ui),validation:Is,entity:_s,unknown:be(ke.unknown)};i(mr,"mapToDoNotDevError")});function fi(e,t,r={}){let n=globalThis.Sentry;n&&n.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([o,s])=>{if(typeof s!="function"&&o!=="originalError")try{a.setExtra(o,s)}catch{a.setExtra(o,`[${typeof s}]`)}}),Object.entries(r).forEach(([o,s])=>{if(typeof s!="function")try{a.setExtra(`context.${o}`,s)}catch{a.setExtra(`context.${o}`,`[${typeof s}]`)}}),(e.details?.userId||r.userId)&&a.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),n.captureException(e)})}var yr=f(()=>{"use strict";i(fi,"captureErrorToSentry")});function Ps(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function H(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:n,context:a={},log:o=!0,reportToSentry:s=!0,showNotification:c=!1,severity:p="error"}=r,m=pi(e),l=e instanceof T?e:mr(e,m,n);if(n&&!l.userMessageProvided&&(l.message.includes("Error")||l.message.includes("Failed")||l.message.length<10?l=new T(n,l.code,{details:{...l.details,originalMessage:l.message},source:m,userMessageProvided:!0}):l=new T(l.message,l.code,{details:{...l.details,userMessage:n},source:m,userMessageProvided:!0})),o){let v=Ps()||typeof window<"u"&&window.__DNDEV_DEBUG,E={code:l.code,message:l.message,source:m};switch(p){case"warning":console.warn(`[DoNotDev] ${l.code}: ${l.message}`,v?{...E,details:l.details}:E);break;case"info":console.info(`[DoNotDev] ${l.code}: ${l.message}`,v?{...E,details:l.details}:E);break;case"success":console.log(`[DoNotDev] ${l.code}: ${l.message}`,v?{...E,details:l.details}:E);break;default:console.error(`[DoNotDev] ${l.code}: ${l.message}`,v?{...E,details:l.details,stack:l.stack}:E)}}return s&&fi(l,m,a),c&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),l}var mi=f(()=>{"use strict";tt();pr();gr();yr();i(Ps,"isDev");i(H,"handleError")});var wt=f(()=>{"use strict";tt();mi();pr();gr();yr();dr()});var gi=f(()=>{"use strict";wt()});var yi=f(()=>{"use strict";wt()});var hi=f(()=>{"use strict";gi();yi()});var vi=f(()=>{"use strict"});var bi=f(()=>{"use strict"});var Ei=f(()=>{"use strict"});var Si=f(()=>{"use strict"});var xi=f(()=>{"use strict"});var ki=f(()=>{"use strict"});var wi=f(()=>{"use strict"});var Ai=f(()=>{"use strict"});var Ri=f(()=>{"use strict"});function ae(e,t){if(!e)return!1;let r=Ti[e]??-1,n=Ti[t]??1/0;return r>=n}var Ti,hr=f(()=>{"use strict";ve();Ti={[xe.GUEST]:0,[xe.USER]:1,[xe.ADMIN]:2,[xe.SUPER]:3};i(ae,"hasRoleAccess")});var Ci=f(()=>{"use strict";ve()});function Ii(e,...t){let r=null,n=!1;return i(function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{n=!1}},"getInstance")}var vr=f(()=>{"use strict";i(Ii,"createSingleton")});var _i=f(()=>{"use strict";vr()});var Pi=f(()=>{"use strict"});function Os(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function Ds(e){if(Os(e))return e.visibility}function Ns(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?ae(t,"admin"):r==="owner"?!1:ae(t,r)}function Us(e,t,r){for(let n of r.ownerFields)if(e[n]===t)return!0;return!1}function Oi(e,t,r){let n=e;if(!n||typeof n!="object"||!n.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let a=n.entries,o=[],{documentData:s,uid:c,ownership:p}=r??{},m=p&&c!=null&&s&&Us(s,c,p);for(let[l,v]of Object.entries(a)){let E=Ds(v);if(E==="owner"){m&&o.push(l);continue}Ns(E,t)&&o.push(l)}return o}var br=f(()=>{"use strict";hr();i(Os,"hasVisibility");i(Ds,"getFieldVisibility");i(Ns,"isFieldVisible");i(Us,"isOwnerVisible");i(Oi,"getVisibleFields")});function Me(e,t,r,n){if(!e)return{};let a=n?.uid!=null&&n?.ownership!=null?{documentData:n.documentData??e,uid:n.uid,ownership:n.ownership}:void 0,o=Oi(t,r,a),s={};for(let c of o)Object.prototype.hasOwnProperty.call(e,c)&&(s[c]=e[c]);return s}var Di=f(()=>{"use strict";br();i(Me,"filterVisibleFields")});function rt(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let r=t,n=[...r.title??[],...r.subtitle??[],...r.content??[],...r.footer??[]];return[...new Set(n)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}var Ni=f(()=>{"use strict";i(rt,"getListCardFieldNames")});var Ui=f(()=>{"use strict"});var Fi=f(()=>{"use strict";Di();Ni();br();Ui()});var Mi=f(()=>{"use strict"});var Li=f(()=>{"use strict";Mi()});var Bi=f(()=>{"use strict"});function qi(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let r=new URL(t);if(Fs.has(r.protocol))return t}catch{return t}return""}var Fs,ji=f(()=>{"use strict";Fs=new Set(["http:","https:","mailto:","tel:","blob:"]);i(qi,"sanitizeHref")});var $i=f(()=>{"use strict"});var Vi=f(()=>{"use strict"});var Hi=f(()=>{"use strict";hi();vi();bi();Ei();Si();wt();xi();ki();wi();Ai();Ri();hr();Ci();_i();vr();Pi();Fi();Li();Bi();ji();$i();Vi()});var Gi=f(()=>{"use strict"});var Ki=f(()=>{"use strict"});var zi=f(()=>{"use strict"});var we=f(()=>{Hi();Gi();Ki();zi()});var Wi=f(()=>{"use strict"});var Yi=f(()=>{"use strict"});function I(e,t){eo.set(e,t)}function q(e,t){return t?e:oe(e)}function ea(){I("text",At),I("textarea",At),I("richtext",At),I("color",At),I("email",Ls),I("password",Bs),I("url",qs),I("tel",Ys),I("iban",Xs),I("number",Le),I("currency",Le),I("price",Qs),I("range",Le),I("year",Le),I("rating",Le),I("duration",Le),I("boolean",Xi),I("checkbox",Xi),I("gdprConsent",Js),I("date",Be),I("datetime-local",Be),I("time",Be),I("week",Be),I("month",Be),I("timestamp",Be),I("file",Zi),I("files",Ji),I("document",Zi),I("documents",Ji),I("image",js),I("images",$s),I("geopoint",Vs),I("address",Hs),I("map",Gs),I("array",Ks),I("select",Er),I("multiselect",zs),I("radio",Er),I("combobox",Er),I("switch",Zs),I("reference",Ws),I("hidden",Sr),I("avatar",Sr),I("badge",Sr),I("submit",Qi),I("reset",Qi)}function nt(e){if(e.validation?.schema){let n=e.validation.schema;return q(n,e.validation?.required)}let t=eo.get(e.type);if(t){let n=t(e);if(n!==null)return n}let r=ee();return q(r,e.validation?.required)}var eo,At,Ls,Bs,qs,Le,Xi,Be,to,Zi,Ji,ro,js,$s,Vs,Hs,Gs,Ks,Er,zs,Ws,Sr,Ys,Xs,Qi,Zs,Js,Qs,xr=f(()=>{"use strict";F();eo=new Map;i(I,"registerSchemaGenerator");i(q,"applyRequired");At=i(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(S(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(De(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(vt(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?g(u(),...t):u();return q(r,e.validation?.required)},"textSchema"),Ls=i(e=>{let t=g(u(),se("Invalid email address"));return q(t,e.validation?.required)},"emailSchema"),Bs=i(e=>{let t=e.validation?.minLength!==void 0?g(u(),S(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):u();return q(t,e.validation?.required)},"passwordSchema"),qs=i(e=>{let t=g(u(),X("Invalid URL"));return q(t,e.validation?.required)},"urlSchema"),Le=i(e=>{let t=[];e.validation?.min!==void 0&&t.push(Y(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(ye(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?g(U(),...t):U();return q(r,e.validation?.required)},"numberSchema"),Xi=i(e=>{let t=V();return q(t,e.validation?.required)},"booleanSchema"),Be=i(e=>{let t=g(u(),We(r=>!isNaN(new Date(r).getTime()),"Invalid date format"));return q(t,e.validation?.required)},"dateSchema"),to=y({url:u(),filename:u(),size:U(),mimeType:oe(u()),uploadedAt:oe(u())}),Zi=i(e=>{let t=Z(to);return q(t,e.validation?.required)},"fileSchema"),Ji=i(e=>{let t=D(to);return q(t,e.validation?.required)},"filesSchema"),ro=y({fullUrl:u(),thumbUrl:u()}),js=i(e=>q(ro,e.validation?.required),"pictureSchema"),$s=i(e=>{let t=D(ro);return q(t,e.validation?.required)},"picturesSchema"),Vs=i(e=>{let t=y({lat:U(),lng:U()});return q(t,e.validation?.required)},"geopointSchema"),Hs=i(e=>{let t=y({formatted_address:u(),latitude:U(),longitude:U(),street_number:oe(u()),route:oe(u()),locality:oe(u()),administrative_area_level_1:oe(u()),administrative_area_level_2:oe(u()),country:oe(u()),postal_code:oe(u())});return q(t,e.validation?.required)},"addressSchema"),Gs=i(e=>{let t=N(u(),ee());return q(t,e.validation?.required)},"mapSchema"),Ks=i(e=>{let t=D(ee());return q(t,e.validation?.required)},"arraySchema"),Er=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(o=>o.value),a=O(n);return q(a,e.validation?.required)}let r=Ze([u(),U()]);return q(r,e.validation?.required)},"selectSchema"),zs=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(o=>o.value),a=D(O(n));return q(a,e.validation?.required)}let r=D(u());return q(r,e.validation?.required)},"multiselectSchema"),Ws=i(e=>{let t=g(u(),S(1,"Invalid ID format"));return q(t,e.validation?.required)},"referenceSchema"),Sr=i(e=>{let t=u();return q(t,e.validation?.required)},"stringSchema"),Ys=i(e=>{let t=u();return q(t,e.validation?.required)},"telSchema"),Xs=i(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,n=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",a=[];if(t!==void 0&&a.push(S(t,`IBAN must be at least ${t} characters`)),r!==void 0&&a.push(De(r,`IBAN must not exceed ${r} characters`)),n){let s=typeof n=="string"?new RegExp(n):n;a.push(vt(s,"Invalid IBAN format"))}let o=a.length>0?g(u(),...a):u();return q(o,e.validation?.required)},"ibanSchema"),Qi=i(()=>Zt(),"neverSchema"),Zs=i(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let n=[t.checkedValue,t.uncheckedValue],a=O(n);return q(a,e.validation?.required)}let r=V();return q(r,e.validation?.required)},"switchSchema"),Js=i(e=>Wt(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),Qs=i(e=>{let t=y({amount:U(),currency:d(u()),vatIncluded:d(V()),discountPercent:d(g(U(),Y(0),ye(100)))});return q(t,e.validation?.required)},"priceSchema");i(ea,"registerBuiltinSchemas");ea();i(nt,"getSchemaType")});var kr=f(()=>{"use strict";we()});var wr=f(()=>{"use strict";we()});var no=f(()=>{"use strict";kr();wr()});var io=f(()=>{"use strict";Yi();xr();kr();no();wr()});var oo=f(()=>{"use strict";we()});var so,ao,Rt,Ar,Cm,Tt,Ct=f(()=>{"use strict";ve();so=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],ao="available",Rt=["draft","deleted"],Ar=["id","createdAt","updatedAt","createdById","updatedById"],Cm=[...Ar,"status"],Tt={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...so]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}}});var uo=f(()=>{"use strict";ve();we();Ct()});function Rr(e,t){return!!(t.visibility==="hidden"||t.editable==="generated"||Ar.includes(e))}function it(e,t){return Object.assign(e,{visibility:t})}function Oe(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},r}function co(e){let t=nt(e);return it(t,e.visibility)}function lo(e){let t=nt({...e,validation:{...e.validation,required:!1}});return it(t,e.visibility)}function po(e){let t=e.fields,r={};for(let[h,b]of Object.entries(t))b.visibility!=="hidden"&&(r[h]=co(b));let n=Oe(y(r),e),a={};for(let[h,b]of Object.entries(t))Rr(h,b)||(a[h]=co(b));let o=Oe(y(a),e),s={};for(let[h,b]of Object.entries(t))if(!Rr(h,b))if(h==="status"){let w=de("draft");s[h]=it(w,b.visibility)}else s[h]=lo(b);let c=Oe(y(s),e),p={};for(let[h,b]of Object.entries(t))Rr(h,b)||(p[h]=lo(b));p.id=it(nt(Tt.id),"technical");let m=Oe(y(p),e),l;if(e.listFields&&e.listFields.length>0){let h=["id","status"],b=[...new Set([...h,...e.listFields])];l={};for(let w of b){let x=r[w];x&&(l[w]=x)}}else l=r;let v=Oe(y(l),e),E,k=rt(e);if(k.length>0){let h=["id","status"],b=[...new Set([...h,...k])];E={};for(let w of b){let x=r[w];x&&(E[w]=x)}}else E=r;let A=Oe(y(E),e),C=Oe(y({id:it(nt(Tt.id),"technical")}),e);return{create:o,draft:c,update:m,get:n,list:v,listCard:A,delete:C}}var fo=f(()=>{"use strict";F();ve();we();xr();Ct();i(Rr,"isWriteExcluded");i(it,"withVisibility");i(Oe,"withMetadata");i(co,"createFieldSchema");i(lo,"createOptionalFieldSchema");i(po,"createSchemas")});var mo=f(()=>{"use strict"});var go=f(()=>{"use strict"});var yo=f(()=>{"use strict";io();oo();Ct();uo();fo();mo();go()});var ho=f(()=>{"use strict";Wi();yo()});var L=f(()=>{we();ve();ho();we()});import{initializeApp as Ao,getApps as xa,cert as ka}from"firebase-admin/app";import{getAuth as wa}from"firebase-admin/auth";import{getFirestore as Aa}from"firebase-admin/firestore";import{getFunctions as Ra}from"firebase-admin/functions";function Ta(){let e=xa(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=Ao({credential:ka({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
22
+ `)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=Ao():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:wa(t),firestore:Aa(t),functions:Ra(t)}}async function To(){let e=Ro();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function _r(){let e=Ro();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}var Ro,_t=f(()=>{"use strict";L();i(Ta,"initializeFirebaseAdminServices");Ro=Ii(Ta);i(To,"getFirebaseAdminApp");i(_r,"getFirebaseAdminFirestore")});var Co=f(()=>{"use strict";L();_t()});var Pt,Jg,je,Qg,st=f(()=>{"use strict";L();_t();Pt={async getServerAdmin(){try{return To()}catch(e){throw H(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return _r()}catch(e){throw H(e,"Error getting Admin Firestore")}},async generateServerId(){return(await Pt.getServerFirestore()).collection("_").doc().id}},Jg=Pt.getServerAdmin,je=Pt.getServerFirestore,Qg=Pt.generateServerId});function _a(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw H(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw H(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw H(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw H(t,"Failed to convert to ISO string")}}function Pa(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function $e(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,n=r.data();return{id:r.id,...$e(n)}}if(Array.isArray(e))return e.map(r=>$e(r));if(Pa(e))return _a(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,a]of Object.entries(e))r[n]=$e(a);return r}return e}function at(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>at(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[n,a]of Object.entries(e))t.includes(n)||a!==void 0&&(r[n]=at(a,t));return r}return e}var Ot=f(()=>{"use strict";L();i(_a,"firestoreToISOString");i(Pa,"isTimestamp");i($e,"transformFirestoreData");i(at,"prepareForFirestore")});var Ve,me,He,ay,uy,cy,ly,py,dy,Io=f(()=>{"use strict";F();L();st();Ot();Ve=typeof window<"u",me={async batchWrite(e,t,r,n,a={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:o="id",generateIds:s=!0,maxBatchSize:c=450,removeFields:p=[],validate:m=!!n}=a,l={successes:0,failures:0,failedItems:[]};try{let v=[],E=await je(),k=E.batch(),A=0;for(let h=0;h<t.length;h++){let b=t[h];if(!b){l.failures++,l.failedItems?.push({index:h,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!b[o])throw H(new Error(`Missing ID for delete operation (${o})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:o,operation:r}});let w=E.collection(e).doc(b[o]);k.delete(w)}else{if(m&&n)try{Je(n,b)}catch(te){throw H(te,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:o,itemId:b[o]}})}let w=b[o];if(!w&&r==="create"&&s)w=E.collection(e).doc().id,b={...b,[o]:w};else if(!w)throw H(new Error(`Missing ID for ${r} operation (${o})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:o,operation:r}});let x=[o,...p],j=at(b,x),P=E.collection(e).doc(w);r==="create"?k.create(P,j):r==="update"&&k.update(P,j)}A++,A>=c&&(v.push({batch:k,size:A}),k=E.batch(),A=0)}catch(w){l.failures++,l.failedItems?.push({index:h,error:w instanceof Error?w:new Error(String(w))})}}A>0&&v.push({batch:k,size:A});let C=0;for(let{batch:h,size:b}of v){try{await h.commit(),l.successes+=b}catch(w){let x=w instanceof Error?w:new Error(String(w));for(let j=C;j<C+b;j++)l.failures++,l.failedItems?.push({index:j,error:x})}C+=b}return l}catch(v){throw H(v,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:l.successes+l.failures,successCount:l.successes,failureCount:l.failures}})}},async batchCreate(e,t,r,n={}){return me.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return me.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let n=r.idField||"id",a=t.map(o=>({[n]:o}));return me.batchWrite(e,a,"delete",void 0,r)}return me.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await je()).runTransaction(e)}catch(t){throw H(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:a=!0}=r;try{let o=[];for(let p=0;p<t.length;p+=n)o.push(t.slice(p,p+n));let s=o.map(async p=>{let v=await(await je()).collection(e).where("__name__","in",p).get(),E=new Map;return v.forEach(k=>{E.set(k.id,k.data())}),p.map(k=>{let A=E.get(k);return A?a?$e({id:k,...A}):{id:k,...A}:null})});return(await Promise.all(s)).flat()}catch(o){throw H(o,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},He=i(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),ay=Ve?He("batchWrite"):me.batchWrite,uy=Ve?He("batchCreate"):me.batchCreate,cy=Ve?He("batchUpdate"):me.batchUpdate,ly=Ve?He("batchDelete"):me.batchDelete,py=Ve?He("runTransaction"):me.runTransaction,dy=Ve?He("bulkGet"):me.bulkGet});var _o=f(()=>{"use strict";L()});var Po=f(()=>{"use strict";L();st();Ot();_o()});var Dt=f(()=>{"use strict";L();st()});var Oo=f(()=>{"use strict";L();Dt();Dt()});import{FieldValue as Xy,Query as Zy,Timestamp as Jy}from"firebase-admin/firestore";var Do=f(()=>{"use strict";Co();_t();st();Io();Po();Oo();Dt();Ot()});F();L();import{createClient as ia}from"@supabase/supabase-js";async function Tr(e,t){try{let{error:r}=await e.from("operation_metrics").insert({operation:t.operation,user_id:t.userId||null,status:t.status,duration_ms:t.durationMs||null,metadata:t.metadata||null,error_code:t.errorCode||null,error_message:t.errorMessage||null});r&&console.error("[monitoring] Record failed:",r)}catch(r){console.error("[monitoring] Record failed:",r)}}i(Tr,"recordOperationMetrics");async function ta(e,t,r=24){try{let n=new Date;n.setHours(n.getHours()-r);let{data:a,error:o}=await e.from("operation_metrics").select("status").eq("operation",t).gte("timestamp",n.toISOString());return o||!a||a.length===0?0:a.filter(c=>c.status==="failed").length/a.length*100}catch(n){return console.error("[monitoring] Get failure rate failed:",n),0}}i(ta,"getFailureRate");async function ra(e,t,r=24){try{let n=new Date;n.setHours(n.getHours()-r);let{data:a,error:o}=await e.from("operation_metrics").select("operation").eq("user_id",t).gte("timestamp",n.toISOString());if(o||!a)return{};let s={};for(let c of a)s[c.operation]=(s[c.operation]||0)+1;return s}catch(n){return console.error("[monitoring] Get operation counts failed:",n),{}}}i(ra,"getOperationCounts");async function na(e,t,r=24){try{let n=new Date;n.setHours(n.getHours()-r);let{data:a,error:o}=await e.from("operation_metrics").select("operation, duration_ms").gte("timestamp",n.toISOString()).not("duration_ms","is",null);if(o||!a)return[];let s={};for(let p of a)p.duration_ms&&(s[p.operation]||(s[p.operation]={sum:0,count:0}),s[p.operation].sum+=p.duration_ms,s[p.operation].count+=1);let c=[];for(let[p,m]of Object.entries(s)){let l=m.sum/m.count;l>=t&&c.push({operation:p,avgDuration:Math.round(l),count:m.count})}return c.sort((p,m)=>m.avgDuration-p.avgDuration)}catch(n){return console.error("[monitoring] Get slow operations failed:",n),[]}}i(na,"getSlowOperations");var It={api:{maxAttempts:100,windowMs:6e4,blockDurationMs:3e5},create:{maxAttempts:20,windowMs:6e4,blockDurationMs:3e5},update:{maxAttempts:30,windowMs:6e4,blockDurationMs:3e5},delete:{maxAttempts:10,windowMs:6e4,blockDurationMs:6e5},read:{maxAttempts:200,windowMs:6e4,blockDurationMs:3e5}};async function Cr(e,t,r){let n=Date.now(),a=i(()=>({allowed:!1,remaining:0,resetAt:new Date(n+r.windowMs),blockRemainingSeconds:Math.ceil(r.windowMs/1e3)}),"failClosed");try{let{data:o,error:s}=await e.rpc("rate_limit_check",{p_key:t,p_max_attempts:r.maxAttempts,p_window_ms:r.windowMs,p_block_duration_ms:r.blockDurationMs});if(s)return s.code==="42883"||s.message?.includes("function")&&s.message?.includes("does not exist")?console.error("[rateLimit] rate_limit_check function not found. Deploy the required SQL migration (see RATE_LIMIT_CHECK_SQL).",s.message):console.error("[rateLimit] rate_limit_check RPC failed (network/runtime error):",s.message,s.code),a();let c=o;return{allowed:c.allowed,remaining:c.remaining,resetAt:new Date(c.reset_at_epoch_ms),blockRemainingSeconds:c.block_remaining_seconds}}catch(o){return console.error("[rateLimit] Unexpected error in checkRateLimitWithPostgres:",o),a()}}i(Cr,"checkRateLimitWithPostgres");function _(e,t,r,n="user",a){return async o=>{try{let s=qe("ALLOWED_ORIGIN","*"),c=i((K,z)=>vo(K,z,s),"respond");if(o.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":s,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"authorization, content-type, x-client-info, apikey"}});if(o.method!=="POST")return c({error:"Method not allowed"},405);let p=o.headers.get("authorization");if(!p?.startsWith("Bearer "))return c({error:"Missing or invalid authorization header"},401);let m=p.slice(7),l=oa("SUPABASE_URL"),v=qe("SUPABASE_SECRET_KEY")||qe("SUPABASE_SERVICE_ROLE_KEY");if(!v)throw new Error("Missing environment variable: SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY");let E=ia(l,v,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:k},error:A}=await E.auth.getUser(m);if(A||!k)return c({error:"Invalid or expired token"},401);let h=(k.app_metadata??{}).role||"user";if(n!=="guest"){if(!ae(h,n))return c({error:`Access denied. Required role: ${n}, your role: ${h}`},403)}if(!(qe("DISABLE_RATE_LIMITING")==="true")){let K=n==="guest"&&k.id==="guest"?`ip_${aa(o)}`:`uid_${k.id}`,z=`${e}_${K}`,Ce=It[e]||It.api,Se=await Cr(E,z,Ce);if(!Se.allowed)return a?.audit({type:"rate_limit.exceeded",userId:k.id,metadata:{operation:e,remaining:0}}),c({error:`Rate limit exceeded. Try again in ${Se.blockRemainingSeconds} seconds.`},429)}let w=o.headers.get("content-length"),x=1048576;if(w&&parseInt(w,10)>x)return c({error:`Request body too large. Maximum size: ${x} bytes`},413);let j=await o.json().catch(()=>({})),P=he(t,j);if(!P.success){let K=P.issues.map(z=>z.message).join(", ");return c({error:`Validation failed: ${K}`},400)}let te=qe("ENABLE_METRICS")==="true",re=te?Date.now():0,Q,G=null;try{Q=await r(P.output,{uid:k.id,userRole:h,supabaseAdmin:E})}catch(K){throw G=K instanceof Error?K:new Error(String(K)),K}finally{if(te){let K=Date.now()-re;await Tr(E,{operation:e,userId:k.id,status:G?"failed":"success",durationMs:K,metadata:{requestId:o.headers.get("x-request-id")||void 0},errorCode:G?Eo(G.message):void 0,errorMessage:G?G.message:void 0})}}if(Q instanceof Response){let K=new Headers(Q.headers);return K.set("Access-Control-Allow-Origin",s),new Response(Q.body,{status:Q.status,statusText:Q.statusText,headers:K})}return c(Q,200)}catch(s){console.error(`[${e}] Error:`,s);let c=s instanceof Error?s.message:"Internal server error",p=Eo(c),l=new Set(["rate-limit-exceeded","not-found","permission-denied","invalid-argument","already-exists"]).has(p)?c:"Internal server error",v=ua(c),E=qe("ALLOWED_ORIGIN","*");return vo({error:l},v,E)}}}i(_,"createSupabaseHandler");function vo(e,t,r="*"){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":r}})}i(vo,"jsonResponse");function oa(e){let t=typeof Deno<"u"?Deno.env.get(e):process.env[e];if(!t)throw new Error(`Missing environment variable: ${e}`);return t}i(oa,"getEnvOrThrow");function qe(e,t=""){return(typeof Deno<"u"?Deno.env.get(e):process.env[e])||t}i(qe,"getEnv");var sa=/^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;function bo(e){return sa.test(e)}i(bo,"isValidIp");function aa(e){let t=e.headers.get("x-forwarded-for");if(t){let n=t.split(",").map(o=>o.trim()).filter(Boolean),a=n[n.length-1];if(a&&bo(a))return a}let r=e.headers.get("cf-connecting-ip");return r&&bo(r)?r:"unknown"}i(aa,"getClientIp");function Eo(e){return e.includes("Rate limit")?"rate-limit-exceeded":e.includes("not found")||e.includes("No active")?"not-found":e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?"permission-denied":e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?"invalid-argument":e.includes("already-exists")||e.includes("Duplicate")?"already-exists":"internal"}i(Eo,"getErrorCode");function ua(e){return e.includes("Rate limit")?429:e.includes("not found")||e.includes("No active")?404:e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?403:e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?400:500}i(ua,"getErrorStatus");import{createClient as So}from"@supabase/supabase-js";function Ir(e,t){let r=t?.requireAuth??!0,n="authorization, content-type, x-client-info, apikey",a=t?.extraHeaders?.length?`${n}, ${t.extraHeaders.join(", ")}`:n;return async o=>{let s=ot("ALLOWED_ORIGIN")||"*",c=i((b,w)=>ca(b,w,s),"respond"),p=i((b,w=200)=>c(b,w),"json"),m=i((b,w=400)=>c({error:b},w),"error");if(o.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":s,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":a}});if(o.method!=="POST")return m("Method not allowed",405);let l=ot("SUPABASE_URL"),v=ot("SUPABASE_SECRET_KEY")||ot("SUPABASE_SERVICE_ROLE_KEY");if(!l||!v)return console.error("Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY"),m("Server misconfigured",500);let E=So(l,v,{auth:{autoRefreshToken:!1,persistSession:!1}}),k=null,A=null,C=o.headers.get("authorization");if(C?.startsWith("Bearer ")){let b=C.slice(7),w=ot("SUPABASE_ANON_KEY");if(w){A=So(l,w,{global:{headers:{Authorization:`Bearer ${b}`}}});let{data:x,error:j}=await E.auth.getUser(b);!j&&x.user&&(k={id:x.user.id,email:x.user.email??void 0})}}if(r&&!k)return m("Unauthorized",401);let h={user:k,supabaseAdmin:E,userClient:A,json:p,error:m,respond:c};try{return await e(o,h)}catch(b){return console.error("Edge function error:",b),m("Internal error",500)}}}i(Ir,"createEdgeFunction");function ca(e,t,r){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":r}})}i(ca,"jsonResponse");function ot(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e)??"":typeof process<"u"?process.env[e]??"":""}i(ot,"getEnv");function ue(e){return{async getUser(t){let{data:r,error:n}=await e.auth.admin.getUserById(t);if(n)throw n;return{customClaims:r.user?.app_metadata??{}}},async setCustomUserClaims(t,r){let{error:n}=await e.auth.admin.updateUserById(t,{app_metadata:r});if(n)throw n}}}i(ue,"createSupabaseAuthProvider");F();var la=y({});function pa(){return _("delete-account",la,async(e,t)=>{let{error:r}=await t.supabaseAdmin.auth.admin.deleteUser(t.uid);if(r)throw r;return{success:!0}})}i(pa,"createDeleteAccount");F();var da=y({customClaims:N(u(),ee()),idempotencyKey:d(u())}),fa=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated","plan","tier","provider","providers","sub","iss","aud"]);function ma(e){let t=new Set(e.allowedClaimKeys);for(let r of t)if(fa.has(r))throw new Error(`Claim key "${r}" is blocked - it is a privilege-escalation vector and cannot be self-assigned.`);return _("set-custom-claims",da,async(r,n)=>{let a=Object.keys(r.customClaims).filter(l=>!t.has(l));if(a.length>0)throw new Error(`Claim keys not allowed: ${a.join(", ")}`);let{data:{user:o},error:s}=await n.supabaseAdmin.auth.admin.getUserById(n.uid);if(s||!o)throw new Error("User not found");let p={...o.app_metadata??{},...r.customClaims},{error:m}=await n.supabaseAdmin.auth.admin.updateUserById(n.uid,{app_metadata:p});if(m)throw m;return{success:!0,customClaims:p}},"user")}i(ma,"createSetCustomClaims");F();var ga=y({});function ya(){return _("get-custom-claims",ga,async(e,t)=>{let{data:{user:r},error:n}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(n||!r)throw new Error("User not found");return{customClaims:r.app_metadata??{}}},"user")}i(ya,"createGetCustomClaims");F();var ha=y({claimsToRemove:g(D(u()),S(1,"At least one claim key is required"))}),va=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated","plan","tier","provider","providers","sub","iss","aud"]);function ba(){return _("remove-custom-claims",ha,async(e,t)=>{let r=e.claimsToRemove.filter(c=>va.has(c));if(r.length>0)throw new Error(`Protected claims cannot be removed: ${r.join(", ")}`);let{data:{user:n},error:a}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(a||!n)throw new Error("User not found");let o={...n.app_metadata??{}};for(let c of e.claimsToRemove)delete o[c];let{error:s}=await t.supabaseAdmin.auth.admin.updateUserById(t.uid,{app_metadata:o});if(s)throw s;return{success:!0,customClaims:o}},"user")}i(ba,"createRemoveCustomClaims");F();var Ea=y({});function Sa(){return _("get-user-auth-status",Ea,async(e,t)=>{let{data:{user:r},error:n}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(n||!r)throw new Error("User not found");return{uid:r.id,email:r.email,emailVerified:r.email_confirmed_at!=null,customClaims:r.app_metadata??{},disabled:r.banned_until!=null}},"user")}i(Sa,"createGetUserAuthStatus");L();function xo(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(xo,"validateCheckoutUrl");function ko(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let a=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(a.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=a}return t}i(ko,"sanitizeMetadata");async function wo(e,t,r,n){if(!process.env.FRONTEND_URL)throw new Error("FRONTEND_URL environment variable is required");let{priceId:a,unitAmount:o,productName:s,currency:c,userId:p,customerEmail:m,metadata:l={},allowPromotionCodes:v=!0,successUrl:E,cancelUrl:k,mode:A="payment"}=e,C=l.billingConfigKey;if(!C)throw new Error("Missing billingConfigKey in metadata");let h=n[C];if(!h)throw new Error(`Invalid billing config key: ${C}`);let b=!a&&o&&s;if(!a&&!b)throw new Error("Either priceId or (unitAmount + productName) is required");if(b&&A==="subscription")throw new Error("Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.");if(a){if(h.priceId&&h.priceId!==a)throw new Error("Price ID mismatch with configuration")}else{if(!h.maxUnitAmount)throw new Error("Dynamic pricing requires maxUnitAmount in billing config for security");if(o>h.maxUnitAmount)throw new Error(`Unit amount ${o} exceeds maximum allowed: ${h.maxUnitAmount}`);if(o<100)throw new Error("Unit amount must be at least 100 cents (1.00)")}if(!p)throw new Error("Missing userId in request");await r.getUser(p);let w=o,x=s;if(h.beforeCheckout){let G=await h.beforeCheckout(p,{priceId:a,unitAmount:o,productName:s,currency:c,mode:A,metadata:l,allowPromotionCodes:v},ko(l));if(!G.allowed)throw new Error(G.reason||"Checkout blocked by beforeCheckout hook");G.overrides&&(G.overrides.unitAmount!==void 0&&(w=G.overrides.unitAmount),G.overrides.productName!==void 0&&(x=G.overrides.productName))}let j=!a&&w&&x;if(j&&h.maxUnitAmount&&w>h.maxUnitAmount)throw new Error(`Hook-overridden unit amount ${w} exceeds maximum allowed: ${h.maxUnitAmount}`);let P=E||`${process.env.FRONTEND_URL}/billing/success`,te=k||`${process.env.FRONTEND_URL}/billing/cancel`;xo(P,"success"),xo(te,"cancel");let re=ko(l),Q=await t.createCheckoutSession({priceId:a,unitAmount:j?w:void 0,productName:j?x:void 0,currency:c||h.currency||"eur",customerEmail:m,metadata:{...re,userId:p,billingConfigKey:C},allowPromotionCodes:v,successUrl:P,cancelUrl:te,mode:A});return{sessionId:Q.id,sessionUrl:Q.url}}i(wo,"createCheckoutAlgorithm");F();L();Do();import Da from"stripe";var Nt=null;function ce(e){if(!e)throw new Error("Stripe API key is required");let t=process.env.STRIPE_API_VERSION||"2024-12-18.acacia";return Nt=new Da(e,{apiVersion:t}),Nt}i(ce,"initStripe");function Na(){if(!Nt){let e=process.env.STRIPE_SECRET_KEY;if(e)ce(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return Nt}i(Na,"getStripe");var Ee=new Proxy({},{get(e,t){return Na()[t]}});function Ae(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}i(Ae,"validateStripeEnvironment");function Ut(e,t){if(!e||typeof e!="object")throw new Error("Invalid document data");if(Array.isArray(e))throw new Error("Document data cannot be an array");if(t)try{Je(t,e)}catch(r){if(r?.issues){let n=r.issues.map(a=>`${a.path?.map(o=>o.key).join(".")||"root"}: ${a.message}`).join("; ");throw new T(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:r.issues}})}throw r}}i(Ut,"validateDocument");function Ua(e){return _("create-checkout-session",Zr,async(t,r)=>{ce(Fa()),Ae();let n=ue(r.supabaseAdmin);return wo(t,{async createCheckoutSession(o){let s=await Ee.checkout.sessions.create({mode:o.mode||"payment",line_items:[o.priceId?{price:o.priceId,quantity:1}:{price_data:{currency:o.currency||"eur",unit_amount:o.unitAmount,product_data:{name:o.productName}},quantity:1}],customer_email:o.customerEmail||void 0,success_url:o.successUrl,cancel_url:o.cancelUrl,allow_promotion_codes:o.allowPromotionCodes,metadata:o.metadata,...o.mode==="subscription"&&{subscription_data:{metadata:o.metadata}}});return{id:s.id,url:s.url}}},n,e)})}i(Ua,"createCheckoutSession");function Fa(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Fa,"getStripeKey");F();L();async function Pr(e,t,r){let a=(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 o={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},s={...a,subscription:o};await r.setCustomUserClaims(e,s)}i(Pr,"updateUserSubscription");L();function Ge(e){let t,r,n;if(e instanceof T)t=e.code,r=e.message,n=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",n={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let a=e;switch(a.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=a.message,n=void 0}else t="internal",r="An unexpected error occurred",n=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new T(r,t,n?{details:n}:void 0)}i(Ge,"handleError");async function No(e,t){Ae();let a=((await t.getUser(e)).customClaims||{}).subscription,o=a?.subscriptionId;if(!o)throw Ge(new Error("No active subscription found"));let s=await Ee.subscriptions.update(o,{cancel_at_period_end:!0}),p=["active","canceled","past_due","trialing","incomplete"].includes(s.status)?s.status:"incomplete";return await Pr(e,{tier:a?.tier||"free",status:p,subscriptionEnd:new Date(s.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:s.id,customerId:s.customer},t),{success:!0,endsAt:new Date(s.current_period_end*1e3).toISOString()}}i(No,"cancelUserSubscription");async function Uo(e,t,r,n,a){Ae();let o=n[r];if(!o||o.type!=="StripeSubscription")throw Ge(new Error("Invalid plan"));if(o.priceId!==t)throw Ge(new Error("Price ID mismatch with configuration"));let m=((await a.getUser(e)).customClaims||{}).subscription?.subscriptionId;if(!m)throw Ge(new Error("No active subscription found"));let l=await Ee.subscriptions.retrieve(m),v=await Ee.subscriptions.update(m,{items:[{id:l.items.data[0]?.id,price:t}],proration_behavior:"create_prorations"}),k=["active","canceled","past_due","trialing","incomplete"].includes(v.status)?v.status:"incomplete";return await Pr(e,{tier:o.tier,status:k,subscriptionEnd:new Date(v.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:v.cancel_at_period_end,subscriptionId:v.id,customerId:v.customer},a),{success:!0,newTier:o.tier,newPrice:o.price}}i(Uo,"changeUserPlan");async function Fo(e,t,r){Ae();let s=((await t.getUser(e)).customClaims||{}).subscription?.customerId;if(!s)throw Ge(new Error("No customer found"));if(r){let p=new URL(r),m=new URL(process.env.FRONTEND_URL||"");if(p.origin!==m.origin)throw new Error("Invalid return URL: must match frontend domain")}return{url:(await Ee.billingPortal.sessions.create({customer:s,return_url:r||`${process.env.FRONTEND_URL}/billing`})).url}}i(Fo,"createCustomerPortalSession");var Ma=y({userId:g(u(),S(1,"User ID is required"))});function La(){return _("cancel-subscription",Ma,async(e,t)=>{ce(Ba());let r=ue(t.supabaseAdmin);return No(e.userId,r)})}i(La,"createCancelSubscription");function Ba(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Ba,"getStripeKey");F();L();var qa=y({userId:g(u(),S(1,"User ID is required")),newPriceId:g(u(),S(1,"Price ID is required")),billingConfigKey:g(u(),S(1,"Billing config key is required"))});function ja(e){return _("change-plan",qa,async(t,r)=>{if(!ae(r.userRole,"admin")&&t.userId!==r.uid)throw new Error("Forbidden: cannot change another user's plan");ce($a());let n=ue(r.supabaseAdmin);return Uo(t.userId,t.newPriceId,t.billingConfigKey,e,n)})}i(ja,"createChangePlan");function $a(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i($a,"getStripeKey");F();var Va=y({userId:g(u(),S(1,"User ID is required")),returnUrl:d(g(u(),X()))});function Ha(){return _("create-customer-portal",Va,async(e,t)=>{ce(Ga());let r=ue(t.supabaseAdmin);return Fo(e.userId,r,e.returnUrl)})}i(Ha,"createCustomerPortal");function Ga(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Ga,"getStripeKey");F();var Ka=y({userId:g(u(),S(1,"User ID is required"))});function za(){return _("refresh-subscription-status",Ka,async(e,t)=>{ce(Wa()),Ae();let r=ue(t.supabaseAdmin),a=(await r.getUser(e.userId)).customClaims||{},o=a.subscription?.subscriptionId;if(!o)throw new Error("No active subscription found");let s=await Ee.subscriptions.retrieve(o),c={...a,subscription:{...a.subscription,status:s.status,currentPeriodStart:new Date(s.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(s.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:s.cancel_at_period_end}};return await r.setCustomUserClaims(e.userId,c),{success:!0,userId:e.userId,status:s.status,currentPeriodEnd:new Date(s.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:s.cancel_at_period_end}})}i(za,"createRefreshSubscriptionStatus");function Wa(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}i(Wa,"getStripeKey");L();function Lo(e){let t={};for(let[r,n]of Object.entries(e))typeof n=="string"?t[r]=n.replace(/<[^>]*>/g,"").slice(0,1e3):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=Lo(n):t[r]=n;return t}i(Lo,"sanitizeProfileData");function Mo(e){return typeof Deno<"u"?Deno.env.get(e):process.env[e]}i(Mo,"getEnv");function Bo(){return _("exchange-token",Hn,async(e,t)=>{let{provider:r,purpose:n,code:a,redirectUri:o,codeVerifier:s}=e;if(!qi(o))throw new Error("Invalid redirect URI scheme");let c=Ue[r];if(!c?.endpoints?.tokenUrl)throw new Error(`Provider ${r} is not supported`);let p=r.toUpperCase(),m=Mo(`${p}_CLIENT_ID`),l=Mo(`${p}_CLIENT_SECRET`);if(!m||!l)throw new Error(`Provider ${r} is not configured`);let v=await fetch(c.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",client_id:m,client_secret:l,code:a,redirect_uri:o,...s?{code_verifier:s}:{}}).toString()});if(!v.ok){let h=await v.text();throw console.error(`Token exchange error for ${r}: ${v.status}`,h),new Error(`Failed to exchange code for token: ${v.status}`)}let E=await v.json(),k={accessToken:E.access_token,refreshToken:E.refresh_token||null,expiresAt:E.expires_in?Math.floor(Date.now()/1e3)+E.expires_in:null,idToken:E.id_token||null,scope:E.scope?E.scope.split(" "):[]},A=null;if(k.accessToken&&c.endpoints.profileUrl)try{let h=await fetch(c.endpoints.profileUrl,{headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"application/json"}});if(h.ok){let b=await h.json();A=Lo(b)}}catch(h){console.warn(`Failed to fetch profile for ${r}:`,h)}let{error:C}=await t.supabaseAdmin.from("oauth_connections").upsert({user_id:t.uid,provider:r,purpose:n,credentials:k,profile:A,connected:!0,updated_at:new Date().toISOString()},{onConflict:"user_id,provider,purpose"});return C&&console.error("Error saving OAuth connection:",C),{success:!0,credentials:k,profile:A}})}i(Bo,"createExchangeToken");F();L();var Ya=y({provider:u(),purpose:O(["authentication","api-access"])});function qo(){return _("disconnect",Ya,async(e,t)=>{let{provider:r,purpose:n}=e,{data:a}=await t.supabaseAdmin.from("oauth_connections").select("credentials").eq("user_id",t.uid).eq("provider",r).eq("purpose",n).single();if(a?.credentials?.accessToken){let s=Ue[r],c="revokeUrl"in s?s.revokeUrl:null;if(c)try{await fetch(c.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:a.credentials.accessToken}).toString()})}catch(p){console.warn(`Failed to revoke token for ${r}:`,p)}}let{error:o}=await t.supabaseAdmin.from("oauth_connections").delete().eq("user_id",t.uid).eq("provider",r).eq("purpose",n);if(o)throw new Error(`Failed to disconnect: ${o.message}`);return{success:!0}})}i(qo,"createDisconnect");F();L();function jo(e){return typeof Deno<"u"?Deno.env.get(e):process.env[e]}i(jo,"getEnv");var Xa=y({provider:u(),refreshToken:g(u(),S(1,"Refresh token is required")),redirectUri:g(u(),X("Valid redirect URI is required"))});function $o(){return _("refresh-token",Xa,async(e,t)=>{let{provider:r,refreshToken:n,redirectUri:a}=e,o=Ue[r];if(!o?.endpoints?.tokenUrl)throw new Error(`Provider ${r} does not support token refresh`);let s=r.toUpperCase(),c=jo(`${s}_CLIENT_ID`),p=jo(`${s}_CLIENT_SECRET`);if(!c||!p)throw new Error(`Provider ${r} is not configured`);let m=await fetch(o.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",client_id:c,client_secret:p,refresh_token:n,redirect_uri:a}).toString()});if(!m.ok){let k=await m.text();throw console.error(`Token refresh error for ${r}:`,k),new Error(`Failed to refresh token: ${m.status}`)}let l=await m.json(),v={accessToken:l.access_token,refreshToken:l.refresh_token||n,expiresAt:l.expires_in?Math.floor(Date.now()/1e3)+l.expires_in:null,scope:l.scope?l.scope.split(" "):[]},{error:E}=await t.supabaseAdmin.from("oauth_connections").update({credentials:v,updated_at:new Date().toISOString()}).eq("user_id",t.uid).eq("provider",r);return E&&console.error("Error updating OAuth connection:",E),{success:!0,credentials:v}})}i($o,"createRefreshToken");F();var Za=y({purpose:d(O(["authentication","api-access"]))});function Vo(){return _("get-connections",Za,async(e,t)=>{let r=t.supabaseAdmin.from("oauth_connections").select("*").eq("user_id",t.uid);e.purpose&&(r=r.eq("purpose",e.purpose));let{data:n,error:a}=await r;if(a)throw new Error(`Failed to get connections: ${a.message}`);return{connections:(n||[]).map(s=>{let c=s.credentials?.expiresAt?s.credentials.expiresAt<Math.floor(Date.now()/1e3):!1;return{id:s.id,userId:s.user_id,provider:s.provider,purpose:s.purpose,connected:!c,createdAt:s.created_at,updatedAt:s.updated_at,hasCredentials:!c&&!!s.credentials,profile:s.profile}})}})}i(Vo,"createGetConnections");L();L();import{streamText as Ja,generateText as Qa,tool as eu,jsonSchema as tu}from"ai";L();function Ho(e,t,r=jr){let n=$r[t];if(!n)throw new Error(`Unknown model for cost calculation: ${t}`);let a=e.promptTokens/1e6*n.promptPer1M,o=e.completionTokens/1e6*n.completionPer1M,s=a+o;return{providerCost:s,billedCost:s*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:a,completionCost:o}}}i(Ho,"calculateCost");async function ru(e,t){let n={anthropic:i(async()=>{let{createAnthropic:s}=await import("@ai-sdk/anthropic");return c=>s({apiKey:c})(t)},"anthropic"),openai:i(async()=>{let{createOpenAI:s}=await import("@ai-sdk/openai");return c=>s({apiKey:c})(t)},"openai"),google:i(async()=>{let{createGoogleGenerativeAI:s}=await import("@ai-sdk/google");return c=>s({apiKey:c})(t)},"google")}[e];if(!n)throw new Error(`Unsupported AI provider: ${e}`);let a=su(e);return(await n())(a)}i(ru,"resolveModel");var nu={maxRequests:30,windowMs:6e4},Re=null;async function iu(){if(Re)return Re;let e=Mt("UPSTASH_REDIS_REST_URL"),t=Mt("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),Re={check:i(async()=>{},"check")},Re;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:n}=await import("@upstash/redis"),a=new n({url:e,token:t}),o=new Map;return Re={check:i(async(s,c)=>{let p=`${c.maxRequests}:${c.windowMs}`,m=o.get(p);if(m||(m=new r({redis:a,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),o.set(p,m)),!(await m.limit(s)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},Re}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),Re={check:i(async()=>{},"check")},Re}}i(iu,"getRateLimiter");function ou(e,t){let r={...t,...e};if(Object.keys(r).length===0)return;let n={};for(let[a,o]of Object.entries(r))n[a]=eu({description:o.description,parameters:tu(o.parameters)});return n}i(ou,"resolveTools");async function Or(e,t,r){let n=Hr(e);if(!n.success)return Ft(`Invalid AI request: ${n.issues?.map(x=>x.message).join(", ")}`,400);let a=e.provider||t.provider||"anthropic",o=qr[a],s=e.model||t.model||o?.default||"claude-sonnet-4-20250514";if(o){let x=o.models;if(!x.includes(s))return Ft(`Model '${s}' is not allowed for provider '${a}'. Allowed: ${x.join(", ")}`,400)}try{await(await iu()).check(r.userId,t.rateLimitConfig||nu)}catch(x){return Ft(x instanceof Error?x.message:"Rate limit exceeded",429)}let c;try{c=await ru(a,s)}catch(x){return Ft(`Failed to initialize provider: ${x instanceof Error?x.message:String(x)}`,500)}let p=e.messages.filter(x=>x.role==="system").map(x=>x.content),m=e.systemPrompt||t.systemPrompt||(p.length>0?p.join(`
23
+ `):void 0),l=e.messages.filter(x=>x.role!=="system").map(x=>({role:x.role,content:x.content})),v=e.maxTokens||t.maxTokens||4096,E=e.temperature??t.temperature??.7,k=r.requestId||crypto.randomUUID(),A=ou(e.tools,t.tools),C=i(async x=>{if(!r.onCostRecord)return;let j=t.cost?.markup??4,P=Ho(x,s,j),te={userId:r.userId,model:s,provider:a,usage:x,providerCost:P.providerCost,billedCost:P.billedCost,markup:j,timestamp:new Date().toISOString(),requestId:k};r.onCostRecord(te).catch(re=>{console.error("[AI] Failed to record cost:",re)})},"recordCost");if(e.stream!==!1)return Ja({model:c,messages:l,system:m,maxTokens:v,temperature:E,tools:A,onFinish:i(async({usage:j})=>{await C({promptTokens:j.promptTokens,completionTokens:j.completionTokens,totalTokens:j.promptTokens+j.completionTokens})},"onFinish")}).toDataStreamResponse();let h=await Qa({model:c,messages:l,system:m,maxTokens:v,temperature:E,tools:A}),b={promptTokens:h.usage.promptTokens,completionTokens:h.usage.completionTokens,totalTokens:h.usage.promptTokens+h.usage.completionTokens};await C(b);let w=h.toolCalls?.map(x=>({id:x.toolCallId,name:x.toolName,args:x.args}))??[];return new Response(JSON.stringify({message:{role:"assistant",content:h.text},usage:b,finishReason:h.finishReason,toolCalls:w.length>0?w:void 0,model:s,provider:a}),{status:200,headers:{"Content-Type":"application/json"}})}i(Or,"handleAIRequest");function Ft(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}i(Ft,"jsonError");function Mt(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(Mt,"getEnv");function su(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let a=Mt(r);if(a)return a}let n=Mt("AI_API_KEY");if(!n)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return n}i(su,"getAIApiKey");L();function Go(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(Go,"getEnv");function au(e,t){if(t){let a=Go(`AI_MODEL_${t.toUpperCase()}`);if(a)return a}let r=Go(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(Qt).find(a=>a.id===e)?.defaultModel??Qt.STANDARD.defaultModel)}i(au,"resolveModelForTier");function uu(e){let t=lu(e),r=pu(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:Ko(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:Ko(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(uu,"classifyAIError");function cu(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(cu,"mapClassifiedToHTTP");function lu(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(lu,"extractStatus");function pu(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(pu,"extractMessage");function Ko(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 n=Number(r);if(!Number.isNaN(n))return n*1e3}}}}i(Ko,"extractRetryAfter");function du(e){return _("ai-chat",rr,async(t,r)=>Or(t,e,{userId:r.uid,requestId:crypto.randomUUID(),onCostRecord:i(async n=>{let{error:a}=await r.supabaseAdmin.from("ai_usage").insert({user_id:n.userId,model:n.model,provider:n.provider,prompt_tokens:n.usage.promptTokens,completion_tokens:n.usage.completionTokens,total_tokens:n.usage.totalTokens,provider_cost:n.providerCost,billed_cost:n.billedCost,markup:n.markup,request_id:n.requestId,created_at:n.timestamp});a&&console.error("[AI] Failed to record cost to Supabase:",a.message)},"onCostRecord")}))}i(du,"createAIFunction");L();L();async function Dr(e,t,r){let n=mn(e);if(!n.success)return{success:!1,error:`Invalid email request: ${n.issues?.map(m=>m.message).join(", ")}`};let a=t.templates[e.templateId];if(!a)return{success:!1,error:`Template not found: ${e.templateId}`};let o=e.locale||"fr",s=a.subject(e.data,o),c=a.html(e.data,o);return{success:!0,messageId:(await r.send({from:e.from||t.defaultFrom,to:e.to,subject:s,html:c,replyTo:e.replyTo||t.replyTo})).messageId}}i(Dr,"handleEmailRequest");var fu="https://api.resend.com/emails";function zo(e){if(!e)throw new Error("Resend API key is required");return{async send({from:t,to:r,subject:n,html:a,replyTo:o}){let s={from:t,to:r,subject:n,html:a};o&&(s.reply_to=o);let c=await fetch(fu,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!c.ok){let m=await c.text().catch(()=>"Unknown error");throw new Error(`Resend API error (${c.status}): ${m}`)}return{messageId:(await c.json()).id}}}}i(zo,"createResendProvider");function mu(e){return _("send-email",ar,async(t,r)=>{let n=gu("RESEND_API_KEY");if(!n)return new Response(JSON.stringify({success:!1,error:"Email provider not configured"}),{status:500,headers:{"Content-Type":"application/json"}});let a=zo(n),o=await Dr(t,e,a);return new Response(JSON.stringify(o),{status:o.success?200:400,headers:{"Content-Type":"application/json"}})})}i(mu,"createEmailFunction");function gu(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(gu,"getEnv");F();L();L();import{createClient as Wv}from"@supabase/supabase-js";function Lt(e){return typeof e!="string"?String(e):e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}i(Lt,"camelToSnake");function Wo(e){return typeof e!="string"?String(e):e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}i(Wo,"snakeToCamel");var Yo=new Set(["createdAt","updatedAt"]);function Xo(e){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e))return new Date(e.replace(" ","T")).toISOString()}return e}i(Xo,"toIsoString");function yu(){return{toBackendField:i(n=>{if(typeof n!="string")throw new TypeError(`Supabase field mapper: field name must be a string (e.g. "createdById"), got ${typeof n}. Check where query options (orderBy/where) are built \u2014 ensure "field" is the field name string, not a schema or other value.`);return Lt(n)},"toBackendField"),toBackendKeys:i(n=>{let a={};for(let[o,s]of Object.entries(n))a[Lt(o)]=s;return a},"toBackendKeys"),fromBackendRow:i(n=>{let a={};for(let[o,s]of Object.entries(n)){let c=Wo(o);a[c]=Yo.has(c)?Xo(s):s}return a},"fromBackendRow")}}i(yu,"createFieldMapperInternal");var ie=yu(),hu=["id","createdAt","updatedAt","createdById","updatedById","status"];function ut(e){if(!e||typeof e!="object")return[];let t=e.entries;return!t||typeof t!="object"?[]:Object.keys(t)}i(ut,"getEntityFieldNames");function ct(e){let t=new Map;for(let r of e)t.set(Lt(r),r);for(let r of hu)t.set(Lt(r),r);return{toBackendField:ie.toBackendField,toBackendKeys:ie.toBackendKeys,fromBackendRow:i(r=>{let n={};for(let[a,o]of Object.entries(r)){let s=t.get(a)??Wo(a);n[s]=Yo.has(s)?Xo(o):o}return n},"fromBackendRow")}}i(ct,"createEntityAwareMapper");function Bt(e,t,r,n){let a=y({id:g(u(),S(1))});return _(`get_${e}`,a,async(o,s)=>{let{id:c}=o,{userRole:p,uid:m,supabaseAdmin:l}=s,{data:v,error:E}=await l.from(e).select("*").eq("id",c).single();if(E||!v)throw new T("Entity not found","not-found");if(!ae(p,"admin")&&Rt.includes(v.status))throw new T("Entity not found","not-found");let A=ut(t),h=(A.length>0?ct(A):ie).fromBackendRow(v),w=Me(h,t,p,n&&m?{documentData:h,uid:m,ownership:n}:void 0);return{id:v.id,...w}},r)}i(Bt,"createSupabaseGetEntity");F();L();function Zo(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}i(Zo,"createMetadata");function Jo(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}i(Jo,"updateMetadata");var Qo={create:24,update:12,delete:1,default:24};async function lt(e,t,r){try{let n=`${r}_${t}`,{data:a,error:o}=await e.from("idempotency").select("result").eq("idempotency_key",t).eq("operation",r).gt("expires_at",new Date().toISOString()).single();return o||!a?null:a.result}catch(n){throw console.error("[idempotency] Check failed:",n),new Error("[idempotency] Unable to verify idempotency. Operation rejected to prevent potential duplicate processing.")}}i(lt,"checkIdempotency");async function pt(e,t,r,n,a,o){try{let s=`${r}_${t}`,c=o??Qo[r]??Qo.default,p=new Date;p.setHours(p.getHours()+c);let{error:m}=await e.from("idempotency").upsert({id:s,operation:r,idempotency_key:t,result:n,processed_by:a,expires_at:p.toISOString()},{onConflict:"idempotency_key"});m&&console.error("[idempotency] Store failed:",m)}catch(s){console.error("[idempotency] Store failed:",s)}}i(pt,"storeIdempotency");async function vu(e){try{let{data:t,error:r}=await e.from("idempotency").delete().lt("expires_at",new Date().toISOString()).select("id");return r?(console.error("[idempotency] Cleanup failed:",r),0):t?.length??0}catch(t){return console.error("[idempotency] Cleanup failed:",t),0}}i(vu,"cleanupExpiredIdempotency");var dt=ie;function bu(e){return typeof e=="string"?e.toLowerCase():e}i(bu,"normalizeValue");function Eu(e,t){let r={...e};for(let n of t)for(let a of n.fields)typeof r[a]=="string"&&(r[a]=r[a].toLowerCase());return r}i(Eu,"normalizePayloadForUniqueKeys");async function Su(e,t,r,n,a){for(let o of r){if(n&&o.skipForDrafts===!0||!o.fields.every(l=>t[l]!=null&&t[l]!==""))continue;let c=a.from(e).select("*");for(let l of o.fields)c=c.eq(dt.toBackendField(l),bu(t[l]));let{data:p,error:m}=await c.limit(1);if(!m&&p&&p.length>0){let l=dt.fromBackendRow(p[0]);if(o.findOrCreate)return{found:!0,existingDoc:l,findOrCreate:!0};let v=o.fields.join(" + ");throw new T(o.errorMessage||`Duplicate ${v}`,"already-exists",{details:{fields:o.fields,existingId:l.id}})}}return{found:!1}}i(Su,"checkUniqueKeys");function qt(e,t,r){let n=y({payload:N(u(),J()),idempotencyKey:d(u())});return _(`create_${e}`,n,async(a,o)=>{let{payload:s,idempotencyKey:c}=a,{uid:p,userRole:m,supabaseAdmin:l}=o;if(c){let z=await lt(l,c,"create");if(z)return z}let v=s.status??ao,E=v==="draft",A=t.metadata?.uniqueKeys;if(A&&A.length>0){let z=await Su(e,s,A,E,l);if(z.found&&z.findOrCreate)return Me(z.existingDoc,t,m)}let C=A&&A.length>0?Eu(s,A):s;E||Ut(C,t);let h=Zo(p),b=dt.toBackendKeys(h),{createdAt:w,updatedAt:x,created_at:j,updated_at:P,...te}=C,re=dt.toBackendKeys(te),{data:Q,error:G}=await l.from(e).insert({...re,status:v,...b}).select().single();if(G)throw new T(`Failed to create entity: ${G.message}`,"internal");let K=dt.fromBackendRow(Q);return c&&await pt(l,c,"create",K,p),K},r)}i(qt,"createSupabaseCreateEntity");F();var ft=ie;function xu(e){return typeof e=="string"?e.toLowerCase():e}i(xu,"normalizeValue");async function ku(e,t,r,n,a,o){for(let s of n){if(a&&s.skipForDrafts===!0||s.fields.filter(E=>E in r).length===0||!s.fields.every(E=>r[E]!=null&&r[E]!==""))continue;let m=o.from(e).select("*");for(let E of s.fields)m=m.eq(ft.toBackendField(E),xu(r[E]));m=m.neq("id",t);let{data:l,error:v}=await m.limit(1);if(!v&&l&&l.length>0){let E=s.fields.join(" + ");throw new T(s.errorMessage||`Duplicate ${E}`,"already-exists",{details:{fields:s.fields,existingId:l[0].id}})}}}i(ku,"checkUniqueKeys");function jt(e,t,r){let n=y({id:g(u(),S(1)),payload:N(u(),J()),idempotencyKey:d(u())});return _(`update_${e}`,n,async(a,o)=>{let{id:s,payload:c,idempotencyKey:p}=a,{uid:m,supabaseAdmin:l}=o;if(p){let Ke=await lt(l,p,"update");if(Ke)return Ke}let{data:v,error:E}=await l.from(e).select("*").eq("id",s).single();if(E||!v)throw new T("Entity not found","not-found");let k={...ft.fromBackendRow(v),...c},C=(k.status??v.status)==="draft",b=t.metadata?.uniqueKeys;b&&b.length>0&&await ku(e,s,k,b,C,l),C||Ut(k,t);let w=Jo(m),x=ft.toBackendKeys(w),{createdAt:j,updatedAt:P,created_at:te,updated_at:re,id:Q,...G}=c,K=ft.toBackendKeys(G),{data:z,error:Ce}=await l.from(e).update({...K,...x}).eq("id",s).select().single();if(Ce)throw new T(`Failed to update entity: ${Ce.message}`,"internal");let Se=ft.fromBackendRow(z);return p&&await pt(l,p,"update",Se,m),Se},r)}i(jt,"createSupabaseUpdateEntity");F();async function wu(e,t,r,n){let a=[];if(!n)return a;if(n.incoming)for(let o of n.incoming){let{count:s,error:c}=await e.from(o.sourceCollection).select("*",{count:"exact",head:!0}).eq(o.sourceField,r);!c&&s&&s>0&&a.push({collection:o.sourceCollection,field:o.sourceField,count:s})}return n.outgoing,a}i(wu,"findReferences");function $t(e,t,r){let n=y({id:g(u(),S(1))});return _(`delete_${e}`,n,async(a,o)=>{let{id:s}=a,{supabaseAdmin:c}=o;r&&!r.incoming&&console.warn(`[delete_${e}] referenceMetadata provided but incoming is undefined \u2014 reference check skipped`);let m=(await wu(c,e,s,r)).filter(v=>r?.incoming?.find(k=>k.sourceCollection===v.collection&&k.sourceField===v.field)?.required===!0);if(m.length>0)throw new T("Cannot delete: item is referenced by other entities","permission-denied",{details:{references:m}});let{error:l}=await c.from(e).delete().eq("id",s);if(l)throw new T(`Failed to delete entity: ${l.message}`,"internal");return{success:!0}},t)}i($t,"createSupabaseDeleteEntity");F();L();var Nr=ie;function Te(e){return Nr.toBackendField(typeof e=="string"?e:String(e))}i(Te,"toBackendColumn");function es(e,t){let r={id:e,orderBy:t};return Buffer.from(JSON.stringify(r)).toString("base64")}i(es,"encodeCursor");function ts(e){try{let t=JSON.parse(Buffer.from(e,"base64").toString());if(!t||typeof t!="object"||typeof t.id!="string"||!t.id||typeof t.orderBy!="object"||t.orderBy===null||Array.isArray(t.orderBy))throw new T("Invalid cursor content","invalid-argument");return t}catch(t){throw t instanceof T?t:new T("Invalid cursor format","invalid-argument")}}i(ts,"decodeCursor");var Au=/^[a-zA-Z][a-zA-Z0-9_]*$/;function rs(e,t,r,n){if(!Au.test(t))throw new T(`Invalid field name: '${t}'`,"invalid-argument");switch(r){case"==":return e.eq(t,n);case"!=":return e.neq(t,n);case">":return e.gt(t,n);case">=":return e.gte(t,n);case"<":return e.lt(t,n);case"<=":return e.lte(t,n);case"in":return e.in(t,Array.isArray(n)?n:[n]);case"not-in":return e.not(t,"in",Array.isArray(n)?n:[n]);case"array-contains":return e.contains(t,[n]);case"array-contains-any":return e.contains(t,Array.isArray(n)?n:[n]);default:return e.eq(t,n)}}i(rs,"applyOperator");function Ru(e,t){let r=e;for(let n of t)r=rs(r,Te(n.field),n.op,n.value);return r}i(Ru,"applyPublicCondition");function mt(e,t,r,n,a,o){let s=y({where:d(D(Ne([u(),J(),J()]))),orderBy:d(D(Ne([g(u(),S(1)),O(["asc","desc"])]))),limit:d(g(U(),Y(1))),startAfterId:d(u()),startAfterCursor:d(u()),search:d(y({field:u(),query:u()}))});return _(o?`listCard_${e}`:`list_${e}`,s,async(c,p)=>{let{where:m=[],orderBy:l=[],limit:v=1e3,startAfterId:E,startAfterCursor:k,search:A}=c,{userRole:C,uid:h,supabaseAdmin:b}=p,w=ae(C,"admin"),x=n?.filter(R=>typeof R=="string"),j=x&&x.length>0?x.map(R=>Te(R)).join(", ")+", id, status":"*",P=b.from(e).select(j,{count:"exact"});if(w||(P=P.not("status","in",[...Rt])),a&&!w){if(o&&a.publicCondition&&a.publicCondition.length>0)P=Ru(P,a.publicCondition);else if(!o&&a.ownerFields.length>0){let R=a.ownerFields[0];P=P.eq(Te(R),h)}}if(A){if(x&&x.length>0){if(!x.includes(A.field))throw new T(`Search field '${A.field}' is not allowed`,"invalid-argument")}else if(A.field.startsWith("_")||A.field.includes("."))throw new T(`Search field '${A.field}' is not allowed`,"invalid-argument");let R=A.query.replace(/%/g,"\\%").replace(/_/g,"\\_");P=P.ilike(Te(A.field),`%${R}%`)}for(let[R,$,ne]of m){if(x&&x.length>0){if(!x.includes(R)&&R!=="status"&&R!=="id")throw new T(`Where field '${R}' is not allowed`,"invalid-argument")}else if(R.startsWith("_")||R.includes("."))throw new T(`Where field '${R}' is not allowed`,"invalid-argument");P=rs(P,Te(R),$,ne)}let te=l.some(([R])=>Te(R)==="id");for(let[R,$]of l)P=P.order(Te(R),{ascending:$==="asc"});!te&&l.length>0&&(P=P.order("id",{ascending:!0}));let re=!1;if(k){re=!0;try{let R=ts(k);if(l.length===0)P=P.gt("id",R.id);else{let $=l[0][0],ne=l[0][1],Ie=Te($),ge=R.orderBy[$];ne==="asc"?P=P.gte(Ie,ge):P=P.lte(Ie,ge)}}catch{throw new T("Invalid cursor format","invalid-argument")}P=P.limit(v+1)}else if(E){let R=parseInt(E,10);if(isNaN(R))throw new T("Invalid startAfterId","invalid-argument");P=P.range(R,R+v-1)}else P=P.range(0,v-1);let{data:Q,error:G,count:K}=await P;if(G)throw new T(`Failed to list entities: ${G.message}`,"internal");let z=Q||[];if(re&&k&&z.length>0)try{let R=ts(k);z=z.filter($=>{if(l.length===0)return $.id!==R.id;let ne=l[0][0],Ie=R.orderBy[ne],ge=$[Nr.toBackendField(ne)];return!($.id===R.id&&ge===Ie)})}catch{}let Ce=i(R=>typeof R=="object"&&R!==null&&"thumbUrl"in R&&"fullUrl"in R,"isPictureObject"),Se=i(R=>{if(Array.isArray(R)&&R.length>0){let $=R[0];if(Ce($))return $.thumbUrl||$.fullUrl||null;if(typeof $=="string")return $}else if(Ce(R))return R.thumbUrl||R.fullUrl||null;return R},"optimizePictureField"),Ke=a&&h?{uid:h,ownership:a}:void 0,Ur=ut(t),ns=Ur.length>0?ct(Ur):Nr,yt=z.map(R=>{let $=ns.fromBackendRow(R),ne=Me($,t,C,Ke?{...Ke,documentData:$}:void 0);if(x&&x.length>0){let ge={id:$.id};for(let ze of x)if(ze in ne){let is=ne[ze];ge[ze]=Se(is)}return ge}let Ie={id:$.id};for(let[ge,ze]of Object.entries(ne))Ie[ge]=Se(ze);return Ie}),Fr=z.length===v,ht=null;if(Fr&&yt.length>0){let R=yt[yt.length-1];if(re&&l.length>0){let $=l[0][0],ne={};ne[$]=R[$],ht=es(R.id,ne)}else if(re)ht=es(R.id,{});else{let $=E?parseInt(E,10):0;ht=String($+z.length)}}return{items:yt,lastVisible:ht,count:K??void 0,hasMore:Fr}},r)}i(mt,"createSupabaseListEntities");F();var gt=ie;function Tu(e,t,r,n){switch(r){case"==":return e.eq(t,n);case"!=":return e.neq(t,n);case">":return e.gt(t,n);case">=":return e.gte(t,n);case"<":return e.lt(t,n);case"<=":return e.lte(t,n);case"in":return e.in(t,Array.isArray(n)?n:[n]);case"not-in":return e.not(t,"in",Array.isArray(n)?n:[n]);case"array-contains":return e.contains(t,[n]);default:return e.eq(t,n)}}i(Tu,"applyOperator");function Vt(e,t,r){let n=y({where:d(D(Ne([u(),J(),J()]))),aggregate:y({field:u(),operation:O(["count","sum","avg","min","max"])}),groupBy:d(D(u()))});return _(`aggregate_${e}`,n,async(a,o)=>{let{where:s=[],aggregate:c,groupBy:p}=a,{supabaseAdmin:m}=o,l=gt.toBackendField(c.field),v=m.from(e);for(let[C,h,b]of s)v=Tu(v,gt.toBackendField(C),h,b);if(p&&p.length>0){let h=`${p.map(b=>gt.toBackendField(b)).join(", ")}, ${c.operation}(${l})`;v=v.select(h);for(let b of p)v=v.group(gt.toBackendField(b))}else c.operation==="count"?v=v.select("*",{count:"exact",head:!0}):v=v.select(l);let{data:E,error:k,count:A}=await v;if(k)throw new T(`Failed to aggregate entities: ${k.message}`,"internal");if(p&&p.length>0){let C={};for(let h of E||[]){let b=p.map(w=>h[gt.toBackendField(w)]).join("|");C[b]=h[`${c.operation}`]||0}return{value:C}}else{if(c.operation==="count")return{value:A??0};{let C=(E||[]).map(b=>b[l]).filter(b=>b!=null&&!isNaN(Number(b))).map(b=>Number(b));if(C.length===0)return{value:0};let h;switch(c.operation){case"sum":h=C.reduce((b,w)=>b+w,0);break;case"avg":h=C.reduce((b,w)=>b+w,0)/C.length;break;case"min":h=Math.min(...C);break;case"max":h=Math.max(...C);break;default:h=0}return{value:h}}}},r)}i(Vt,"createSupabaseAggregateEntities");L();function Cu(e){let t={};for(let[n,a]of Object.entries(e)){if(!Iu(a))continue;let o=a,s=o.collection,c=po(o),p=o.access;t[`create_${s}`]=qt(s,c.create,p.create),t[`get_${s}`]=Bt(s,c.get,p.read,o.ownership),t[`list_${s}`]=mt(s,c.get,p.read,o.listFields,o.ownership,!1),t[`listCard_${s}`]=mt(s,c.get,p.read,rt(o),o.ownership,!0),t[`update_${s}`]=jt(s,c.update,p.update);let l=c.get.metadata?.references;t[`delete_${s}`]=$t(s,p.delete,l),t[`aggregate_${s}`]=Vt(s,c.get,p.read)}let r=Ir(async(n,a)=>{let o=await n.json().catch(()=>({})),s=o._functionName;if(!s)return a.error("Missing _functionName in request body",400);let c=t[s];if(!c)return a.error(`Unknown function: ${s}`,404);let{_functionName:p,...m}=o,l=new Request(n.url,{method:n.method,headers:n.headers,body:JSON.stringify(m)});return c(l)},{requireAuth:!1});return{handlers:t,serve:r}}i(Cu,"createSupabaseCrudFunctions");function Iu(e){return typeof e=="object"&&e!==null&&"collection"in e&&"fields"in e}i(Iu,"isEntity");export{It as DEFAULT_RATE_LIMITS,lt as checkIdempotency,Cr as checkRateLimitWithPostgres,uu as classifyAIError,vu as cleanupExpiredIdempotency,du as createAIFunction,La as createCancelSubscription,ja as createChangePlan,Ua as createCheckoutSession,Ha as createCustomerPortal,pa as createDeleteAccount,qo as createDisconnect,Ir as createEdgeFunction,mu as createEmailFunction,Bo as createExchangeToken,Vo as createGetConnections,ya as createGetCustomClaims,Sa as createGetUserAuthStatus,za as createRefreshSubscriptionStatus,$o as createRefreshToken,ba as createRemoveCustomClaims,ma as createSetCustomClaims,Vt as createSupabaseAggregateEntities,ue as createSupabaseAuthProvider,qt as createSupabaseCreateEntity,Cu as createSupabaseCrudFunctions,$t as createSupabaseDeleteEntity,Bt as createSupabaseGetEntity,_ as createSupabaseHandler,mt as createSupabaseListEntities,jt as createSupabaseUpdateEntity,ta as getFailureRate,ra as getOperationCounts,na as getSlowOperations,cu as mapClassifiedToHTTP,Tr as recordOperationMetrics,au as resolveModelForTier,pt as storeIdempotency};
23
24
  //# sourceMappingURL=index.js.map