@donotdev/functions 0.0.20 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/LICENSE.md +3 -3
  2. package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
  3. package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
  4. package/lib/firebase/auth/index.d.ts +1 -1
  5. package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
  6. package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
  7. package/lib/firebase/baseFunction.d.ts +1 -1
  8. package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
  9. package/lib/firebase/billing/changePlan.d.ts +1 -1
  10. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  11. package/lib/firebase/billing/index.d.ts +1 -1
  12. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
  13. package/lib/firebase/config/constants.d.ts +4 -4
  14. package/lib/firebase/config/index.d.ts +1 -1
  15. package/lib/firebase/crud/aggregate.d.ts +2 -2
  16. package/lib/firebase/crud/delete.d.ts +1 -1
  17. package/lib/firebase/crud/get.d.ts +1 -1
  18. package/lib/firebase/crud/index.d.ts +1 -1
  19. package/lib/firebase/crud/update.d.ts +1 -1
  20. package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
  21. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
  22. package/lib/firebase/helpers/index.d.ts +1 -1
  23. package/lib/firebase/index.d.ts +1 -1
  24. package/lib/firebase/index.js +3 -3
  25. package/lib/firebase/index.js.map +2 -2
  26. package/lib/firebase/oauth/disconnect.d.ts +1 -1
  27. package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
  28. package/lib/firebase/oauth/getConnections.d.ts +1 -1
  29. package/lib/firebase/oauth/githubAccess.d.ts +6 -6
  30. package/lib/firebase/oauth/index.d.ts +1 -1
  31. package/lib/firebase/oauth/refreshToken.d.ts +1 -1
  32. package/lib/firebase/scheduled/index.d.ts +1 -1
  33. package/lib/shared/billing/createCheckout.d.ts +4 -4
  34. package/lib/shared/billing/helpers/index.d.ts +1 -1
  35. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
  36. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
  37. package/lib/shared/billing/idempotency.d.ts +2 -2
  38. package/lib/shared/billing/index.d.ts +1 -1
  39. package/lib/shared/billing/webhookHandler.d.ts +1 -1
  40. package/lib/shared/errorHandling.d.ts +1 -1
  41. package/lib/shared/firebase.d.ts +7 -7
  42. package/lib/shared/github.d.ts +11 -11
  43. package/lib/shared/index.d.ts +1 -1
  44. package/lib/shared/index.js +3 -3
  45. package/lib/shared/index.js.map +2 -2
  46. package/lib/shared/logger.d.ts +6 -6
  47. package/lib/shared/metadata.d.ts +3 -3
  48. package/lib/shared/oauth/exchangeToken.d.ts +2 -2
  49. package/lib/shared/oauth/grantAccess.d.ts +2 -2
  50. package/lib/shared/oauth/index.d.ts +1 -1
  51. package/lib/shared/schema.d.ts +2 -2
  52. package/lib/shared/utils/detectFirestore.d.ts +3 -3
  53. package/lib/shared/utils/external/date.d.ts +2 -2
  54. package/lib/shared/utils/external/index.d.ts +1 -1
  55. package/lib/shared/utils/external/references.d.ts +1 -1
  56. package/lib/shared/utils/external/subscription.d.ts +5 -5
  57. package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
  58. package/lib/shared/utils/functionWrapper.d.ts +4 -4
  59. package/lib/shared/utils/index.d.ts +1 -1
  60. package/lib/shared/utils/internal/auth.d.ts +4 -4
  61. package/lib/shared/utils/internal/idempotency.d.ts +2 -2
  62. package/lib/shared/utils/internal/index.d.ts +1 -1
  63. package/lib/shared/utils/internal/monitoring.d.ts +7 -7
  64. package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
  65. package/lib/shared/utils/internal/validation.d.ts +4 -4
  66. package/lib/shared/utils/schemaValidation.d.ts +6 -6
  67. package/lib/shared/utils/validation.d.ts +9 -9
  68. package/lib/shared/utils/vercelHelpers.d.ts +2 -2
  69. package/lib/shared/utils.d.ts +19 -19
  70. package/lib/shared/validation.d.ts +2 -2
  71. package/lib/supabase/auth/deleteAccount.d.ts +1 -1
  72. package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
  73. package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
  74. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  75. package/lib/supabase/auth/setCustomClaims.d.ts +1 -1
  76. package/lib/supabase/baseFunction.d.ts +2 -2
  77. package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
  78. package/lib/supabase/billing/changePlan.d.ts +1 -1
  79. package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
  80. package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
  81. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
  82. package/lib/supabase/crud/aggregate.d.ts +1 -1
  83. package/lib/supabase/crud/create.d.ts +1 -1
  84. package/lib/supabase/crud/get.d.ts +1 -1
  85. package/lib/supabase/crud/index.d.ts +1 -1
  86. package/lib/supabase/crud/list.d.ts +1 -1
  87. package/lib/supabase/crud/update.d.ts +1 -1
  88. package/lib/supabase/helpers/authProvider.d.ts +2 -2
  89. package/lib/supabase/index.d.ts +3 -2
  90. package/lib/supabase/index.js +2 -2
  91. package/lib/supabase/index.js.map +4 -4
  92. package/lib/supabase/oauth/disconnect.d.ts +13 -0
  93. package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
  94. package/lib/supabase/oauth/getConnections.d.ts +13 -0
  95. package/lib/supabase/oauth/index.d.ts +12 -0
  96. package/lib/supabase/oauth/refreshToken.d.ts +13 -0
  97. package/lib/supabase/utils/idempotency.d.ts +1 -1
  98. package/lib/supabase/utils/monitoring.d.ts +1 -1
  99. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  100. package/lib/vercel/api/auth/index.d.ts +1 -1
  101. package/lib/vercel/api/billing/cancel.d.ts +1 -1
  102. package/lib/vercel/api/billing/change-plan.d.ts +1 -1
  103. package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
  104. package/lib/vercel/api/billing/index.d.ts +1 -1
  105. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
  106. package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
  107. package/lib/vercel/api/config/constants.d.ts +9 -9
  108. package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
  109. package/lib/vercel/api/config/index.d.ts +1 -1
  110. package/lib/vercel/api/crud/index.d.ts +1 -1
  111. package/lib/vercel/api/index.d.ts +1 -1
  112. package/lib/vercel/api/index.js +2 -2
  113. package/lib/vercel/api/index.js.map +2 -2
  114. package/lib/vercel/api/oauth/check-github-access.d.ts +1 -1
  115. package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
  116. package/lib/vercel/api/oauth/index.d.ts +1 -1
  117. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  118. package/lib/vercel/api/utils/cors.d.ts +4 -4
  119. package/lib/vercel/baseFunction.d.ts +2 -2
  120. package/package.json +4 -4
  121. package/src/firebase/auth/getCustomClaims.ts +3 -3
  122. package/src/firebase/auth/getUserAuthStatus.ts +3 -3
  123. package/src/firebase/auth/index.ts +1 -1
  124. package/src/firebase/auth/removeCustomClaims.ts +3 -3
  125. package/src/firebase/auth/setCustomClaims.ts +70 -69
  126. package/src/firebase/baseFunction.ts +2 -2
  127. package/src/firebase/billing/cancelSubscription.ts +3 -3
  128. package/src/firebase/billing/changePlan.ts +3 -3
  129. package/src/firebase/billing/createCheckoutSession.ts +1 -1
  130. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  131. package/src/firebase/billing/healthCheck.ts +1 -1
  132. package/src/firebase/billing/index.d.ts +11 -11
  133. package/src/firebase/billing/index.ts +1 -1
  134. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
  135. package/src/firebase/billing/webhookHandler.ts +1 -1
  136. package/src/firebase/config/constants.ts +4 -4
  137. package/src/firebase/config/index.ts +1 -1
  138. package/src/firebase/config/secrets.ts +1 -1
  139. package/src/firebase/crud/aggregate.ts +2 -2
  140. package/src/firebase/crud/create.ts +2 -2
  141. package/src/firebase/crud/delete.ts +3 -3
  142. package/src/firebase/crud/get.ts +1 -1
  143. package/src/firebase/crud/index.ts +1 -1
  144. package/src/firebase/crud/list.ts +1 -1
  145. package/src/firebase/crud/update.ts +2 -2
  146. package/src/firebase/helpers/githubAccessHelper.ts +4 -4
  147. package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
  148. package/src/firebase/helpers/index.ts +1 -1
  149. package/src/firebase/index.d.ts +9 -9
  150. package/src/firebase/index.ts +1 -1
  151. package/src/firebase/oauth/disconnect.ts +2 -2
  152. package/src/firebase/oauth/exchangeToken.ts +2 -2
  153. package/src/firebase/oauth/getConnections.ts +2 -2
  154. package/src/firebase/oauth/githubAccess.ts +10 -10
  155. package/src/firebase/oauth/index.ts +1 -1
  156. package/src/firebase/oauth/refreshToken.ts +2 -2
  157. package/src/firebase/registerCrudFunctions.ts +1 -1
  158. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
  159. package/src/firebase/scheduled/index.ts +1 -1
  160. package/src/shared/__tests__/auth.test.ts +46 -0
  161. package/src/shared/__tests__/errorHandling.test.ts +66 -1
  162. package/src/shared/__tests__/firebase.test.ts +293 -0
  163. package/src/shared/__tests__/internalValidation.test.ts +190 -0
  164. package/src/shared/__tests__/metadata.test.ts +66 -0
  165. package/src/shared/__tests__/schema.test.ts +219 -0
  166. package/src/shared/__tests__/schemaValidation.test.ts +72 -0
  167. package/src/shared/__tests__/subscription.test.ts +45 -0
  168. package/src/shared/__tests__/utils.test.ts +281 -0
  169. package/src/shared/__tests__/validation-env.test.ts +73 -0
  170. package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
  171. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
  172. package/src/shared/billing/createCheckout.ts +4 -4
  173. package/src/shared/billing/helpers/index.ts +1 -1
  174. package/src/shared/billing/helpers/subscriptionManagement.ts +4 -4
  175. package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
  176. package/src/shared/billing/idempotency.ts +4 -4
  177. package/src/shared/billing/index.ts +1 -1
  178. package/src/shared/billing/webhookHandler.ts +7 -7
  179. package/src/shared/errorHandling.ts +2 -2
  180. package/src/shared/firebase.ts +7 -7
  181. package/src/shared/github.ts +11 -11
  182. package/src/shared/index.d.ts +9 -9
  183. package/src/shared/index.ts +1 -1
  184. package/src/shared/logger.ts +8 -8
  185. package/src/shared/metadata.ts +3 -3
  186. package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
  187. package/src/shared/oauth/exchangeToken.ts +2 -2
  188. package/src/shared/oauth/grantAccess.ts +2 -2
  189. package/src/shared/oauth/index.ts +1 -1
  190. package/src/shared/schema.ts +4 -4
  191. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  192. package/src/shared/utils/detectFirestore.ts +3 -3
  193. package/src/shared/utils/external/date.ts +5 -5
  194. package/src/shared/utils/external/index.ts +1 -1
  195. package/src/shared/utils/external/references.ts +2 -2
  196. package/src/shared/utils/external/subscription.ts +5 -5
  197. package/src/shared/utils/firebaseHelpers.ts +3 -3
  198. package/src/shared/utils/functionWrapper.ts +4 -4
  199. package/src/shared/utils/index.ts +1 -1
  200. package/src/shared/utils/internal/auth.ts +7 -7
  201. package/src/shared/utils/internal/firebase.ts +1 -1
  202. package/src/shared/utils/internal/idempotency.ts +3 -3
  203. package/src/shared/utils/internal/index.ts +1 -1
  204. package/src/shared/utils/internal/monitoring.ts +8 -8
  205. package/src/shared/utils/internal/rateLimiter.ts +6 -6
  206. package/src/shared/utils/internal/validation.ts +5 -5
  207. package/src/shared/utils/schemaValidation.ts +6 -6
  208. package/src/shared/utils/validation.ts +10 -10
  209. package/src/shared/utils/vercelHelpers.ts +3 -3
  210. package/src/shared/utils.ts +19 -19
  211. package/src/shared/validation.ts +2 -2
  212. package/src/supabase/auth/deleteAccount.ts +2 -2
  213. package/src/supabase/auth/getCustomClaims.ts +2 -2
  214. package/src/supabase/auth/getUserAuthStatus.ts +2 -2
  215. package/src/supabase/auth/removeCustomClaims.ts +2 -2
  216. package/src/supabase/auth/setCustomClaims.ts +2 -2
  217. package/src/supabase/baseFunction.ts +3 -3
  218. package/src/supabase/billing/cancelSubscription.ts +2 -2
  219. package/src/supabase/billing/changePlan.ts +2 -2
  220. package/src/supabase/billing/createCheckoutSession.ts +2 -2
  221. package/src/supabase/billing/createCustomerPortal.ts +2 -2
  222. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
  223. package/src/supabase/crud/aggregate.ts +1 -1
  224. package/src/supabase/crud/create.ts +1 -1
  225. package/src/supabase/crud/delete.ts +1 -1
  226. package/src/supabase/crud/get.ts +1 -1
  227. package/src/supabase/crud/index.ts +1 -1
  228. package/src/supabase/crud/list.ts +1 -1
  229. package/src/supabase/crud/update.ts +1 -1
  230. package/src/supabase/helpers/authProvider.ts +2 -2
  231. package/src/supabase/index.ts +10 -2
  232. package/src/supabase/oauth/disconnect.ts +104 -0
  233. package/src/supabase/oauth/exchangeToken.ts +152 -0
  234. package/src/supabase/oauth/getConnections.ts +85 -0
  235. package/src/supabase/oauth/index.ts +15 -0
  236. package/src/supabase/oauth/refreshToken.ts +131 -0
  237. package/src/supabase/registerCrudFunctions.ts +1 -1
  238. package/src/supabase/utils/idempotency.ts +1 -1
  239. package/src/supabase/utils/monitoring.ts +1 -1
  240. package/src/supabase/utils/rateLimiter.ts +1 -1
  241. package/src/vercel/api/auth/get-custom-claims.ts +1 -1
  242. package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
  243. package/src/vercel/api/auth/index.ts +1 -1
  244. package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
  245. package/src/vercel/api/auth/set-custom-claims.ts +2 -4
  246. package/src/vercel/api/billing/cancel.ts +3 -3
  247. package/src/vercel/api/billing/change-plan.ts +3 -3
  248. package/src/vercel/api/billing/create-checkout-session.ts +3 -3
  249. package/src/vercel/api/billing/customer-portal.ts +1 -1
  250. package/src/vercel/api/billing/index.ts +1 -1
  251. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  252. package/src/vercel/api/billing/webhook-handler.ts +3 -3
  253. package/src/vercel/api/config/constants.ts +9 -9
  254. package/src/vercel/api/config/firebase-admin.ts +3 -3
  255. package/src/vercel/api/config/index.ts +1 -1
  256. package/src/vercel/api/crud/create.ts +1 -1
  257. package/src/vercel/api/crud/delete.ts +1 -1
  258. package/src/vercel/api/crud/get.ts +1 -1
  259. package/src/vercel/api/crud/index.ts +1 -1
  260. package/src/vercel/api/crud/list.ts +1 -1
  261. package/src/vercel/api/crud/update.ts +1 -1
  262. package/src/vercel/api/index.d.ts +1 -1
  263. package/src/vercel/api/index.ts +1 -1
  264. package/src/vercel/api/oauth/check-github-access.ts +3 -3
  265. package/src/vercel/api/oauth/exchange-token.ts +1 -1
  266. package/src/vercel/api/oauth/grant-github-access.ts +3 -3
  267. package/src/vercel/api/oauth/index.ts +1 -1
  268. package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
  269. package/src/vercel/api/utils/cors.ts +4 -4
  270. package/src/vercel/baseFunction.ts +2 -2
@@ -18,6 +18,6 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- var Xn=Object.defineProperty;var n=(e,t)=>Xn(e,"name",{value:t,configurable:!0});var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Z,Rt,Ct,It,ze=u(()=>{"use strict";Z={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},Rt={FREE:"free",PRO:"pro",PREMIUM:"premium"},Ct={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},It={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"}});function Ye(e){return{lang:e?.lang??Ke?.lang,message:e?.message,abortEarly:e?.abortEarly??Ke?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ke?.abortPipeEarly}}function Jn(e){return Zn?.get(e)}function ei(e){return Qn?.get(e)}function ri(e,t){return ti?.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 x(e,t,r,i,a){let s=a&&"input"in a?a.input:r.value,c=a?.expected??e.expects??null,m=a?.received??te(s),l={kind:e.kind,type:e.type,input:s,expected:c,received:m,message:`Invalid ${t}: ${c?`Expected ${c} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:i.lang,abortEarly:i.abortEarly,abortPipeEarly:i.abortPipeEarly},h=e.kind==="schema",p=a?.message??e.message??ri(e.reference,l.lang)??(h?ei(l.lang):null)??i.message??Jn(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),h&&(r.typed=!1),r.issues?r.issues.push(l):r.issues=[l]}function O(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},Ye())}}}function Dt(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Xe(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function K(e){return{kind:"validation",type:"email",reference:K,expects:null,async:!1,requirement:ni,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&x(this,"email",t,r),t}}}function $(e){return{kind:"validation",type:"iso_timestamp",reference:$,async:!1,expects:null,requirement:ii,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&x(this,"timestamp",t,r),t}}}function Pe(e,t){return{kind:"validation",type:"length",reference:Pe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length!==this.requirement&&x(this,"length",r,i,{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,i){return r.typed&&r.value.length>this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function ue(e,t){return{kind:"validation",type:"max_value",reference:ue,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!(r.value<=this.requirement)&&x(this,"value",r,i,{received:r.value instanceof Date?r.value.toJSON():te(r.value)}),r}}}function v(e,t){return{kind:"validation",type:"min_length",reference:v,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length<this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function re(e,t){return{kind:"validation",type:"min_value",reference:re,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!(r.value>=this.requirement)&&x(this,"value",r,i,{received:r.value instanceof Date?r.value.toJSON():te(r.value)}),r}}}function Oe(e,t){return{kind:"validation",type:"regex",reference:Oe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!this.requirement.test(r.value)&&x(this,"format",r,i),r}}}function F(e){return{kind:"validation",type:"url",reference:F,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)&&x(this,"URL",t,r),t}}}function Ot(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function be(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function ne(){return{kind:"schema",type:"any",reference:ne,expects:"any",async:!1,get"~standard"(){return O(this)},"~run"(e){return e.typed=!0,e}}}function R(e,t){return{kind:"schema",type:"array",reference:R,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(Array.isArray(a)){r.typed=!0,r.value=[];for(let s=0;s<a.length;s++){let c=a[s],m=this.item["~run"]({value:c},i);if(m.issues){let l={type:"array",origin:"value",input:a,key:s,value:c};for(let h of m.issues)h.path?h.path.unshift(l):h.path=[l],r.issues?.push(h);if(r.issues||(r.issues=m.issues),i.abortEarly){r.typed=!1;break}}m.typed||(r.typed=!1),r.value.push(m.value)}}else x(this,"type",r,i);return r}}}function C(e){return{kind:"schema",type:"boolean",reference:C,expects:"boolean",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:x(this,"type",t,r),t}}}function Je(e,t){return{kind:"schema",type:"custom",reference:Je,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return this.check(r.value)?r.typed=!0:x(this,"type",r,i),r}}}function ce(e,t){return{kind:"schema",type:"literal",reference:ce,expects:te(e),async:!1,literal:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===this.literal?r.typed=!0:x(this,"type",r,i),r}}}function Qe(e,t){return{kind:"schema",type:"loose_object",reference:Qe,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let s in this.entries){let c=this.entries[s];if(s in a||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){let m=s in a?a[s]:be(c),l=c["~run"]({value:m},i);if(l.issues){let h={type:"object",origin:"value",input:a,key:s,value:m};for(let p of l.issues)p.path?p.path.unshift(h):p.path=[h],r.issues?.push(p);if(r.issues||(r.issues=l.issues),i.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[s]=l.value}else if(c.fallback!==void 0)r.value[s]=Ot(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(x(this,"key",r,i,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:a,key:s,value:a[s]}]}),i.abortEarly))break}if(!r.issues||!i.abortEarly)for(let s in a)Dt(a,s)&&!(s in this.entries)&&(r.value[s]=a[s])}else x(this,"type",r,i);return r}}}function et(e){return{kind:"schema",type:"never",reference:et,expects:"never",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return x(this,"type",t,r),t}}}function _(e,t){return{kind:"schema",type:"nullable",reference:_,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===null&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function G(e,t){return{kind:"schema",type:"nullish",reference:G,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function U(e){return{kind:"schema",type:"number",reference:U,expects:"number",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:x(this,"type",t,r),t}}}function g(e,t){return{kind:"schema",type:"object",reference:g,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let s in this.entries){let c=this.entries[s];if(s in a||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){let m=s in a?a[s]:be(c),l=c["~run"]({value:m},i);if(l.issues){let h={type:"object",origin:"value",input:a,key:s,value:m};for(let p of l.issues)p.path?p.path.unshift(h):p.path=[h],r.issues?.push(p);if(r.issues||(r.issues=l.issues),i.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[s]=l.value}else if(c.fallback!==void 0)r.value[s]=Ot(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(x(this,"key",r,i,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:a,key:s,value:a[s]}]}),i.abortEarly))break}}else x(this,"type",r,i);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 O(this)},"~run"(r,i){return r.value===void 0&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function S(e,t){return{kind:"schema",type:"picklist",reference:S,expects:Xe(e.map(te),"|"),async:!1,options:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return this.options.includes(r.value)?r.typed=!0:x(this,"type",r,i),r}}}function I(e,t,r){return{kind:"schema",type:"record",reference:I,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return O(this)},"~run"(i,a){let s=i.value;if(s&&typeof s=="object"){i.typed=!0,i.value={};for(let c in s)if(Dt(s,c)){let m=s[c],l=this.key["~run"]({value:c},a);if(l.issues){let p={type:"object",origin:"key",input:s,key:c,value:m};for(let b of l.issues)b.path=[p],i.issues?.push(b);if(i.issues||(i.issues=l.issues),a.abortEarly){i.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let p={type:"object",origin:"value",input:s,key:c,value:m};for(let b of h.issues)b.path?b.path.unshift(p):b.path=[p],i.issues?.push(b);if(i.issues||(i.issues=h.issues),a.abortEarly){i.typed=!1;break}}(!l.typed||!h.typed)&&(i.typed=!1),l.typed&&(i.value[l.value]=h.value)}}else x(this,"type",i,a);return i}}}function o(e){return{kind:"schema",type:"string",reference:o,expects:"string",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:x(this,"type",t,r),t}}}function Pt(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function Ee(e,t){return{kind:"schema",type:"union",reference:Ee,expects:Xe(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a,s,c;for(let m of this.options){let l=m["~run"]({value:r.value},i);if(l.typed)if(l.issues)s?s.push(l):s=[l];else{a=l;break}else c?c.push(l):c=[l]}if(a)return a;if(s){if(s.length===1)return s[0];x(this,"type",r,i,{issues:Pt(s)}),r.typed=!0}else{if(c?.length===1)return c[0];x(this,"type",r,i,{issues:Pt(c)})}return r}}}function J(){return{kind:"schema",type:"unknown",reference:J,expects:"unknown",async:!1,get"~standard"(){return O(this)},"~run"(e){return e.typed=!0,e}}}function tt(e,t,r){return{kind:"schema",type:"variant",reference:tt,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return O(this)},"~run"(i,a){let s=i.value;if(s&&typeof s=="object"){let c,m=0,l=this.key,h=[],p=n((b,E)=>{for(let w of b.options){if(w.type==="variant")p(w,new Set(E).add(w.key));else{let D=!0,L=0;for(let P of E){let N=w.entries[P];if(P in s?N["~run"]({typed:!1,value:s[P]},{abortEarly:!0}).issues:N.type!=="exact_optional"&&N.type!=="optional"&&N.type!=="nullish"){D=!1,l!==P&&(m<L||m===L&&P in s&&!(l in s))&&(m=L,l=P,h=[]),l===P&&h.push(w.entries[P].expects);break}L++}if(D){let P=w["~run"]({value:s},a);(!c||!c.typed&&P.typed)&&(c=P)}}if(c&&!c.issues)break}},"parseOptions");if(p(this,new Set([this.key])),c)return c;x(this,"type",i,a,{input:s[l],expected:Xe(h,"|"),path:[{type:"object",origin:"value",input:s,key:l,value:s[l]}]})}else x(this,"type",i,a);return i}}}function rt(e,t,r){let i=e["~run"]({value:t},Ye(r));if(i.issues)throw new Ze(i.issues);return i.value}function f(...e){return{...e[0],pipe:e,get"~standard"(){return O(this)},"~run"(t,r){for(let i of e)if(i.kind!=="metadata"){if(t.issues&&(i.kind==="schema"||i.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=i["~run"](t,r))}return t}}}function Se(e,t,r){let i=e["~run"]({value:t},Ye(r));return{typed:i.typed,success:!i.issues,output:i.value,issues:i.issues}}var Ke,Zn,Qn,ti,Ze,ni,bo,ii,j=u(()=>{n(Ye,"getGlobalConfig");n(Jn,"getGlobalMessage");n(ei,"getSchemaMessage");n(ri,"getSpecificMessage");n(te,"_stringify");n(x,"_addIssue");n(O,"_getStandardProps");n(Dt,"_isValidObjectKey");n(Xe,"_joinExpects");Ze=class extends Error{static{n(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},ni=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,bo=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"),ii=/^\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;n(K,"email");n($,"isoTimestamp");n(Pe,"length");n(De,"maxLength");n(ue,"maxValue");n(v,"minLength");n(re,"minValue");n(Oe,"regex");n(F,"url");n(Ot,"getFallback");n(be,"getDefault");n(ne,"any");n(R,"array");n(C,"boolean");n(Je,"custom");n(ce,"literal");n(Qe,"looseObject");n(et,"never");n(_,"nullable");n(G,"nullish");n(U,"number");n(g,"object");n(d,"optional");n(S,"picklist");n(I,"record");n(o,"string");n(Pt,"_subIssues");n(Ee,"union");n(J,"unknown");n(tt,"variant");n(rt,"parse");n(f,"pipe");n(Se,"safeParse")});var xe,nt,xo,it=u(()=>{"use strict";xe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},nt={PAYMENT:"payment",SUBSCRIPTION:"subscription"},xo={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});var To,Ro,Co,Io,Po,Do,oi,si,ai,Oo,_o,No,_t=u(()=>{"use strict";j();it();To=g({userId:d(o()),productId:d(o()),priceId:o(),successUrl:f(o(),F()),cancelUrl:f(o(),F()),customerEmail:d(f(o(),K())),userEmail:d(f(o(),K())),metadata:d(I(o(),o())),allowPromotionCodes:d(C()),mode:d(S([nt.PAYMENT,nt.SUBSCRIPTION]))}),Ro=g({sessionId:o(),sessionUrl:_(f(o(),F()))}),Co=g({userId:o(),tier:o(),status:S(Object.values(xe)),subscriptionId:_(o()),customerId:o(),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$())}),Io=g({tier:o(),subscriptionId:_(o()),customerId:o(),status:S(Object.values(xe)),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$()),isDefault:d(C())}),Po=g({id:o(),type:o(),data:g({object:ne()}),created:f(o(),$())}),Do=Qe({userId:d(o()),firebaseUid:d(o()),productType:d(o())}),oi=g({type:ce("StripePayment"),name:f(o(),v(1,"Product name is required")),description:d(o()),price:o(),currency:d(f(o(),Pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(o(),v(1,"Stripe price ID is required")),tier:f(o(),v(1,"Tier is required")),duration:f(o(),v(1,"Duration is required")),allowPromotionCodes:d(C()),metadata:d(I(o(),o()))}),si=g({type:ce("StripeSubscription"),name:f(o(),v(1,"Product name is required")),description:d(o()),price:o(),currency:d(f(o(),Pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(o(),v(1,"Stripe price ID is required")),tier:f(o(),v(1,"Tier is required")),duration:S(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:d(C()),metadata:d(I(o(),o()))}),ai=tt("type",[oi,si]),Oo=I(o(),ai),_o=I(o(),g({name:o(),price:o(),currency:o(),description:d(o()),features:d(R(o())),priceId:o(),allowPromotionCodes:d(C())})),No=I(o(),g({type:S(["StripePayment","StripeSubscription"]),name:o(),price:U(),currency:o(),priceId:o(),tier:o(),duration:o(),description:d(o()),metadata:d(I(o(),o())),allowPromotionCodes:d(C())}))});var Nt=u(()=>{"use strict"});var ot=u(()=>{"use strict";it();_t();Nt()});var $o,ui,Go,Ft=u(()=>{"use strict";j();ze();ot();$o=g({id:o(),email:d(_(f(o(),K()))),displayName:d(_(o())),photoURL:d(_(f(o(),F()))),emailVerified:d(C()),lastLoginAt:d(o()),providerData:d(R(g({providerId:o(),uid:o(),email:d(_(f(o(),K()))),displayName:d(_(o())),photoURL:d(_(f(o(),F()))),phoneNumber:d(_(o()))}))),role:d(S(Object.values(Z))),customClaims:d(I(o(),ne()))}),ui=g({userId:o(),tier:S(Object.values(Rt)),status:S(Object.values(xe)),isActive:d(C()),features:d(R(o())),subscriptionId:_(o()),customerId:o(),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$())}),Go=g({role:d(S(Object.values(Z))),subscription:d(ui),features:d(R(S(Object.values(Ct)))),permissions:d(R(S(Object.values(It)))),githubAccess:d(g({username:d(o()),teamAccess:d(R(o())),repoAccess:d(R(o()))}))})});var Ut=u(()=>{"use strict"});var Mt=u(()=>{"use strict"});var Lt=u(()=>{"use strict";ze();Ft();Ut();Mt()});var Bt=u(()=>{"use strict"});var qt=u(()=>{"use strict"});var ie,_e=u(()=>{"use strict";ie={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var ns,Vt=u(()=>{"use strict";_e();ns={EQ:ie.EQ,NEQ:ie.NEQ,LT:ie.LT,LTE:ie.LTE,GT:ie.GT,GTE:ie.GTE}});var jt=u(()=>{"use strict"});var $t=u(()=>{"use strict"});var cs,ls,ps,ds,fs,Gt=u(()=>{"use strict";j();_e();cs=g({collection:f(o(),v(1,"Collection name is required")),data:I(o(),J()),idempotencyKey:d(o())}),ls=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required"))}),ps=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required")),data:I(o(),J()),merge:d(C(),!1)}),ds=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required"))}),fs=g({collection:f(o(),v(1,"Collection name is required")),limit:d(f(U(),re(1),ue(1e3)),1e3),offset:d(f(U(),re(0)),0),orderBy:d(o()),orderDirection:d(S(["asc","desc"]),"desc"),where:d(R(g({field:o(),operator:S(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:J()})))})});var Ht=u(()=>{"use strict"});var Wt=u(()=>{"use strict";qt();Vt();jt();_e();$t();Gt();Ht()});var ke,Ne,st,A,zt=u(()=>{"use strict";ke={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"},Ne={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},st={[ke.PERMISSION_DENIED]:{type:Ne.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ke.NOT_FOUND]:{type:Ne.NOT_FOUND,message:"The requested resource was not found"},[ke.ALREADY_EXISTS]:{type:Ne.ALREADY_EXISTS,message:"The resource already exists"},[ke.INVALID_ARGUMENT]:{type:Ne.VALIDATION_ERROR,message:"Invalid argument provided"}},A=class e extends Error{static{n(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=ke.INTERNAL,i){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=i?.details,this.source=i?.source,this.originalError=i?.originalError,this.context=i?.context,this.displayable=i?.displayable??!0,this.userMessageProvided=i?.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 Kt=u(()=>{"use strict";zt()});var Yt=u(()=>{"use strict"});var Xt=u(()=>{"use strict"});var Zt=u(()=>{"use strict"});var Jt=u(()=>{"use strict"});var Qt=u(()=>{"use strict"});var er=u(()=>{"use strict"});var tr=u(()=>{"use strict";Xt();Zt();Jt();Qt();er()});var rr=u(()=>{"use strict"});var nr=u(()=>{"use strict";rr()});var ir=u(()=>{"use strict"});var or=u(()=>{"use strict";ir()});var sr=u(()=>{"use strict"});var ar=u(()=>{"use strict";sr()});var ur=u(()=>{"use strict"});var cr=u(()=>{"use strict";ur()});var lr=u(()=>{"use strict"});var pr=u(()=>{"use strict"});var dr=u(()=>{"use strict"});var fr=u(()=>{"use strict";lr();pr();dr()});var mr=u(()=>{"use strict"});var gr=u(()=>{"use strict";mr()});var yr,at=u(()=>{"use strict";yr=["pull","push","admin","maintain","triage"]});var hr=u(()=>{"use strict"});var ut,li,Js,Qs,ea,ta,ra,na,ia,vr=u(()=>{"use strict";j();at();ut=g({owner:f(o(),v(1,"Repository owner is required")),repo:f(o(),v(1,"Repository name is required"))}),li=S([...yr]),Js=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut,permission:d(li,"push"),customClaims:d(I(o(),ne()))}),Qs=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut}),ea=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut}),ta=g({provider:o(),purpose:S(["authentication","api-access"]),code:f(o(),v(1,"Authorization code is required")),redirectUri:f(o(),F("Valid redirect URI is required")),codeVerifier:d(o()),state:d(o()),instance:d(f(o(),F()))}),ra=g({provider:o(),refreshToken:f(o(),v(1,"Refresh token is required")),redirectUri:f(o(),F("Valid redirect URI is required"))}),na=g({provider:o()}),ia=g({userId:f(o(),v(1,"User ID is required"))})});var br=u(()=>{"use strict";at();hr();vr()});var Er=u(()=>{"use strict"});var Sr,pi,Fe,di,fi,mi,gi,pa,da,xr=u(()=>{"use strict";j();Sr=g({name:o(),color:o(),icon:o(),customParameters:d(I(o(),o())),button:g({backgroundColor:o(),textColor:o(),borderColor:o(),hoverBackgroundColor:o(),focusOutlineColor:o(),fontWeight:d(o(),"500"),textKey:d(o())})}),pi=g({...Sr.entries,type:S(["auth","both"]),scopes:d(R(o())),firebaseProviderId:d(o())}),Fe=Ee([ce(""),f(o(),F())]),di=g({authUrl:Fe,tokenUrl:Fe,profileUrl:Fe,revokeUrl:d(Fe)}),fi=g({authentication:d(R(o())),"api-access":R(o())}),mi=d(g({pkce:d(C(),!1),codeChallengeMethod:d(S(["S256","plain"]),"S256")})),gi=g({...Sr.entries,type:S(["oauth","both"]),scopes:fi,endpoints:di,capabilities:mi}),pa=I(o(),pi),da=I(o(),gi)});var kr=u(()=>{"use strict"});var wr=u(()=>{"use strict";Er();xr();kr()});var Ar=u(()=>{"use strict"});var Tr=u(()=>{"use strict"});var Rr=u(()=>{"use strict";Ar();Tr()});var Cr=u(()=>{"use strict"});var Ir=u(()=>{"use strict";Cr()});var Pr=u(()=>{"use strict"});var Dr=u(()=>{"use strict";Pr()});var Or,ka,_r=u(()=>{"use strict";Or={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},ka={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Or.ANALYTICS},marketing:{requiresConsent:Or.MARKETING}}});var Nr=u(()=>{"use strict";_r()});var Fr=u(()=>{"use strict"});var Ur=u(()=>{"use strict"});var Mr=u(()=>{"use strict";Fr();Ur()});var Y=u(()=>{"use strict";Lt();ot();Bt();Wt();Kt();Yt();tr();nr();or();ar();cr();fr();gr();br();wr();Rr();Ir();Dr();Nr();Mr()});var we=u(()=>{"use strict";Y()});function Lr(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 ct=u(()=>{"use strict";n(Lr,"detectErrorSource")});function X(e){return(t,r)=>{if(t instanceof A)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new A(r||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let i;e.extractErrorCode?i=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(i=t.code);let a=e.defaultErrorCode;i&&e.errorCodeMapping&&i in e.errorCodeMapping&&(a=e.errorCodeMapping[i]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),i&&e.friendlyMessageMapping&&i in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[i]),s||(s=e.defaultErrorMessage);let c;return e.processMetadata?c=e.processMetadata(t):(c={originalError:t},i&&(c.originalCode=i)),"originalError"in c||(c.originalError=t),new A(r||s,a,{details:c,source:e.errorSource})}}var Ue,lt=u(()=>{"use strict";we();n(X,"createErrorHandler");Ue={"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 dt(e,t,r){return e instanceof A?e:(Br[t]||Br.unknown)(e,r)}var le,yi,pt,Q,hi,vi,Br,ft=u(()=>{"use strict";j();Y();we();lt();le={"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."},yi={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"},pt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Q={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",...Ue},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",...Ue},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(yi).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:n(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:n(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:Ue,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:le.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:n(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:le["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:le.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:n(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},hi=n(e=>e instanceof Ze?new A(le["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):X(Q.validation)(e),"handleValidationError"),vi=n(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in pt){let t=e,r=pt[t.type]||"unknown";return new A(t.message||le[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&st[e.code]){let t=e,r=st[t.code];if(r){let i=pt[r.type]||"unknown";return new A(r.message||le[i],i,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return X(Q.entity)(e)},"handleEntityError"),Br={auth:X(Q.auth),oauth:X(Q.oauth),api:X(Q.api),firebase:X(Q.firebase),ui:X(Q.ui),validation:hi,entity:vi,unknown:X(Q.unknown)};n(dt,"mapToDoNotDevError")});function qr(e,t,r={}){let i=globalThis.Sentry;i&&i.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,c])=>{if(typeof c!="function"&&s!=="originalError")try{a.setExtra(s,c)}catch{a.setExtra(s,`[${typeof c}]`)}}),Object.entries(r).forEach(([s,c])=>{if(typeof c!="function")try{a.setExtra(`context.${s}`,c)}catch{a.setExtra(`context.${s}`,`[${typeof c}]`)}}),(e.details?.userId||r.userId)&&a.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),i.captureException(e)})}var mt=u(()=>{"use strict";n(qr,"captureErrorToSentry")});function bi(){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 T(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:i,context:a={},log:s=!0,reportToSentry:c=!0,showNotification:m=!1,severity:l="error"}=r,h=Lr(e),p=e instanceof A?e:dt(e,h,i);if(i&&!p.userMessageProvided&&(p.message.includes("Error")||p.message.includes("Failed")||p.message.length<10?p=new A(i,p.code,{details:{...p.details,originalMessage:p.message},source:h,userMessageProvided:!0}):p=new A(p.message,p.code,{details:{...p.details,userMessage:i},source:h,userMessageProvided:!0})),s){let b=bi()||typeof window<"u"&&window.__DNDEV_DEBUG,E={code:p.code,message:p.message,source:h};switch(l){case"warning":console.warn(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;case"info":console.info(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;case"success":console.log(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;default:console.error(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details,stack:p.stack}:E)}}return c&&qr(p,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),p}var Vr=u(()=>{"use strict";we();ct();ft();mt();n(bi,"isDev");n(T,"handleError")});var Me=u(()=>{"use strict";we();Vr();ct();ft();mt();lt()});var jr=u(()=>{"use strict";Me()});var $r=u(()=>{"use strict";Me()});var Gr=u(()=>{"use strict";jr();$r()});var Hr=u(()=>{"use strict"});var Wr=u(()=>{"use strict"});var zr=u(()=>{"use strict"});var Kr=u(()=>{"use strict"});var Yr=u(()=>{"use strict"});var Xr=u(()=>{"use strict"});var Zr=u(()=>{"use strict"});var Jr=u(()=>{"use strict"});var Qr=u(()=>{"use strict"});var Zu,gt=u(()=>{"use strict";Y();Zu={[Z.GUEST]:0,[Z.USER]:1,[Z.ADMIN]:2,[Z.SUPER]:3}});var en=u(()=>{"use strict";Y()});function tn(e){if(!yt)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let t=yt[e];if(!t)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return t}function rn(e){return!!yt?.[e]}var yt,nn=u(()=>{"use strict";yt=null;n(tn,"getProvider");n(rn,"hasProvider")});function on(e,...t){let r=null,i=!1;return n(function(){if(r!==null)return r;if(i)throw new Error("Circular dependency detected in singleton initialization");i=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{i=!1}},"getInstance")}var sn=u(()=>{"use strict";n(on,"createSingleton")});var an=u(()=>{"use strict"});var ht=u(()=>{"use strict";gt()});var un=u(()=>{"use strict";ht()});var cn=u(()=>{"use strict"});var ln=u(()=>{"use strict"});var pn=u(()=>{"use strict";un();cn();ht();ln()});var dn=u(()=>{"use strict"});var fn=u(()=>{"use strict";dn()});var mn=u(()=>{"use strict"});var gn=u(()=>{"use strict";Gr();Hr();Wr();zr();Kr();Me();Yr();Xr();Zr();Jr();Qr();gt();en();nn();sn();an();pn();fn();mn()});var yn=u(()=>{"use strict"});var hn=u(()=>{"use strict"});var vn=u(()=>{"use strict"});var ee=u(()=>{gn();yn();hn();vn()});var bn=u(()=>{"use strict"});var En=u(()=>{"use strict"});function y(e,t){Si.set(e,t)}function k(e,t){return t?e:G(e)}function Li(){y("text",Le),y("textarea",Le),y("richtext",Le),y("color",Le),y("email",xi),y("password",ki),y("url",wi),y("tel",_i),y("iban",Ni),y("number",pe),y("currency",pe),y("price",Mi),y("range",pe),y("year",pe),y("rating",pe),y("duration",pe),y("boolean",Sn),y("checkbox",Sn),y("gdprConsent",Ui),y("date",de),y("datetime-local",de),y("time",de),y("week",de),y("month",de),y("timestamp",de),y("file",xn),y("files",kn),y("document",xn),y("documents",kn),y("image",Ai),y("images",Ti),y("geopoint",Ri),y("address",Ci),y("map",Ii),y("array",Pi),y("select",vt),y("multiselect",Di),y("radio",vt),y("combobox",vt),y("switch",Fi),y("reference",Oi),y("hidden",bt),y("avatar",bt),y("badge",bt),y("submit",wn),y("reset",wn)}var Si,Le,xi,ki,wi,pe,Sn,de,An,xn,kn,Tn,Ai,Ti,Ri,Ci,Ii,Pi,vt,Di,Oi,bt,_i,Ni,wn,Fi,Ui,Mi,Et=u(()=>{"use strict";j();Si=new Map;n(y,"registerSchemaGenerator");n(k,"applyRequired");Le=n(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(v(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(Oe(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?f(o(),...t):o();return k(r,e.validation?.required)},"textSchema"),xi=n(e=>{let t=f(o(),K("Invalid email address"));return k(t,e.validation?.required)},"emailSchema"),ki=n(e=>{let t=e.validation?.minLength!==void 0?f(o(),v(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):o();return k(t,e.validation?.required)},"passwordSchema"),wi=n(e=>{let t=f(o(),F("Invalid URL"));return k(t,e.validation?.required)},"urlSchema"),pe=n(e=>{let t=[];e.validation?.min!==void 0&&t.push(re(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(ue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?f(U(),...t):U();return k(r,e.validation?.required)},"numberSchema"),Sn=n(e=>{let t=C();return k(t,e.validation?.required)},"booleanSchema"),de=n(e=>{let t=f(o(),$("Invalid date format"));return k(t,e.validation?.required)},"dateSchema"),An=g({url:o(),filename:o(),size:U(),mimeType:G(o()),uploadedAt:G(o())}),xn=n(e=>{let t=_(An);return k(t,e.validation?.required)},"fileSchema"),kn=n(e=>{let t=R(An);return k(t,e.validation?.required)},"filesSchema"),Tn=g({fullUrl:o(),thumbUrl:o()}),Ai=n(e=>k(Tn,e.validation?.required),"pictureSchema"),Ti=n(e=>{let t=R(Tn);return k(t,e.validation?.required)},"picturesSchema"),Ri=n(e=>{let t=g({lat:U(),lng:U()});return k(t,e.validation?.required)},"geopointSchema"),Ci=n(e=>{let t=g({formatted_address:o(),latitude:U(),longitude:U(),street_number:G(o()),route:G(o()),locality:G(o()),administrative_area_level_1:G(o()),administrative_area_level_2:G(o()),country:G(o()),postal_code:G(o())});return k(t,e.validation?.required)},"addressSchema"),Ii=n(e=>{let t=I(o(),J());return k(t,e.validation?.required)},"mapSchema"),Pi=n(e=>{let t=R(J());return k(t,e.validation?.required)},"arraySchema"),vt=n(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(s=>s.value),a=S(i);return k(a,e.validation?.required)}let r=Ee([o(),U()]);return k(r,e.validation?.required)},"selectSchema"),Di=n(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(s=>s.value),a=R(S(i));return k(a,e.validation?.required)}let r=R(o());return k(r,e.validation?.required)},"multiselectSchema"),Oi=n(e=>{let t=f(o(),v(1,"Invalid ID format"));return k(t,e.validation?.required)},"referenceSchema"),bt=n(e=>{let t=o();return k(t,e.validation?.required)},"stringSchema"),_i=n(e=>{let t=o();return k(t,e.validation?.required)},"telSchema"),Ni=n(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,i=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",a=[];if(t!==void 0&&a.push(v(t,`IBAN must be at least ${t} characters`)),r!==void 0&&a.push(De(r,`IBAN must not exceed ${r} characters`)),i){let c=typeof i=="string"?new RegExp(i):i;a.push(Oe(c,"Invalid IBAN format"))}let s=a.length>0?f(o(),...a):o();return k(s,e.validation?.required)},"ibanSchema"),wn=n(()=>et(),"neverSchema"),Fi=n(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let i=[t.checkedValue,t.uncheckedValue],a=S(i);return k(a,e.validation?.required)}let r=C();return k(r,e.validation?.required)},"switchSchema"),Ui=n(e=>Je(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"),Mi=n(e=>{let t=g({amount:U(),currency:d(o()),vatIncluded:d(C()),discountPercent:d(f(U(),re(0),ue(100)))});return k(t,e.validation?.required)},"priceSchema");n(Li,"registerBuiltinSchemas");Li()});var St=u(()=>{"use strict";ee()});var xt=u(()=>{"use strict";ee()});var Rn=u(()=>{"use strict";St();xt()});var Cn=u(()=>{"use strict";En();Et();St();Rn();xt()});var In=u(()=>{"use strict";ee()});var Pn,Dn,Ul,On,Be=u(()=>{"use strict";Y();Pn=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],Dn=["id","createdAt","updatedAt","createdById","updatedById"],Ul=[...Dn,"status"],On={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Pn]}},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 _n=u(()=>{"use strict";Y();ee();Be()});var Nn=u(()=>{"use strict";Y();ee();Et();Be()});var Fn=u(()=>{"use strict"});var Un=u(()=>{"use strict"});var Mn=u(()=>{"use strict";Cn();In();Be();_n();Nn();Fn();Un()});var Ln=u(()=>{"use strict";bn();Mn()});var q=u(()=>{ee();Y();Ln();ee()});import{initializeApp as Bn,getApps as qi,cert as Vi}from"firebase-admin/app";import{getAuth as ji}from"firebase-admin/auth";import{getFirestore as $i}from"firebase-admin/firestore";import{getFunctions as Gi}from"firebase-admin/functions";function Hi(){let e=qi(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=Bn({credential:Vi({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=Bn():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:ji(t),firestore:$i(t),functions:Gi(t)}}async function Ae(){let e=kt();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function M(){let e=kt();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function oe(){let e=kt();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}var kt,qe=u(()=>{"use strict";q();n(Hi,"initializeFirebaseAdminServices");kt=on(Hi);n(Ae,"getFirebaseAdminApp");n(M,"getFirebaseAdminAuth");n(oe,"getFirebaseAdminFirestore")});var qn=u(()=>{"use strict";q();qe()});var Ve,Pp,fe,Dp,Te=u(()=>{"use strict";q();qe();Ve={async getServerAdmin(){try{return Ae()}catch(e){throw T(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return oe()}catch(e){throw T(e,"Error getting Admin Firestore")}},async generateServerId(){return(await Ve.getServerFirestore()).collection("_").doc().id}},Pp=Ve.getServerAdmin,fe=Ve.getServerFirestore,Dp=Ve.generateServerId});function Wi(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw T(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 T(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw T(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw T(t,"Failed to convert to ISO string")}}function zi(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function me(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,i=r.data();return{id:r.id,...me(i)}}if(Array.isArray(e))return e.map(r=>me(r));if(zi(e))return Wi(e);if(typeof e=="object"&&e!==null){let r={};for(let[i,a]of Object.entries(e))r[i]=me(a);return r}return e}function Re(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>Re(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[i,a]of Object.entries(e))t.includes(i)||a!==void 0&&(r[i]=Re(a,t));return r}return e}var je=u(()=>{"use strict";q();n(Wi,"firestoreToISOString");n(zi,"isTimestamp");n(me,"transformFirestoreData");n(Re,"prepareForFirestore")});var ge,W,ye,Bp,qp,Vp,jp,$p,Gp,Vn=u(()=>{"use strict";j();q();Te();je();ge=typeof window<"u",W={async batchWrite(e,t,r,i,a={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:s="id",generateIds:c=!0,maxBatchSize:m=450,removeFields:l=[],validate:h=!!i}=a,p={successes:0,failures:0,failedItems:[]};try{let b=[],E=await fe(),w=E.batch(),D=0;for(let P=0;P<t.length;P++){let N=t[P];if(!N){p.failures++,p.failedItems?.push({index:P,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!N[s])throw T(new Error(`Missing ID for delete operation (${s})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:s,operation:r}});let B=E.collection(e).doc(N[s]);w.delete(B)}else{if(h&&i)try{rt(i,N)}catch(Yn){throw T(Yn,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:s,itemId:N[s]}})}let B=N[s];if(!B&&r==="create"&&c)B=E.collection(e).doc().id,N={...N,[s]:B};else if(!B)throw T(new Error(`Missing ID for ${r} operation (${s})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:s,operation:r}});let We=[s,...l],ae=Re(N,We),Tt=E.collection(e).doc(B);r==="create"?w.create(Tt,ae):r==="update"&&w.update(Tt,ae)}D++,D>=m&&(b.push({batch:w,size:D}),w=E.batch(),D=0)}catch(B){p.failures++,p.failedItems?.push({index:P,error:B instanceof Error?B:new Error(String(B))})}}D>0&&b.push({batch:w,size:D});let L=0;for(let{batch:P,size:N}of b){try{await P.commit(),p.successes+=N}catch(B){let We=B instanceof Error?B:new Error(String(B));for(let ae=L;ae<L+N;ae++)p.failures++,p.failedItems?.push({index:ae,error:We})}L+=N}return p}catch(b){throw T(b,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:p.successes+p.failures,successCount:p.successes,failureCount:p.failures}})}},async batchCreate(e,t,r,i={}){return W.batchWrite(e,t,"create",r,i)},async batchUpdate(e,t,r,i={}){return W.batchWrite(e,t,"update",r,i)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let i=r.idField||"id",a=t.map(s=>({[i]:s}));return W.batchWrite(e,a,"delete",void 0,r)}return W.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await fe()).runTransaction(e)}catch(t){throw T(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:i=30,transform:a=!0}=r;try{let s=[];for(let l=0;l<t.length;l+=i)s.push(t.slice(l,l+i));let c=s.map(async l=>{let b=await(await fe()).collection(e).where("__name__","in",l).get(),E=new Map;return b.forEach(w=>{E.set(w.id,w.data())}),l.map(w=>{let D=E.get(w);return D?a?me({id:w,...D}):{id:w,...D}:null})});return(await Promise.all(c)).flat()}catch(s){throw T(s,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},ye=n(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),Bp=ge?ye("batchWrite"):W.batchWrite,qp=ge?ye("batchCreate"):W.batchCreate,Vp=ge?ye("batchUpdate"):W.batchUpdate,jp=ge?ye("batchDelete"):W.batchDelete,$p=ge?ye("runTransaction"):W.runTransaction,Gp=ge?ye("bulkGet"):W.bulkGet});var jn=u(()=>{"use strict";q()});var $n=u(()=>{"use strict";q();Te();je();jn()});var $e=u(()=>{"use strict";q();Te()});var Gn=u(()=>{"use strict";q();$e();$e()});import{FieldValue as Cd,Query as Id,Timestamp as Pd}from"firebase-admin/firestore";var z=u(()=>{"use strict";qn();qe();Te();Vn();$n();Gn();$e();je()});q();function V(e){let t,r,i;if(e instanceof A)t=e.code,r=e.message,i=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",i={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,i=void 0}else t="internal",r=e instanceof Error?e.message:"An unexpected error occurred",i=void 0;throw new A(r,t,i?{details:i}:void 0)}n(V,"handleError");q();z();function Yi(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}n(Yi,"extractBearerToken");async function Xi(e,t){try{return t==="supabase"?await Zi(e):t==="firebase"?{uid:(await M().verifyIdToken(e)).uid}:rn("serverAuth")?{uid:(await tn("serverAuth").verifyToken(e)).uid}:{uid:(await M().verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}n(Xi,"verifyToken");async function Zi(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,i=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!i)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let a=t(r,i,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:c}=await a.auth.getUser(e);if(c||!s)throw new Error("Invalid or expired token");return{uid:s.id}}n(Zi,"verifySupabaseToken");async function Ge(e,t){let r=Yi(e.headers.authorization),{uid:i}=await Xi(r,t);return i}n(Ge,"verifyAuthToken");z();var Ji=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Vd(e){let t=new Set(e.allowedClaimKeys);for(let r of t)if(Ji.has(r))throw new Error(`Claim key "${r}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return n(async function(i,a){if(i.method!=="POST")return a.status(405).json({error:"Method not allowed"});try{let s=await Ge(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw V(new Error("customClaims must be an object"));let m=Object.keys(c).filter(b=>!t.has(b));if(m.length>0)throw V(new Error(`Claim keys not allowed: ${m.join(", ")}`));let p={...(await M().getUser(s)).customClaims||{},...c};return await M().setCustomUserClaims(s,p),a.status(200).json({success:!0,customClaims:p})}catch(s){throw V(s)}},"handler")}n(Vd,"createSetCustomClaimsHandler");import Qi from"stripe";q();z();var He=null;function eo(e){if(!e)throw new Error("Stripe API key is required");let t=process.env.STRIPE_API_VERSION||"2024-12-18.acacia";return He=new Qi(e,{apiVersion:t}),He}n(eo,"initStripe");function to(){if(!He){let e=process.env.STRIPE_SECRET_KEY;if(e)eo(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return He}n(to,"getStripe");var se=new Proxy({},{get(e,t){return to()[t]}});function he(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}n(he,"validateStripeEnvironment");j();z();import{logger as Hn}from"firebase-functions/v2";async function wt(e){try{await oe().collection("payment_metrics").doc().set({...e,recordedAt:new Date().toISOString()}),Hn.info("Payment metrics recorded",{operation:e.operation,status:e.status,userId:e.userId})}catch(t){Hn.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:e})}}n(wt,"recordPaymentMetrics");z();import{logger as Wn}from"firebase-functions/v2";async function zn(e,t){let r=oe(),i=r.collection("rateLimits").doc(e);try{let a=Date.now(),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return await r.runTransaction(async c=>{let m=await c.get(i);if(!m.exists){c.set(i,{attempts:1,windowStart:a,blockUntil:null,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return}let l=m.data();if(l.blockUntil&&a<l.blockUntil){s={allowed:!1,remaining:0,resetAt:new Date(l.blockUntil),blockRemainingSeconds:Math.ceil((l.blockUntil-a)/1e3)};return}if(a>=l.windowStart+t.windowMs){c.set(i,{attempts:1,windowStart:a,blockUntil:null,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return}if(l.attempts>=t.maxAttempts){let h=a+t.blockDurationMs;c.update(i,{blockUntil:h,lastUpdated:a}),Wn.warn("Rate limit exceeded (Firestore)",{key:e,attempts:l.attempts,blockUntil:new Date(h)}),s={allowed:!1,remaining:0,resetAt:new Date(h),blockRemainingSeconds:Math.ceil(t.blockDurationMs/1e3)};return}c.update(i,{attempts:l.attempts+1,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-(l.attempts+1),resetAt:new Date(l.windowStart+t.windowMs),blockRemainingSeconds:null}}),s}catch(a){return Wn.error("Rate limit check failed",{key:e,error:a instanceof Error?a.message:String(a)}),{allowed:!0,remaining:t.maxAttempts,resetAt:null,blockRemainingSeconds:null}}}n(zn,"checkRateLimitWithFirestore");var At={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};function ve(e,t,r,i,a,s){return async(c,m)=>{try{if(c.method!==e)return m.status(405).json({error:"Method not allowed"});let l=Se(t,c.body);if(!l.success)return m.status(400).json({error:`Validation failed: ${l.issues.map(L=>L.message).join(", ")}`});let h=l.output,p=await Ge(c,s),b=`${r}_${p}`,E=At[r]||At.api,w=await zn(b,E);if(!w.allowed)return a?.audit({type:"rate_limit.exceeded",userId:p,metadata:{operation:r,remaining:0}}),m.status(429).json({error:`Rate limit exceeded. Try again in ${w.blockRemainingSeconds} seconds.`,retryAfter:w.blockRemainingSeconds});let D=await i(c,m,h,{uid:p});return D==null&&console.warn(`[${r}] businessLogic returned ${D} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await wt({operation:r,userId:p,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),D}catch(l){process.env.ENABLE_METRICS==="true"&&await wt({operation:r,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:l instanceof Error?l.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{V(l)}catch(h){let p=ro(h);return m.status(p.status).json({error:p.message})}return m.status(500).json({error:"Internal server error"})}}}n(ve,"createVercelBaseFunction");function ro(e){return e instanceof A?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[e.code]??500,message:e.message}:{status:500,message:"Internal server error"}}n(ro,"classifiedToHttp");async function Ce(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 s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},c={...a,subscription:s};await r.setCustomUserClaims(e,c)}n(Ce,"updateUserSubscription");j();z();q();async function Kn(e,t){he();let a=((await t.getUser(e)).customClaims||{}).subscription,s=a?.subscriptionId;if(!s)throw V(new Error("No active subscription found"));let c=await se.subscriptions.update(s,{cancel_at_period_end:!0}),l=["active","canceled","past_due","trialing","incomplete"].includes(c.status)?c.status:"incomplete";return await Ce(e,{tier:a?.tier||"free",status:l,subscriptionEnd:new Date(c.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:c.id,customerId:c.customer},t),{success:!0,endsAt:new Date(c.current_period_end*1e3).toISOString()}}n(Kn,"cancelUserSubscription");var no=g({userId:o()});async function io(e,t,r,i){let a=i.uid,c=await Kn(a,{async getUser(m){return M().getUser(m)},async setCustomUserClaims(m,l){await M().setCustomUserClaims(m,l)}});return t.status(200).json({success:c.success,cancelAtPeriodEnd:!0,endsAt:c.endsAt})}n(io,"cancelSubscriptionLogic");var oo=n(()=>ve("POST",no,"cancel_subscription",io),"cancelSubscription"),so=oo;j();z();var ao=g({userId:o(),newPriceId:o(),billingConfigKey:o()});async function uo(e,t,r,i,a){he();let s=i.uid,{newPriceId:c,billingConfigKey:m}=r,l=a[m];if(!l||l.type!=="StripeSubscription")throw V(new Error("Invalid plan"));if(l.priceId!==c)throw V(new Error("Price ID mismatch"));let p=(await M().getUser(s)).customClaims?.subscription?.subscriptionId;if(!p)throw V(new Error("No active subscription"));let b=await se.subscriptions.retrieve(p),E=await se.subscriptions.update(p,{items:[{id:b.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),D=["active","canceled","past_due","trialing","incomplete"].includes(E.status)?E.status:"incomplete";return await Ce(s,{tier:l.tier,status:D,subscriptionEnd:new Date(E.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:E.cancel_at_period_end,subscriptionId:E.id,customerId:E.customer},{async getUser(L){return M().getUser(L)},async setCustomUserClaims(L,P){await M().setCustomUserClaims(L,P)}}),t.status(200).json({success:!0,newTier:l.tier,newPrice:l.price})}n(uo,"changePlanLogic");var co=n(e=>ve("POST",ao,"change_plan",(t,r,i,a)=>uo(t,r,i,a,e)),"changePlan"),lo=co;j();z();var po=g({userId:o(),returnUrl:d(f(o(),F()))});async function fo(e,t,r,i){he();let a=i.uid,{returnUrl:s}=r,m=(await M().getUser(a)).customClaims?.subscription?.customerId;if(!m)throw V(new Error("No customer found"));let l=await se.billingPortal.sessions.create({customer:m,return_url:s||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:l.url})}n(fo,"createCustomerPortalLogic");var mo=n(()=>ve("POST",po,"create_customer_portal",fo),"createCustomerPortal"),go=mo;var Ie=process.env.FIREBASE_REGION||"europe-west1",zf={region:Ie,memory:"1GiB",timeoutSeconds:60},Kf={region:Ie,memory:"512MiB",timeoutSeconds:30},Yf={region:Ie,memory:"256MiB",timeoutSeconds:20},Xf={region:Ie,memory:"256MiB",timeoutSeconds:15},Zf={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},Jf=n(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${Ie}`)},"validateEnvironment");z();async function rm(){return await Ae()}n(rm,"initializeFirebaseAdmin");async function nm(){return await Ae()}n(nm,"getFirebaseAdmin");export{Yf as AUTH_CONFIG,Zf as AVAILABLE_REGIONS,Xf as CRUD_CONFIG,Ie as FIREBASE_REGION,zf as FUNCTION_CONFIG,Kf as STRIPE_CONFIG,so as cancelSubscription,lo as changePlan,go as createCustomerPortal,Vd as createSetCustomClaimsHandler,nm as getFirebaseAdmin,rm as initializeFirebaseAdmin,Ce as updateUserSubscription,Jf as validateEnvironment};
21
+ var Xn=Object.defineProperty;var n=(e,t)=>Xn(e,"name",{value:t,configurable:!0});var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Z,Rt,Ct,It,We=u(()=>{"use strict";Z={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},Rt={FREE:"free",PRO:"pro",PREMIUM:"premium"},Ct={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},It={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"}});function Ye(e){return{lang:e?.lang??Ke?.lang,message:e?.message,abortEarly:e?.abortEarly??Ke?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ke?.abortPipeEarly}}function Jn(e){return Zn?.get(e)}function ei(e){return Qn?.get(e)}function ri(e,t){return ti?.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 x(e,t,r,i,a){let s=a&&"input"in a?a.input:r.value,c=a?.expected??e.expects??null,m=a?.received??te(s),l={kind:e.kind,type:e.type,input:s,expected:c,received:m,message:`Invalid ${t}: ${c?`Expected ${c} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:i.lang,abortEarly:i.abortEarly,abortPipeEarly:i.abortPipeEarly},h=e.kind==="schema",p=a?.message??e.message??ri(e.reference,l.lang)??(h?ei(l.lang):null)??i.message??Jn(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),h&&(r.typed=!1),r.issues?r.issues.push(l):r.issues=[l]}function O(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},Ye())}}}function Dt(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Xe(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function K(e){return{kind:"validation",type:"email",reference:K,expects:null,async:!1,requirement:ni,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&x(this,"email",t,r),t}}}function $(e){return{kind:"validation",type:"iso_timestamp",reference:$,async:!1,expects:null,requirement:ii,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&x(this,"timestamp",t,r),t}}}function Pe(e,t){return{kind:"validation",type:"length",reference:Pe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length!==this.requirement&&x(this,"length",r,i,{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,i){return r.typed&&r.value.length>this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function ue(e,t){return{kind:"validation",type:"max_value",reference:ue,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!(r.value<=this.requirement)&&x(this,"value",r,i,{received:r.value instanceof Date?r.value.toJSON():te(r.value)}),r}}}function v(e,t){return{kind:"validation",type:"min_length",reference:v,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&r.value.length<this.requirement&&x(this,"length",r,i,{received:`${r.value.length}`}),r}}}function re(e,t){return{kind:"validation",type:"min_value",reference:re,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!(r.value>=this.requirement)&&x(this,"value",r,i,{received:r.value instanceof Date?r.value.toJSON():te(r.value)}),r}}}function Oe(e,t){return{kind:"validation",type:"regex",reference:Oe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,i){return r.typed&&!this.requirement.test(r.value)&&x(this,"format",r,i),r}}}function F(e){return{kind:"validation",type:"url",reference:F,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)&&x(this,"URL",t,r),t}}}function Ot(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function be(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function ne(){return{kind:"schema",type:"any",reference:ne,expects:"any",async:!1,get"~standard"(){return O(this)},"~run"(e){return e.typed=!0,e}}}function R(e,t){return{kind:"schema",type:"array",reference:R,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(Array.isArray(a)){r.typed=!0,r.value=[];for(let s=0;s<a.length;s++){let c=a[s],m=this.item["~run"]({value:c},i);if(m.issues){let l={type:"array",origin:"value",input:a,key:s,value:c};for(let h of m.issues)h.path?h.path.unshift(l):h.path=[l],r.issues?.push(h);if(r.issues||(r.issues=m.issues),i.abortEarly){r.typed=!1;break}}m.typed||(r.typed=!1),r.value.push(m.value)}}else x(this,"type",r,i);return r}}}function C(e){return{kind:"schema",type:"boolean",reference:C,expects:"boolean",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:x(this,"type",t,r),t}}}function Je(e,t){return{kind:"schema",type:"custom",reference:Je,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return this.check(r.value)?r.typed=!0:x(this,"type",r,i),r}}}function ce(e,t){return{kind:"schema",type:"literal",reference:ce,expects:te(e),async:!1,literal:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===this.literal?r.typed=!0:x(this,"type",r,i),r}}}function Qe(e,t){return{kind:"schema",type:"loose_object",reference:Qe,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let s in this.entries){let c=this.entries[s];if(s in a||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){let m=s in a?a[s]:be(c),l=c["~run"]({value:m},i);if(l.issues){let h={type:"object",origin:"value",input:a,key:s,value:m};for(let p of l.issues)p.path?p.path.unshift(h):p.path=[h],r.issues?.push(p);if(r.issues||(r.issues=l.issues),i.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[s]=l.value}else if(c.fallback!==void 0)r.value[s]=Ot(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(x(this,"key",r,i,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:a,key:s,value:a[s]}]}),i.abortEarly))break}if(!r.issues||!i.abortEarly)for(let s in a)Dt(a,s)&&!(s in this.entries)&&(r.value[s]=a[s])}else x(this,"type",r,i);return r}}}function et(e){return{kind:"schema",type:"never",reference:et,expects:"never",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return x(this,"type",t,r),t}}}function _(e,t){return{kind:"schema",type:"nullable",reference:_,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return r.value===null&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function G(e,t){return{kind:"schema",type:"nullish",reference:G,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return O(this)},"~run"(r,i){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function U(e){return{kind:"schema",type:"number",reference:U,expects:"number",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:x(this,"type",t,r),t}}}function g(e,t){return{kind:"schema",type:"object",reference:g,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a=r.value;if(a&&typeof a=="object"){r.typed=!0,r.value={};for(let s in this.entries){let c=this.entries[s];if(s in a||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){let m=s in a?a[s]:be(c),l=c["~run"]({value:m},i);if(l.issues){let h={type:"object",origin:"value",input:a,key:s,value:m};for(let p of l.issues)p.path?p.path.unshift(h):p.path=[h],r.issues?.push(p);if(r.issues||(r.issues=l.issues),i.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[s]=l.value}else if(c.fallback!==void 0)r.value[s]=Ot(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(x(this,"key",r,i,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:a,key:s,value:a[s]}]}),i.abortEarly))break}}else x(this,"type",r,i);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 O(this)},"~run"(r,i){return r.value===void 0&&(this.default!==void 0&&(r.value=be(this,r,i)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,i)}}}function S(e,t){return{kind:"schema",type:"picklist",reference:S,expects:Xe(e.map(te),"|"),async:!1,options:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){return this.options.includes(r.value)?r.typed=!0:x(this,"type",r,i),r}}}function I(e,t,r){return{kind:"schema",type:"record",reference:I,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return O(this)},"~run"(i,a){let s=i.value;if(s&&typeof s=="object"){i.typed=!0,i.value={};for(let c in s)if(Dt(s,c)){let m=s[c],l=this.key["~run"]({value:c},a);if(l.issues){let p={type:"object",origin:"key",input:s,key:c,value:m};for(let b of l.issues)b.path=[p],i.issues?.push(b);if(i.issues||(i.issues=l.issues),a.abortEarly){i.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let p={type:"object",origin:"value",input:s,key:c,value:m};for(let b of h.issues)b.path?b.path.unshift(p):b.path=[p],i.issues?.push(b);if(i.issues||(i.issues=h.issues),a.abortEarly){i.typed=!1;break}}(!l.typed||!h.typed)&&(i.typed=!1),l.typed&&(i.value[l.value]=h.value)}}else x(this,"type",i,a);return i}}}function o(e){return{kind:"schema",type:"string",reference:o,expects:"string",async:!1,message:e,get"~standard"(){return O(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:x(this,"type",t,r),t}}}function Pt(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function Ee(e,t){return{kind:"schema",type:"union",reference:Ee,expects:Xe(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return O(this)},"~run"(r,i){let a,s,c;for(let m of this.options){let l=m["~run"]({value:r.value},i);if(l.typed)if(l.issues)s?s.push(l):s=[l];else{a=l;break}else c?c.push(l):c=[l]}if(a)return a;if(s){if(s.length===1)return s[0];x(this,"type",r,i,{issues:Pt(s)}),r.typed=!0}else{if(c?.length===1)return c[0];x(this,"type",r,i,{issues:Pt(c)})}return r}}}function J(){return{kind:"schema",type:"unknown",reference:J,expects:"unknown",async:!1,get"~standard"(){return O(this)},"~run"(e){return e.typed=!0,e}}}function tt(e,t,r){return{kind:"schema",type:"variant",reference:tt,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return O(this)},"~run"(i,a){let s=i.value;if(s&&typeof s=="object"){let c,m=0,l=this.key,h=[],p=n((b,E)=>{for(let w of b.options){if(w.type==="variant")p(w,new Set(E).add(w.key));else{let D=!0,L=0;for(let P of E){let N=w.entries[P];if(P in s?N["~run"]({typed:!1,value:s[P]},{abortEarly:!0}).issues:N.type!=="exact_optional"&&N.type!=="optional"&&N.type!=="nullish"){D=!1,l!==P&&(m<L||m===L&&P in s&&!(l in s))&&(m=L,l=P,h=[]),l===P&&h.push(w.entries[P].expects);break}L++}if(D){let P=w["~run"]({value:s},a);(!c||!c.typed&&P.typed)&&(c=P)}}if(c&&!c.issues)break}},"parseOptions");if(p(this,new Set([this.key])),c)return c;x(this,"type",i,a,{input:s[l],expected:Xe(h,"|"),path:[{type:"object",origin:"value",input:s,key:l,value:s[l]}]})}else x(this,"type",i,a);return i}}}function rt(e,t,r){let i=e["~run"]({value:t},Ye(r));if(i.issues)throw new Ze(i.issues);return i.value}function f(...e){return{...e[0],pipe:e,get"~standard"(){return O(this)},"~run"(t,r){for(let i of e)if(i.kind!=="metadata"){if(t.issues&&(i.kind==="schema"||i.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=i["~run"](t,r))}return t}}}function Se(e,t,r){let i=e["~run"]({value:t},Ye(r));return{typed:i.typed,success:!i.issues,output:i.value,issues:i.issues}}var Ke,Zn,Qn,ti,Ze,ni,bo,ii,j=u(()=>{n(Ye,"getGlobalConfig");n(Jn,"getGlobalMessage");n(ei,"getSchemaMessage");n(ri,"getSpecificMessage");n(te,"_stringify");n(x,"_addIssue");n(O,"_getStandardProps");n(Dt,"_isValidObjectKey");n(Xe,"_joinExpects");Ze=class extends Error{static{n(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},ni=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,bo=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"),ii=/^\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;n(K,"email");n($,"isoTimestamp");n(Pe,"length");n(De,"maxLength");n(ue,"maxValue");n(v,"minLength");n(re,"minValue");n(Oe,"regex");n(F,"url");n(Ot,"getFallback");n(be,"getDefault");n(ne,"any");n(R,"array");n(C,"boolean");n(Je,"custom");n(ce,"literal");n(Qe,"looseObject");n(et,"never");n(_,"nullable");n(G,"nullish");n(U,"number");n(g,"object");n(d,"optional");n(S,"picklist");n(I,"record");n(o,"string");n(Pt,"_subIssues");n(Ee,"union");n(J,"unknown");n(tt,"variant");n(rt,"parse");n(f,"pipe");n(Se,"safeParse")});var xe,nt,xo,it=u(()=>{"use strict";xe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},nt={PAYMENT:"payment",SUBSCRIPTION:"subscription"},xo={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});var To,Ro,Co,Io,Po,Do,oi,si,ai,Oo,_o,No,_t=u(()=>{"use strict";j();it();To=g({userId:d(o()),productId:d(o()),priceId:o(),successUrl:f(o(),F()),cancelUrl:f(o(),F()),customerEmail:d(f(o(),K())),userEmail:d(f(o(),K())),metadata:d(I(o(),o())),allowPromotionCodes:d(C()),mode:d(S([nt.PAYMENT,nt.SUBSCRIPTION]))}),Ro=g({sessionId:o(),sessionUrl:_(f(o(),F()))}),Co=g({userId:o(),tier:o(),status:S(Object.values(xe)),subscriptionId:_(o()),customerId:o(),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$())}),Io=g({tier:o(),subscriptionId:_(o()),customerId:o(),status:S(Object.values(xe)),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$()),isDefault:d(C())}),Po=g({id:o(),type:o(),data:g({object:ne()}),created:f(o(),$())}),Do=Qe({userId:d(o()),firebaseUid:d(o()),productType:d(o())}),oi=g({type:ce("StripePayment"),name:f(o(),v(1,"Product name is required")),description:d(o()),price:o(),currency:d(f(o(),Pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(o(),v(1,"Stripe price ID is required")),tier:f(o(),v(1,"Tier is required")),duration:f(o(),v(1,"Duration is required")),allowPromotionCodes:d(C()),metadata:d(I(o(),o()))}),si=g({type:ce("StripeSubscription"),name:f(o(),v(1,"Product name is required")),description:d(o()),price:o(),currency:d(f(o(),Pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(o(),v(1,"Stripe price ID is required")),tier:f(o(),v(1,"Tier is required")),duration:S(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:d(C()),metadata:d(I(o(),o()))}),ai=tt("type",[oi,si]),Oo=I(o(),ai),_o=I(o(),g({name:o(),price:o(),currency:o(),description:d(o()),features:d(R(o())),priceId:o(),allowPromotionCodes:d(C())})),No=I(o(),g({type:S(["StripePayment","StripeSubscription"]),name:o(),price:U(),currency:o(),priceId:o(),tier:o(),duration:o(),description:d(o()),metadata:d(I(o(),o())),allowPromotionCodes:d(C())}))});var Nt=u(()=>{"use strict"});var ot=u(()=>{"use strict";it();_t();Nt()});var $o,ui,Go,Ft=u(()=>{"use strict";j();We();ot();$o=g({id:o(),email:d(_(f(o(),K()))),displayName:d(_(o())),photoURL:d(_(f(o(),F()))),emailVerified:d(C()),lastLoginAt:d(o()),providerData:d(R(g({providerId:o(),uid:o(),email:d(_(f(o(),K()))),displayName:d(_(o())),photoURL:d(_(f(o(),F()))),phoneNumber:d(_(o()))}))),role:d(S(Object.values(Z))),customClaims:d(I(o(),ne()))}),ui=g({userId:o(),tier:S(Object.values(Rt)),status:S(Object.values(xe)),isActive:d(C()),features:d(R(o())),subscriptionId:_(o()),customerId:o(),subscriptionEnd:_(f(o(),$())),cancelAtPeriodEnd:C(),updatedAt:f(o(),$())}),Go=g({role:d(S(Object.values(Z))),subscription:d(ui),features:d(R(S(Object.values(Ct)))),permissions:d(R(S(Object.values(It)))),githubAccess:d(g({username:d(o()),teamAccess:d(R(o())),repoAccess:d(R(o()))}))})});var Ut=u(()=>{"use strict"});var Mt=u(()=>{"use strict"});var Lt=u(()=>{"use strict";We();Ft();Ut();Mt()});var Bt=u(()=>{"use strict"});var qt=u(()=>{"use strict"});var ie,_e=u(()=>{"use strict";ie={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var ns,Vt=u(()=>{"use strict";_e();ns={EQ:ie.EQ,NEQ:ie.NEQ,LT:ie.LT,LTE:ie.LTE,GT:ie.GT,GTE:ie.GTE}});var jt=u(()=>{"use strict"});var $t=u(()=>{"use strict"});var cs,ls,ps,ds,fs,Gt=u(()=>{"use strict";j();_e();cs=g({collection:f(o(),v(1,"Collection name is required")),data:I(o(),J()),idempotencyKey:d(o())}),ls=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required"))}),ps=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required")),data:I(o(),J()),merge:d(C(),!1)}),ds=g({collection:f(o(),v(1,"Collection name is required")),id:f(o(),v(1,"Entity ID is required"))}),fs=g({collection:f(o(),v(1,"Collection name is required")),limit:d(f(U(),re(1),ue(1e3)),1e3),offset:d(f(U(),re(0)),0),orderBy:d(o()),orderDirection:d(S(["asc","desc"]),"desc"),where:d(R(g({field:o(),operator:S(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:J()})))})});var Ht=u(()=>{"use strict"});var zt=u(()=>{"use strict";qt();Vt();jt();_e();$t();Gt();Ht()});var ke,Ne,st,A,Wt=u(()=>{"use strict";ke={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"},Ne={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},st={[ke.PERMISSION_DENIED]:{type:Ne.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ke.NOT_FOUND]:{type:Ne.NOT_FOUND,message:"The requested resource was not found"},[ke.ALREADY_EXISTS]:{type:Ne.ALREADY_EXISTS,message:"The resource already exists"},[ke.INVALID_ARGUMENT]:{type:Ne.VALIDATION_ERROR,message:"Invalid argument provided"}},A=class e extends Error{static{n(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=ke.INTERNAL,i){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=i?.details,this.source=i?.source,this.originalError=i?.originalError,this.context=i?.context,this.displayable=i?.displayable??!0,this.userMessageProvided=i?.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 Kt=u(()=>{"use strict";Wt()});var Yt=u(()=>{"use strict"});var Xt=u(()=>{"use strict"});var Zt=u(()=>{"use strict"});var Jt=u(()=>{"use strict"});var Qt=u(()=>{"use strict"});var er=u(()=>{"use strict"});var tr=u(()=>{"use strict";Xt();Zt();Jt();Qt();er()});var rr=u(()=>{"use strict"});var nr=u(()=>{"use strict";rr()});var ir=u(()=>{"use strict"});var or=u(()=>{"use strict";ir()});var sr=u(()=>{"use strict"});var ar=u(()=>{"use strict";sr()});var ur=u(()=>{"use strict"});var cr=u(()=>{"use strict";ur()});var lr=u(()=>{"use strict"});var pr=u(()=>{"use strict"});var dr=u(()=>{"use strict"});var fr=u(()=>{"use strict";lr();pr();dr()});var mr=u(()=>{"use strict"});var gr=u(()=>{"use strict";mr()});var yr,at=u(()=>{"use strict";yr=["pull","push","admin","maintain","triage"]});var hr=u(()=>{"use strict"});var ut,li,Js,Qs,ea,ta,ra,na,ia,vr=u(()=>{"use strict";j();at();ut=g({owner:f(o(),v(1,"Repository owner is required")),repo:f(o(),v(1,"Repository name is required"))}),li=S([...yr]),Js=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut,permission:d(li,"push"),customClaims:d(I(o(),ne()))}),Qs=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut}),ea=g({userId:f(o(),v(1,"User ID is required")),githubUsername:f(o(),v(1,"GitHub username is required")),repoConfig:ut}),ta=g({provider:o(),purpose:S(["authentication","api-access"]),code:f(o(),v(1,"Authorization code is required")),redirectUri:f(o(),F("Valid redirect URI is required")),codeVerifier:d(o()),state:d(o()),instance:d(f(o(),F()))}),ra=g({provider:o(),refreshToken:f(o(),v(1,"Refresh token is required")),redirectUri:f(o(),F("Valid redirect URI is required"))}),na=g({provider:o()}),ia=g({userId:f(o(),v(1,"User ID is required"))})});var br=u(()=>{"use strict";at();hr();vr()});var Er=u(()=>{"use strict"});var Sr,pi,Fe,di,fi,mi,gi,pa,da,xr=u(()=>{"use strict";j();Sr=g({name:o(),color:o(),icon:o(),customParameters:d(I(o(),o())),button:g({backgroundColor:o(),textColor:o(),borderColor:o(),hoverBackgroundColor:o(),focusOutlineColor:o(),fontWeight:d(o(),"500"),textKey:d(o())})}),pi=g({...Sr.entries,type:S(["auth","both"]),scopes:d(R(o())),firebaseProviderId:d(o())}),Fe=Ee([ce(""),f(o(),F())]),di=g({authUrl:Fe,tokenUrl:Fe,profileUrl:Fe,revokeUrl:d(Fe)}),fi=g({authentication:d(R(o())),"api-access":R(o())}),mi=d(g({pkce:d(C(),!1),codeChallengeMethod:d(S(["S256","plain"]),"S256")})),gi=g({...Sr.entries,type:S(["oauth","both"]),scopes:fi,endpoints:di,capabilities:mi}),pa=I(o(),pi),da=I(o(),gi)});var kr=u(()=>{"use strict"});var wr=u(()=>{"use strict";Er();xr();kr()});var Ar=u(()=>{"use strict"});var Tr=u(()=>{"use strict"});var Rr=u(()=>{"use strict";Ar();Tr()});var Cr=u(()=>{"use strict"});var Ir=u(()=>{"use strict";Cr()});var Pr=u(()=>{"use strict"});var Dr=u(()=>{"use strict";Pr()});var Or,ka,_r=u(()=>{"use strict";Or={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},ka={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Or.ANALYTICS},marketing:{requiresConsent:Or.MARKETING}}});var Nr=u(()=>{"use strict";_r()});var Fr=u(()=>{"use strict"});var Ur=u(()=>{"use strict"});var Mr=u(()=>{"use strict";Fr();Ur()});var Y=u(()=>{"use strict";Lt();ot();Bt();zt();Kt();Yt();tr();nr();or();ar();cr();fr();gr();br();wr();Rr();Ir();Dr();Nr();Mr()});var we=u(()=>{"use strict";Y()});function Lr(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 ct=u(()=>{"use strict";n(Lr,"detectErrorSource")});function X(e){return(t,r)=>{if(t instanceof A)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new A(r||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let i;e.extractErrorCode?i=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(i=t.code);let a=e.defaultErrorCode;i&&e.errorCodeMapping&&i in e.errorCodeMapping&&(a=e.errorCodeMapping[i]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),i&&e.friendlyMessageMapping&&i in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[i]),s||(s=e.defaultErrorMessage);let c;return e.processMetadata?c=e.processMetadata(t):(c={originalError:t},i&&(c.originalCode=i)),"originalError"in c||(c.originalError=t),new A(r||s,a,{details:c,source:e.errorSource})}}var Ue,lt=u(()=>{"use strict";we();n(X,"createErrorHandler");Ue={"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 dt(e,t,r){return e instanceof A?e:(Br[t]||Br.unknown)(e,r)}var le,yi,pt,Q,hi,vi,Br,ft=u(()=>{"use strict";j();Y();we();lt();le={"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."},yi={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"},pt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Q={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",...Ue},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",...Ue},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(yi).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:n(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:n(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:Ue,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:le.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:n(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:le["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:le.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:n(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},hi=n(e=>e instanceof Ze?new A(le["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):X(Q.validation)(e),"handleValidationError"),vi=n(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in pt){let t=e,r=pt[t.type]||"unknown";return new A(t.message||le[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&st[e.code]){let t=e,r=st[t.code];if(r){let i=pt[r.type]||"unknown";return new A(r.message||le[i],i,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return X(Q.entity)(e)},"handleEntityError"),Br={auth:X(Q.auth),oauth:X(Q.oauth),api:X(Q.api),firebase:X(Q.firebase),ui:X(Q.ui),validation:hi,entity:vi,unknown:X(Q.unknown)};n(dt,"mapToDoNotDevError")});function qr(e,t,r={}){let i=globalThis.Sentry;i&&i.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,c])=>{if(typeof c!="function"&&s!=="originalError")try{a.setExtra(s,c)}catch{a.setExtra(s,`[${typeof c}]`)}}),Object.entries(r).forEach(([s,c])=>{if(typeof c!="function")try{a.setExtra(`context.${s}`,c)}catch{a.setExtra(`context.${s}`,`[${typeof c}]`)}}),(e.details?.userId||r.userId)&&a.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),i.captureException(e)})}var mt=u(()=>{"use strict";n(qr,"captureErrorToSentry")});function bi(){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 T(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:i,context:a={},log:s=!0,reportToSentry:c=!0,showNotification:m=!1,severity:l="error"}=r,h=Lr(e),p=e instanceof A?e:dt(e,h,i);if(i&&!p.userMessageProvided&&(p.message.includes("Error")||p.message.includes("Failed")||p.message.length<10?p=new A(i,p.code,{details:{...p.details,originalMessage:p.message},source:h,userMessageProvided:!0}):p=new A(p.message,p.code,{details:{...p.details,userMessage:i},source:h,userMessageProvided:!0})),s){let b=bi()||typeof window<"u"&&window.__DNDEV_DEBUG,E={code:p.code,message:p.message,source:h};switch(l){case"warning":console.warn(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;case"info":console.info(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;case"success":console.log(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details}:E);break;default:console.error(`[DoNotDev] ${p.code}: ${p.message}`,b?{...E,details:p.details,stack:p.stack}:E)}}return c&&qr(p,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),p}var Vr=u(()=>{"use strict";we();ct();ft();mt();n(bi,"isDev");n(T,"handleError")});var Me=u(()=>{"use strict";we();Vr();ct();ft();mt();lt()});var jr=u(()=>{"use strict";Me()});var $r=u(()=>{"use strict";Me()});var Gr=u(()=>{"use strict";jr();$r()});var Hr=u(()=>{"use strict"});var zr=u(()=>{"use strict"});var Wr=u(()=>{"use strict"});var Kr=u(()=>{"use strict"});var Yr=u(()=>{"use strict"});var Xr=u(()=>{"use strict"});var Zr=u(()=>{"use strict"});var Jr=u(()=>{"use strict"});var Qr=u(()=>{"use strict"});var Zu,gt=u(()=>{"use strict";Y();Zu={[Z.GUEST]:0,[Z.USER]:1,[Z.ADMIN]:2,[Z.SUPER]:3}});var en=u(()=>{"use strict";Y()});function tn(e){if(!yt)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let t=yt[e];if(!t)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return t}function rn(e){return!!yt?.[e]}var yt,nn=u(()=>{"use strict";yt=null;n(tn,"getProvider");n(rn,"hasProvider")});function on(e,...t){let r=null,i=!1;return n(function(){if(r!==null)return r;if(i)throw new Error("Circular dependency detected in singleton initialization");i=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{i=!1}},"getInstance")}var sn=u(()=>{"use strict";n(on,"createSingleton")});var an=u(()=>{"use strict"});var ht=u(()=>{"use strict";gt()});var un=u(()=>{"use strict";ht()});var cn=u(()=>{"use strict"});var ln=u(()=>{"use strict"});var pn=u(()=>{"use strict";un();cn();ht();ln()});var dn=u(()=>{"use strict"});var fn=u(()=>{"use strict";dn()});var mn=u(()=>{"use strict"});var gn=u(()=>{"use strict";Gr();Hr();zr();Wr();Kr();Me();Yr();Xr();Zr();Jr();Qr();gt();en();nn();sn();an();pn();fn();mn()});var yn=u(()=>{"use strict"});var hn=u(()=>{"use strict"});var vn=u(()=>{"use strict"});var ee=u(()=>{gn();yn();hn();vn()});var bn=u(()=>{"use strict"});var En=u(()=>{"use strict"});function y(e,t){Si.set(e,t)}function k(e,t){return t?e:G(e)}function Li(){y("text",Le),y("textarea",Le),y("richtext",Le),y("color",Le),y("email",xi),y("password",ki),y("url",wi),y("tel",_i),y("iban",Ni),y("number",pe),y("currency",pe),y("price",Mi),y("range",pe),y("year",pe),y("rating",pe),y("duration",pe),y("boolean",Sn),y("checkbox",Sn),y("gdprConsent",Ui),y("date",de),y("datetime-local",de),y("time",de),y("week",de),y("month",de),y("timestamp",de),y("file",xn),y("files",kn),y("document",xn),y("documents",kn),y("image",Ai),y("images",Ti),y("geopoint",Ri),y("address",Ci),y("map",Ii),y("array",Pi),y("select",vt),y("multiselect",Di),y("radio",vt),y("combobox",vt),y("switch",Fi),y("reference",Oi),y("hidden",bt),y("avatar",bt),y("badge",bt),y("submit",wn),y("reset",wn)}var Si,Le,xi,ki,wi,pe,Sn,de,An,xn,kn,Tn,Ai,Ti,Ri,Ci,Ii,Pi,vt,Di,Oi,bt,_i,Ni,wn,Fi,Ui,Mi,Et=u(()=>{"use strict";j();Si=new Map;n(y,"registerSchemaGenerator");n(k,"applyRequired");Le=n(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(v(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(Oe(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?f(o(),...t):o();return k(r,e.validation?.required)},"textSchema"),xi=n(e=>{let t=f(o(),K("Invalid email address"));return k(t,e.validation?.required)},"emailSchema"),ki=n(e=>{let t=e.validation?.minLength!==void 0?f(o(),v(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):o();return k(t,e.validation?.required)},"passwordSchema"),wi=n(e=>{let t=f(o(),F("Invalid URL"));return k(t,e.validation?.required)},"urlSchema"),pe=n(e=>{let t=[];e.validation?.min!==void 0&&t.push(re(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(ue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?f(U(),...t):U();return k(r,e.validation?.required)},"numberSchema"),Sn=n(e=>{let t=C();return k(t,e.validation?.required)},"booleanSchema"),de=n(e=>{let t=f(o(),$("Invalid date format"));return k(t,e.validation?.required)},"dateSchema"),An=g({url:o(),filename:o(),size:U(),mimeType:G(o()),uploadedAt:G(o())}),xn=n(e=>{let t=_(An);return k(t,e.validation?.required)},"fileSchema"),kn=n(e=>{let t=R(An);return k(t,e.validation?.required)},"filesSchema"),Tn=g({fullUrl:o(),thumbUrl:o()}),Ai=n(e=>k(Tn,e.validation?.required),"pictureSchema"),Ti=n(e=>{let t=R(Tn);return k(t,e.validation?.required)},"picturesSchema"),Ri=n(e=>{let t=g({lat:U(),lng:U()});return k(t,e.validation?.required)},"geopointSchema"),Ci=n(e=>{let t=g({formatted_address:o(),latitude:U(),longitude:U(),street_number:G(o()),route:G(o()),locality:G(o()),administrative_area_level_1:G(o()),administrative_area_level_2:G(o()),country:G(o()),postal_code:G(o())});return k(t,e.validation?.required)},"addressSchema"),Ii=n(e=>{let t=I(o(),J());return k(t,e.validation?.required)},"mapSchema"),Pi=n(e=>{let t=R(J());return k(t,e.validation?.required)},"arraySchema"),vt=n(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(s=>s.value),a=S(i);return k(a,e.validation?.required)}let r=Ee([o(),U()]);return k(r,e.validation?.required)},"selectSchema"),Di=n(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(s=>s.value),a=R(S(i));return k(a,e.validation?.required)}let r=R(o());return k(r,e.validation?.required)},"multiselectSchema"),Oi=n(e=>{let t=f(o(),v(1,"Invalid ID format"));return k(t,e.validation?.required)},"referenceSchema"),bt=n(e=>{let t=o();return k(t,e.validation?.required)},"stringSchema"),_i=n(e=>{let t=o();return k(t,e.validation?.required)},"telSchema"),Ni=n(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,i=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",a=[];if(t!==void 0&&a.push(v(t,`IBAN must be at least ${t} characters`)),r!==void 0&&a.push(De(r,`IBAN must not exceed ${r} characters`)),i){let c=typeof i=="string"?new RegExp(i):i;a.push(Oe(c,"Invalid IBAN format"))}let s=a.length>0?f(o(),...a):o();return k(s,e.validation?.required)},"ibanSchema"),wn=n(()=>et(),"neverSchema"),Fi=n(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let i=[t.checkedValue,t.uncheckedValue],a=S(i);return k(a,e.validation?.required)}let r=C();return k(r,e.validation?.required)},"switchSchema"),Ui=n(e=>Je(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"),Mi=n(e=>{let t=g({amount:U(),currency:d(o()),vatIncluded:d(C()),discountPercent:d(f(U(),re(0),ue(100)))});return k(t,e.validation?.required)},"priceSchema");n(Li,"registerBuiltinSchemas");Li()});var St=u(()=>{"use strict";ee()});var xt=u(()=>{"use strict";ee()});var Rn=u(()=>{"use strict";St();xt()});var Cn=u(()=>{"use strict";En();Et();St();Rn();xt()});var In=u(()=>{"use strict";ee()});var Pn,Dn,Ul,On,Be=u(()=>{"use strict";Y();Pn=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],Dn=["id","createdAt","updatedAt","createdById","updatedById"],Ul=[...Dn,"status"],On={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Pn]}},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 _n=u(()=>{"use strict";Y();ee();Be()});var Nn=u(()=>{"use strict";Y();ee();Et();Be()});var Fn=u(()=>{"use strict"});var Un=u(()=>{"use strict"});var Mn=u(()=>{"use strict";Cn();In();Be();_n();Nn();Fn();Un()});var Ln=u(()=>{"use strict";bn();Mn()});var q=u(()=>{ee();Y();Ln();ee()});import{initializeApp as Bn,getApps as qi,cert as Vi}from"firebase-admin/app";import{getAuth as ji}from"firebase-admin/auth";import{getFirestore as $i}from"firebase-admin/firestore";import{getFunctions as Gi}from"firebase-admin/functions";function Hi(){let e=qi(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=Bn({credential:Vi({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=Bn():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:ji(t),firestore:$i(t),functions:Gi(t)}}async function Ae(){let e=kt();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function M(){let e=kt();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function oe(){let e=kt();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}var kt,qe=u(()=>{"use strict";q();n(Hi,"initializeFirebaseAdminServices");kt=on(Hi);n(Ae,"getFirebaseAdminApp");n(M,"getFirebaseAdminAuth");n(oe,"getFirebaseAdminFirestore")});var qn=u(()=>{"use strict";q();qe()});var Ve,Pp,fe,Dp,Te=u(()=>{"use strict";q();qe();Ve={async getServerAdmin(){try{return Ae()}catch(e){throw T(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return oe()}catch(e){throw T(e,"Error getting Admin Firestore")}},async generateServerId(){return(await Ve.getServerFirestore()).collection("_").doc().id}},Pp=Ve.getServerAdmin,fe=Ve.getServerFirestore,Dp=Ve.generateServerId});function zi(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw T(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 T(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw T(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw T(t,"Failed to convert to ISO string")}}function Wi(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function me(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,i=r.data();return{id:r.id,...me(i)}}if(Array.isArray(e))return e.map(r=>me(r));if(Wi(e))return zi(e);if(typeof e=="object"&&e!==null){let r={};for(let[i,a]of Object.entries(e))r[i]=me(a);return r}return e}function Re(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>Re(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[i,a]of Object.entries(e))t.includes(i)||a!==void 0&&(r[i]=Re(a,t));return r}return e}var je=u(()=>{"use strict";q();n(zi,"firestoreToISOString");n(Wi,"isTimestamp");n(me,"transformFirestoreData");n(Re,"prepareForFirestore")});var ge,z,ye,Bp,qp,Vp,jp,$p,Gp,Vn=u(()=>{"use strict";j();q();Te();je();ge=typeof window<"u",z={async batchWrite(e,t,r,i,a={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:s="id",generateIds:c=!0,maxBatchSize:m=450,removeFields:l=[],validate:h=!!i}=a,p={successes:0,failures:0,failedItems:[]};try{let b=[],E=await fe(),w=E.batch(),D=0;for(let P=0;P<t.length;P++){let N=t[P];if(!N){p.failures++,p.failedItems?.push({index:P,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!N[s])throw T(new Error(`Missing ID for delete operation (${s})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:s,operation:r}});let B=E.collection(e).doc(N[s]);w.delete(B)}else{if(h&&i)try{rt(i,N)}catch(Yn){throw T(Yn,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:s,itemId:N[s]}})}let B=N[s];if(!B&&r==="create"&&c)B=E.collection(e).doc().id,N={...N,[s]:B};else if(!B)throw T(new Error(`Missing ID for ${r} operation (${s})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:s,operation:r}});let ze=[s,...l],ae=Re(N,ze),Tt=E.collection(e).doc(B);r==="create"?w.create(Tt,ae):r==="update"&&w.update(Tt,ae)}D++,D>=m&&(b.push({batch:w,size:D}),w=E.batch(),D=0)}catch(B){p.failures++,p.failedItems?.push({index:P,error:B instanceof Error?B:new Error(String(B))})}}D>0&&b.push({batch:w,size:D});let L=0;for(let{batch:P,size:N}of b){try{await P.commit(),p.successes+=N}catch(B){let ze=B instanceof Error?B:new Error(String(B));for(let ae=L;ae<L+N;ae++)p.failures++,p.failedItems?.push({index:ae,error:ze})}L+=N}return p}catch(b){throw T(b,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:p.successes+p.failures,successCount:p.successes,failureCount:p.failures}})}},async batchCreate(e,t,r,i={}){return z.batchWrite(e,t,"create",r,i)},async batchUpdate(e,t,r,i={}){return z.batchWrite(e,t,"update",r,i)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let i=r.idField||"id",a=t.map(s=>({[i]:s}));return z.batchWrite(e,a,"delete",void 0,r)}return z.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await fe()).runTransaction(e)}catch(t){throw T(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:i=30,transform:a=!0}=r;try{let s=[];for(let l=0;l<t.length;l+=i)s.push(t.slice(l,l+i));let c=s.map(async l=>{let b=await(await fe()).collection(e).where("__name__","in",l).get(),E=new Map;return b.forEach(w=>{E.set(w.id,w.data())}),l.map(w=>{let D=E.get(w);return D?a?me({id:w,...D}):{id:w,...D}:null})});return(await Promise.all(c)).flat()}catch(s){throw T(s,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},ye=n(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),Bp=ge?ye("batchWrite"):z.batchWrite,qp=ge?ye("batchCreate"):z.batchCreate,Vp=ge?ye("batchUpdate"):z.batchUpdate,jp=ge?ye("batchDelete"):z.batchDelete,$p=ge?ye("runTransaction"):z.runTransaction,Gp=ge?ye("bulkGet"):z.bulkGet});var jn=u(()=>{"use strict";q()});var $n=u(()=>{"use strict";q();Te();je();jn()});var $e=u(()=>{"use strict";q();Te()});var Gn=u(()=>{"use strict";q();$e();$e()});import{FieldValue as Cd,Query as Id,Timestamp as Pd}from"firebase-admin/firestore";var W=u(()=>{"use strict";qn();qe();Te();Vn();$n();Gn();$e();je()});q();function V(e){let t,r,i;if(e instanceof A)t=e.code,r=e.message,i=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",i={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,i=void 0}else t="internal",r=e instanceof Error?e.message:"An unexpected error occurred",i=void 0;throw new A(r,t,i?{details:i}:void 0)}n(V,"handleError");q();W();function Yi(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}n(Yi,"extractBearerToken");async function Xi(e,t){try{return t==="supabase"?await Zi(e):t==="firebase"?{uid:(await M().verifyIdToken(e)).uid}:rn("serverAuth")?{uid:(await tn("serverAuth").verifyToken(e)).uid}:{uid:(await M().verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}n(Xi,"verifyToken");async function Zi(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,i=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!i)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let a=t(r,i,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:c}=await a.auth.getUser(e);if(c||!s)throw new Error("Invalid or expired token");return{uid:s.id}}n(Zi,"verifySupabaseToken");async function Ge(e,t){let r=Yi(e.headers.authorization),{uid:i}=await Xi(r,t);return i}n(Ge,"verifyAuthToken");W();var Ji=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Vd(e){let t=new Set(e.allowedClaimKeys);for(let r of t)if(Ji.has(r))throw new Error(`Claim key "${r}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return n(async function(i,a){if(i.method!=="POST")return a.status(405).json({error:"Method not allowed"});try{let s=await Ge(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw V(new Error("customClaims must be an object"));let m=Object.keys(c).filter(b=>!t.has(b));if(m.length>0)throw V(new Error(`Claim keys not allowed: ${m.join(", ")}`));let p={...(await M().getUser(s)).customClaims||{},...c};return await M().setCustomUserClaims(s,p),a.status(200).json({success:!0,customClaims:p})}catch(s){throw V(s)}},"handler")}n(Vd,"createSetCustomClaimsHandler");import Qi from"stripe";q();W();var He=null;function eo(e){if(!e)throw new Error("Stripe API key is required");let t=process.env.STRIPE_API_VERSION||"2024-12-18.acacia";return He=new Qi(e,{apiVersion:t}),He}n(eo,"initStripe");function to(){if(!He){let e=process.env.STRIPE_SECRET_KEY;if(e)eo(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return He}n(to,"getStripe");var se=new Proxy({},{get(e,t){return to()[t]}});function he(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}n(he,"validateStripeEnvironment");j();W();import{logger as Hn}from"firebase-functions/v2";async function wt(e){try{await oe().collection("payment_metrics").doc().set({...e,recordedAt:new Date().toISOString()}),Hn.info("Payment metrics recorded",{operation:e.operation,status:e.status,userId:e.userId})}catch(t){Hn.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:e})}}n(wt,"recordPaymentMetrics");W();import{logger as zn}from"firebase-functions/v2";async function Wn(e,t){let r=oe(),i=r.collection("rateLimits").doc(e);try{let a=Date.now(),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return await r.runTransaction(async c=>{let m=await c.get(i);if(!m.exists){c.set(i,{attempts:1,windowStart:a,blockUntil:null,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return}let l=m.data();if(l.blockUntil&&a<l.blockUntil){s={allowed:!1,remaining:0,resetAt:new Date(l.blockUntil),blockRemainingSeconds:Math.ceil((l.blockUntil-a)/1e3)};return}if(a>=l.windowStart+t.windowMs){c.set(i,{attempts:1,windowStart:a,blockUntil:null,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(a+t.windowMs),blockRemainingSeconds:null};return}if(l.attempts>=t.maxAttempts){let h=a+t.blockDurationMs;c.update(i,{blockUntil:h,lastUpdated:a}),zn.warn("Rate limit exceeded (Firestore)",{key:e,attempts:l.attempts,blockUntil:new Date(h)}),s={allowed:!1,remaining:0,resetAt:new Date(h),blockRemainingSeconds:Math.ceil(t.blockDurationMs/1e3)};return}c.update(i,{attempts:l.attempts+1,lastUpdated:a}),s={allowed:!0,remaining:t.maxAttempts-(l.attempts+1),resetAt:new Date(l.windowStart+t.windowMs),blockRemainingSeconds:null}}),s}catch(a){return zn.error("Rate limit check failed",{key:e,error:a instanceof Error?a.message:String(a)}),{allowed:!0,remaining:t.maxAttempts,resetAt:null,blockRemainingSeconds:null}}}n(Wn,"checkRateLimitWithFirestore");var At={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};function ve(e,t,r,i,a,s){return async(c,m)=>{try{if(c.method!==e)return m.status(405).json({error:"Method not allowed"});let l=Se(t,c.body);if(!l.success)return m.status(400).json({error:`Validation failed: ${l.issues.map(L=>L.message).join(", ")}`});let h=l.output,p=await Ge(c,s),b=`${r}_${p}`,E=At[r]||At.api,w=await Wn(b,E);if(!w.allowed)return a?.audit({type:"rate_limit.exceeded",userId:p,metadata:{operation:r,remaining:0}}),m.status(429).json({error:`Rate limit exceeded. Try again in ${w.blockRemainingSeconds} seconds.`,retryAfter:w.blockRemainingSeconds});let D=await i(c,m,h,{uid:p});return D==null&&console.warn(`[${r}] businessLogic returned ${D} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await wt({operation:r,userId:p,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),D}catch(l){process.env.ENABLE_METRICS==="true"&&await wt({operation:r,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:l instanceof Error?l.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{V(l)}catch(h){let p=ro(h);return m.status(p.status).json({error:p.message})}return m.status(500).json({error:"Internal server error"})}}}n(ve,"createVercelBaseFunction");function ro(e){return e instanceof A?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[e.code]??500,message:e.message}:{status:500,message:"Internal server error"}}n(ro,"classifiedToHttp");async function Ce(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 s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},c={...a,subscription:s};await r.setCustomUserClaims(e,c)}n(Ce,"updateUserSubscription");j();W();q();async function Kn(e,t){he();let a=((await t.getUser(e)).customClaims||{}).subscription,s=a?.subscriptionId;if(!s)throw V(new Error("No active subscription found"));let c=await se.subscriptions.update(s,{cancel_at_period_end:!0}),l=["active","canceled","past_due","trialing","incomplete"].includes(c.status)?c.status:"incomplete";return await Ce(e,{tier:a?.tier||"free",status:l,subscriptionEnd:new Date(c.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:c.id,customerId:c.customer},t),{success:!0,endsAt:new Date(c.current_period_end*1e3).toISOString()}}n(Kn,"cancelUserSubscription");var no=g({userId:o()});async function io(e,t,r,i){let a=i.uid,c=await Kn(a,{async getUser(m){return M().getUser(m)},async setCustomUserClaims(m,l){await M().setCustomUserClaims(m,l)}});return t.status(200).json({success:c.success,cancelAtPeriodEnd:!0,endsAt:c.endsAt})}n(io,"cancelSubscriptionLogic");var oo=n(()=>ve("POST",no,"cancel_subscription",io),"cancelSubscription"),so=oo;j();W();var ao=g({userId:o(),newPriceId:o(),billingConfigKey:o()});async function uo(e,t,r,i,a){he();let s=i.uid,{newPriceId:c,billingConfigKey:m}=r,l=a[m];if(!l||l.type!=="StripeSubscription")throw V(new Error("Invalid plan"));if(l.priceId!==c)throw V(new Error("Price ID mismatch"));let p=(await M().getUser(s)).customClaims?.subscription?.subscriptionId;if(!p)throw V(new Error("No active subscription"));let b=await se.subscriptions.retrieve(p),E=await se.subscriptions.update(p,{items:[{id:b.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),D=["active","canceled","past_due","trialing","incomplete"].includes(E.status)?E.status:"incomplete";return await Ce(s,{tier:l.tier,status:D,subscriptionEnd:new Date(E.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:E.cancel_at_period_end,subscriptionId:E.id,customerId:E.customer},{async getUser(L){return M().getUser(L)},async setCustomUserClaims(L,P){await M().setCustomUserClaims(L,P)}}),t.status(200).json({success:!0,newTier:l.tier,newPrice:l.price})}n(uo,"changePlanLogic");var co=n(e=>ve("POST",ao,"change_plan",(t,r,i,a)=>uo(t,r,i,a,e)),"changePlan"),lo=co;j();W();var po=g({userId:o(),returnUrl:d(f(o(),F()))});async function fo(e,t,r,i){he();let a=i.uid,{returnUrl:s}=r,m=(await M().getUser(a)).customClaims?.subscription?.customerId;if(!m)throw V(new Error("No customer found"));let l=await se.billingPortal.sessions.create({customer:m,return_url:s||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:l.url})}n(fo,"createCustomerPortalLogic");var mo=n(()=>ve("POST",po,"create_customer_portal",fo),"createCustomerPortal"),go=mo;var Ie=process.env.FIREBASE_REGION||"europe-west1",Wf={region:Ie,memory:"1GiB",timeoutSeconds:60},Kf={region:Ie,memory:"512MiB",timeoutSeconds:30},Yf={region:Ie,memory:"256MiB",timeoutSeconds:20},Xf={region:Ie,memory:"256MiB",timeoutSeconds:15},Zf={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},Jf=n(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${Ie}`)},"validateEnvironment");W();async function rm(){return await Ae()}n(rm,"initializeFirebaseAdmin");async function nm(){return await Ae()}n(nm,"getFirebaseAdmin");export{Yf as AUTH_CONFIG,Zf as AVAILABLE_REGIONS,Xf as CRUD_CONFIG,Ie as FIREBASE_REGION,Wf as FUNCTION_CONFIG,Kf as STRIPE_CONFIG,so as cancelSubscription,lo as changePlan,go as createCustomerPortal,Vd as createSetCustomClaimsHandler,nm as getFirebaseAdmin,rm as initializeFirebaseAdmin,Ce as updateUserSubscription,Jf as validateEnvironment};
23
23
  //# sourceMappingURL=index.js.map