@donotdev/functions 0.1.0 → 0.1.1

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