@donotdev/functions 0.3.3 → 0.3.4

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 (29) hide show
  1. package/lib/chunks/{chunk-IO4MUTT6.js → chunk-6JBLL6ZX.js} +2 -2
  2. package/lib/chunks/{chunk-LJXSA7EP.js → chunk-6PXANFSJ.js} +2 -2
  3. package/lib/chunks/{chunk-7T2RZ5A4.js → chunk-CZ5IFNKD.js} +2 -2
  4. package/lib/chunks/{chunk-Y6BR2QOV.js → chunk-FGXZMPSY.js} +2 -2
  5. package/lib/chunks/{chunk-NP4Y2LAO.js → chunk-GIKHRVAH.js} +2 -2
  6. package/lib/chunks/{chunk-MJ5VZTLM.js → chunk-H5ZLI4H4.js} +2 -2
  7. package/lib/chunks/{chunk-4BJP372Z.js → chunk-ID7MUXVQ.js} +2 -2
  8. package/lib/chunks/{chunk-WJUL2W7Y.js → chunk-KVU7ZB5P.js} +2 -2
  9. package/lib/chunks/{chunk-CCEGC2T6.js → chunk-PTC62U6W.js} +2 -2
  10. package/lib/chunks/{monitoring-B2DYDCYC.js → monitoring-CRYSBHK2.js} +2 -2
  11. package/lib/chunks/{rateLimiter-JCBEG33M.js → rateLimiter-OPEHIYNW.js} +2 -2
  12. package/lib/chunks/{server-YXYTPMRF.js → server-BABJRPD3.js} +2 -2
  13. package/lib/firebase/index.js +1 -1
  14. package/lib/shared/index.js +1 -1
  15. package/lib/supabase/index.js +1 -1
  16. package/lib/vercel/api/index.js +1 -1
  17. package/package.json +3 -3
  18. /package/lib/chunks/{chunk-IO4MUTT6.js.map → chunk-6JBLL6ZX.js.map} +0 -0
  19. /package/lib/chunks/{chunk-LJXSA7EP.js.map → chunk-6PXANFSJ.js.map} +0 -0
  20. /package/lib/chunks/{chunk-7T2RZ5A4.js.map → chunk-CZ5IFNKD.js.map} +0 -0
  21. /package/lib/chunks/{chunk-Y6BR2QOV.js.map → chunk-FGXZMPSY.js.map} +0 -0
  22. /package/lib/chunks/{chunk-NP4Y2LAO.js.map → chunk-GIKHRVAH.js.map} +0 -0
  23. /package/lib/chunks/{chunk-MJ5VZTLM.js.map → chunk-H5ZLI4H4.js.map} +0 -0
  24. /package/lib/chunks/{chunk-4BJP372Z.js.map → chunk-ID7MUXVQ.js.map} +0 -0
  25. /package/lib/chunks/{chunk-WJUL2W7Y.js.map → chunk-KVU7ZB5P.js.map} +0 -0
  26. /package/lib/chunks/{chunk-CCEGC2T6.js.map → chunk-PTC62U6W.js.map} +0 -0
  27. /package/lib/chunks/{monitoring-B2DYDCYC.js.map → monitoring-CRYSBHK2.js.map} +0 -0
  28. /package/lib/chunks/{rateLimiter-JCBEG33M.js.map → rateLimiter-OPEHIYNW.js.map} +0 -0
  29. /package/lib/chunks/{server-YXYTPMRF.js.map → server-BABJRPD3.js.map} +0 -0
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a as r}from"./chunk-AYY7UXNI.js";var be={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"};var Ie={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},qe={[be.PERMISSION_DENIED]:{type:Ie.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[be.NOT_FOUND]:{type:Ie.NOT_FOUND,message:"The requested resource was not found"},[be.ALREADY_EXISTS]:{type:Ie.ALREADY_EXISTS,message:"The resource already exists"},[be.INVALID_ARGUMENT]:{type:Ie.VALIDATION_ERROR,message:"Invalid argument provided"}};function an(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}r(an,"hasCaptureStackTrace");var k=class e extends Error{static{r(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=be.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.userMessageProvided,this.name=this.constructor.name,an(Error)&&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 q={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Ce={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},ni={[q.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"]},[q.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[q.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}};var ri={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"}},ii=4,oi={"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"}};var we,un={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function $e(e){return!e&&!we?un:{lang:e?.lang??we?.lang,message:e?.message,abortEarly:e?.abortEarly??we?.abortEarly,abortPipeEarly:e?.abortPipeEarly??we?.abortPipeEarly}}r($e,"getGlobalConfig");var ln;function cn(e){return ln?.get(e)}r(cn,"getGlobalMessage");var pn;function dn(e){return pn?.get(e)}r(dn,"getSchemaMessage");var fn;function mn(e,t){return fn?.get(e)?.get(t)}r(mn,"getSpecificMessage");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}r(te,"_stringify");function E(e,t,n,o,a){let u=a&&"input"in a?a.input:n.value,l=a?.expected??e.expects??null,m=a?.received??te(u),d={kind:e.kind,type:e.type,input:u,expected:l,received:m,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",f=a?.message??e.message??mn(e.reference,d.lang)??(h?dn(d.lang):null)??o.message??cn(d.lang);f!==void 0&&(d.message=typeof f=="function"?f(d):f),h&&(n.typed=!1),n.issues?n.issues.push(d):n.issues=[d]}r(E,"_addIssue");function gn(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}r(gn,"_isSameValueZero");function ct(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}r(ct,"_isValidObjectKey");function Ge(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}r(Ge,"_joinExpects");function T(e){return e["~standard"]={version:1,vendor:"valibot",validate:r(t=>e["~run"]({value:t},$e()),"validate")},e}r(T,"_standardSchema");var Oe=class extends Error{static{r(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function ai(e){return e instanceof Oe}r(ai,"isValiError");var yn=/^[\w+-]+(?:\.[\w+-]+)*@[\da-zA-Z]+(?:[.-][\da-zA-Z]+)*\.[a-zA-Z]{2,}$/u,ui=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");var hn=/^\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;function Ee(e,t){return{kind:"validation",type:"check",reference:Ee,async:!1,expects:null,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement(n.value)&&E(this,"input",n,o),n}}}r(Ee,"check");function L(e){return{kind:"validation",type:"email",reference:L,expects:null,async:!1,requirement:yn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&E(this,"email",t,n),t}}}r(L,"email");function $(e){return{kind:"validation",type:"integer",reference:$,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&E(this,"integer",t,n),t}}}r($,"integer");function ce(e){return{kind:"validation",type:"iso_timestamp",reference:ce,async:!1,expects:null,requirement:hn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&E(this,"timestamp",t,n),t}}}r(ce,"isoTimestamp");function pe(e,t){return{kind:"validation",type:"length",reference:pe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length!==this.requirement&&E(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(pe,"length");function G(e,t){return{kind:"validation",type:"max_length",reference:G,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length>this.requirement&&E(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(G,"maxLength");function V(e,t){return{kind:"validation",type:"max_value",reference:V,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value<=this.requirement)&&E(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(V,"maxValue");function g(e,t){return{kind:"validation",type:"min_length",reference:g,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length<this.requirement&&E(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(g,"minLength");function C(e,t){return{kind:"validation",type:"min_value",reference:C,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value>=this.requirement)&&E(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(C,"minValue");function We(e){return{kind:"transformation",type:"raw_transform",reference:We,async:!1,"~run"(t,n){let o=e({dataset:t,config:n,addIssue:r(a=>E(this,a?.label??"input",t,n,a),"addIssue"),NEVER:null});return t.issues?t.typed=!1:t.value=o,t}}}r(We,"rawTransform");function B(e,t){return{kind:"validation",type:"regex",reference:B,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement.test(n.value)&&E(this,"format",n,o),n}}}r(B,"regex");function vn(e){return{kind:"transformation",type:"transform",reference:vn,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}r(vn,"transform");function P(e){return{kind:"validation",type:"url",reference:P,async:!1,expects:null,requirement(t){try{return URL.canParse?URL.canParse(t):(new URL(t),!0)}catch{return!1}},message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&E(this,"URL",t,n),t}}}r(P,"url");var bn={abortEarly:!0};function pt(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}r(pt,"getFallback");function xe(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}r(xe,"getDefault");function ne(){return T({kind:"schema",type:"any",reference:ne,expects:"any",async:!1,"~run"(e){return e.typed=!0,e}})}r(ne,"any");function y(e,t){return T({kind:"schema",type:"array",reference:y,expects:"Array",async:!1,item:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<a.length;u++){let l=a[u],m=this.item["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,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),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else E(this,"type",n,o);return n}})}r(y,"array");function S(e){return T({kind:"schema",type:"boolean",reference:S,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:E(this,"type",t,n),t}})}r(S,"boolean");function En(e,t){return T({kind:"schema",type:"custom",reference:En,expects:"unknown",async:!1,check:e,message:t,"~run"(n,o){return this.check(n.value)?n.typed=!0:E(this,"type",n,o),n}})}r(En,"custom");function He(e){return T({kind:"schema",type:"lazy",reference:He,expects:"unknown",async:!1,getter:e,"~run"(t,n){return this.getter(t.value)["~run"](t,n)}})}r(He,"lazy");function R(e,t){return T({kind:"schema",type:"literal",reference:R,expects:te(e),async:!1,literal:e,message:t,"~run"(n,o){return gn(n.value,this.literal)?n.typed=!0:E(this,"type",n,o),n}})}r(R,"literal");function Se(e,t){return T({kind:"schema",type:"loose_object",reference:Se,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=pt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(E(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}if(!n.issues||!o.abortEarly)for(let u in a)ct(a,u)&&!Object.prototype.hasOwnProperty.call(this.entries,u)&&(n.value[u]=a[u])}else E(this,"type",n,o);return n}})}r(Se,"looseObject");function Ke(e){return T({kind:"schema",type:"never",reference:Ke,expects:"never",async:!1,message:e,"~run"(t,n){return E(this,"type",t,n),t}})}r(Ke,"never");function xn(e){return T({kind:"schema",type:"null",reference:xn,expects:"null",async:!1,message:e,"~run"(t,n){return t.value===null?t.typed=!0:E(this,"type",t,n),t}})}r(xn,"null_");function w(e,t){return T({kind:"schema",type:"nullable",reference:w,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===null&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(w,"nullable");function N(e,t){return T({kind:"schema",type:"nullish",reference:N,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(N,"nullish");function x(e){return T({kind:"schema",type:"number",reference:x,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:E(this,"type",t,n),t}})}r(x,"number");function p(e,t){return T({kind:"schema",type:"object",reference:p,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=pt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(E(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}}else E(this,"type",n,o);return n}})}r(p,"object");function s(e,t){return T({kind:"schema",type:"optional",reference:s,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===void 0&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(s,"optional");function b(e,t){return T({kind:"schema",type:"picklist",reference:b,expects:Ge(e.map(te),"|"),async:!1,options:e,message:t,"~run"(n,o){return this.options.includes(n.value)?n.typed=!0:E(this,"type",n,o),n}})}r(b,"picklist");function v(e,t,n){return T({kind:"schema",type:"record",reference:v,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){o.typed=!0,o.value={};for(let l in u)if(ct(u,l)){let m=u[l],d=this.key["~run"]({value:l},a);if(d.issues){let f={type:"object",origin:"key",input:u,key:l,value:m};for(let A of d.issues)A.path=[f],o.issues?.push(A);if(o.issues||(o.issues=d.issues),a.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let f={type:"object",origin:"value",input:u,key:l,value:m};for(let A of h.issues)A.path?A.path.unshift(f):A.path=[f],o.issues?.push(A);if(o.issues||(o.issues=h.issues),a.abortEarly){o.typed=!1;break}}(!d.typed||!h.typed)&&(o.typed=!1),d.typed&&(o.value[d.value]=h.value)}}else E(this,"type",o,a);return o}})}r(v,"record");function i(e){return T({kind:"schema",type:"string",reference:i,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:E(this,"type",t,n),t}})}r(i,"string");function Sn(e,t){return T({kind:"schema",type:"tuple",reference:Sn,expects:"Array",async:!1,items:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<this.items.length;u++){let l=a[u],m=this.items[u]["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,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),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else E(this,"type",n,o);return n}})}r(Sn,"tuple");function lt(e){let t;if(e)for(let n of e)if(t)for(let o of n.issues)t.push(o);else t=n.issues;return t}r(lt,"_subIssues");function Y(e,t){return T({kind:"schema",type:"union",reference:Y,expects:Ge(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,o){let a,u,l;for(let m of this.options){let d=m["~run"]({value:n.value},o);if(d.typed)if(d.issues)u?u.push(d):u=[d];else{a=d;break}else l?l.push(d):l=[d]}if(a)return a;if(u){if(u.length===1)return u[0];E(this,"type",n,o,{issues:lt(u)}),n.typed=!0}else{if(l?.length===1)return l[0];E(this,"type",n,o,{issues:lt(l)})}return n}})}r(Y,"union");function D(){return T({kind:"schema",type:"unknown",reference:D,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}r(D,"unknown");function re(e,t,n){return T({kind:"schema",type:"variant",reference:re,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){let l,m=0,d=this.key,h=[],f=r((A,O)=>{for(let z of A.options){if(z.type==="variant")f(z,new Set(O).add(z.key));else{let J=!0,Q=0;for(let _ of O){let le=z.entries[_];if(_ in u?le["~run"]({typed:!1,value:u[_]},bn).issues:le.type!=="exact_optional"&&le.type!=="optional"&&le.type!=="nullish"){J=!1,d!==_&&(m<Q||m===Q&&_ in u&&!(d in u))&&(m=Q,d=_,h=[]),d===_&&h.push(z.entries[_].expects);break}Q++}if(J){let _=z["~run"]({value:u},a);(!l||!l.typed&&_.typed)&&(l=_)}}if(l&&!l.issues)break}},"parseOptions");if(f(this,new Set([this.key])),l)return l;E(this,"type",o,a,{input:u[d],expected:Ge(h,"|"),path:[{type:"object",origin:"value",input:u,key:d,value:u[d]}]})}else E(this,"type",o,a);return o}})}r(re,"variant");function ze(e,t,n){let o=e["~run"]({value:t},$e(n));if(o.issues)throw new Oe(o.issues);return o.value}r(ze,"parse");function c(...e){return T({...e[0],pipe:e,"~run"(t,n){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=o["~run"](t,n))}return t}})}r(c,"pipe");function j(e,t,n){let o=e["~run"]({value:t},$e(n));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}r(j,"safeParse");var dt=p({role:b([Ce.USER,Ce.ASSISTANT,Ce.SYSTEM]),content:c(i(),g(1)),id:s(i()),createdAt:s(i())}),Ye=He(()=>p({type:b(["string","number","boolean","array","object"]),description:s(i()),enum:s(y(i())),items:s(Ye),properties:s(v(i(),Ye)),required:s(y(i()))})),kn=p({description:c(i(),g(1)),parameters:p({type:R("object"),properties:v(i(),Ye),required:s(y(i()))})}),Tn=p({id:i(),name:i(),args:v(i(),D())}),An=p({messages:c(y(dt),g(1)),provider:s(b([q.ANTHROPIC,q.OPENAI,q.GOOGLE])),model:s(i()),maxTokens:s(c(x(),$(),C(1))),temperature:s(c(x(),C(0),V(2))),systemPrompt:s(i()),stream:s(S()),tools:s(v(i(),kn))}),Rn=p({promptTokens:x(),completionTokens:x(),totalTokens:x()}),di=p({message:dt,usage:s(Rn),finishReason:s(i()),toolCalls:s(y(Tn))}),fi=p({provider:b([q.ANTHROPIC,q.OPENAI,q.GOOGLE]),model:s(i()),maxTokens:s(c(x(),$(),C(1))),temperature:s(c(x(),C(0),V(2))),systemPrompt:s(i())});function mi(e){return j(An,e)}r(mi,"validateAIChatRequest");var ft={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};var X={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};var xi={FREE:"free",PRO:"pro",PREMIUM:"premium"};var mt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};var gt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function ke(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}r(ke,"picklistOptions");var Ci=p({id:i(),email:s(w(c(i(),L()))),displayName:s(w(i())),photoURL:s(w(c(i(),P()))),emailVerified:s(S()),lastLoginAt:s(i()),providerData:s(y(p({providerId:i(),uid:i(),email:s(w(c(i(),L()))),displayName:s(w(i())),photoURL:s(w(c(i(),P()))),phoneNumber:s(w(i()))}))),role:s(b(ke(X))),customClaims:s(v(i(),ne()))}),de=p({tier:i(),status:i(),subscriptionEnd:w(c(i(),ce())),updatedAt:c(i(),ce()),isDefault:s(S()),features:s(y(i())),subscriptionId:s(w(i())),customerId:s(w(i())),cancelAtPeriodEnd:s(S())}),wi=p({...de.entries,userId:i(),isActive:s(S())}),Oi=p({role:s(b(ke(X))),subscription:s(de),features:s(y(b(ke(mt)))),permissions:s(y(b(ke(gt)))),githubAccess:s(p({username:s(i()),teamAccess:s(y(i())),repoAccess:s(y(i()))}))});var Xe={PAYMENT:"payment",SUBSCRIPTION:"subscription"};var yt=100,wn=p({productId:c(i(),g(1),G(200)),quantity:c(x(),$(),C(1),V(1e4))}),Zi=c(p({billingConfigKey:s(c(i(),g(1))),lineItems:s(c(y(wn),g(1,"At least one line item is required"),G(yt,`At most ${yt} line items`))),successUrl:c(i(),P()),cancelUrl:c(i(),P()),customerEmail:s(c(i(),L())),metadata:s(v(i(),i())),allowPromotionCodes:s(S()),userId:s(i()),productId:s(i()),priceId:s(i()),currency:s(c(i(),pe(3,"Currency must be 3-letter ISO code"))),userEmail:s(c(i(),L())),mode:s(b([Xe.PAYMENT,Xe.SUBSCRIPTION]))}),We(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,a=o.billingConfigKey||o.metadata?.billingConfigKey;return a?{...o,billingConfigKey:a,lineItems:o.lineItems??[{productId:a,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),Ji=p({sessionId:i(),sessionUrl:w(c(i(),P()))}),Te=c(i(),g(1),B(/\S/)),On=p({sessionId:Te,billingConfigKey:Te}),Pn=p({sessionId:Te,orderId:Te,billingConfigKey:Te,sessionStatus:b(["open","complete","expired"]),paymentStatus:b(["paid","unpaid","no_payment_required"])});function Qi(e){return j(On,e)}r(Qi,"validateVerifyOrderCheckoutRequest");function eo(e){return j(Pn,e)}r(eo,"validateVerifyOrderCheckoutResult");var to=p({...de.entries,userId:i(),subscriptionId:w(i()),customerId:i(),cancelAtPeriodEnd:S()}),no=p({id:i(),type:i(),data:p({object:ne()}),created:c(i(),ce())}),ro=Se({userId:s(i()),firebaseUid:s(i()),productType:s(i())});var Dn=p({type:R("StripePayment"),name:c(i(),g(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:s(c(i(),g(1,"Stripe price ID is required"))),tier:c(i(),g(1,"Tier is required")),duration:c(i(),g(1,"Duration is required")),allowPromotionCodes:s(S()),metadata:s(v(i(),i()))}),_n=p({type:R("StripeSubscription"),name:c(i(),g(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:c(i(),g(1,"Stripe price ID is required")),tier:c(i(),g(1,"Tier is required")),duration:b(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:s(S()),metadata:s(v(i(),i()))}),Nn=re("type",[Dn,_n]),io=v(i(),Nn),oo=v(i(),p({name:i(),price:i(),currency:i(),description:s(i()),features:s(y(i())),priceId:s(i()),allowPromotionCodes:s(S())})),ht={name:i(),price:x(),currency:i(),priceId:s(i()),tier:i(),duration:i(),description:s(i()),metadata:s(v(i(),i())),allowPromotionCodes:s(S())},Fn=re("mode",[p({mode:R("manual"),taxRateIds:c(y(c(i(),g(1))),g(1))}),p({mode:R("automatic")})]),vt=5,Un=p({allowedCountries:c(y(c(i(),B(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),g(1)),shippingRateIds:s(c(y(c(i(),g(1))),G(vt,`shippingRateIds: at most ${vt} (Stripe limit)`)))}),Mn=p({type:R("StripeOrder"),name:i(),currency:c(i(),pe(3)),description:s(i()),metadata:s(v(i(),i())),allowPromotionCodes:s(S()),tax:Fn,taxIdCollection:b(["disabled","optional","required"]),billingAddressCollection:b(["auto","required"]),shipping:s(Un),customerCreation:b(["always","if_required"]),invoiceCreation:S(),paymentMethodConfiguration:s(c(i(),g(1)))}),Ln=v(i(),re("type",[p({type:R("StripePayment"),...ht}),p({type:R("StripeSubscription"),...ht}),Mn]));function so(e){return ze(Ln,e)}r(so,"validateStripeBackConfig");var yo={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},fe={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"};var W={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},bt=W.available,me=Object.keys(W);function Et(e){let t=me.filter(n=>W[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}r(Et,"onlyStatusThat");var Ze=Et("isDefault"),Je=Et("isRemoved"),Vn=me.filter(e=>W[e].read!=="guest"),Ae=["id","createdAt","updatedAt","createdById","updatedById"],ie={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"};var xt=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Eo={EQ:ie.EQ,NEQ:ie.NEQ,LT:ie.LT,LTE:ie.LTE,GT:ie.GT,GTE:ie.GTE};var St=class extends Error{static{r(this,"BulkCollisionError")}collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}};var wo=p({collection:c(i(),g(1,"Collection name is required")),data:v(i(),D()),idempotencyKey:s(i())}),Oo=p({collection:c(i(),g(1,"Collection name is required")),id:c(i(),g(1,"Entity ID is required"))}),Po=p({collection:c(i(),g(1,"Collection name is required")),id:c(i(),g(1,"Entity ID is required")),data:v(i(),D()),merge:s(S(),!1)}),Do=p({collection:c(i(),g(1,"Collection name is required")),id:c(i(),g(1,"Entity ID is required"))}),_o=p({collection:c(i(),g(1,"Collection name is required")),limit:s(c(x(),C(1),V(1e3)),1e3),offset:s(c(x(),C(0)),0),orderBy:s(i()),orderDirection:s(b(["asc","desc"]),"desc"),where:s(y(p({field:i(),operator:b(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:D()})))});var Bn=p({templateId:c(i(),g(1)),to:c(i(),L()),data:v(i(),D()),locale:s(c(i(),g(2),G(5)),"fr"),from:s(i()),replyTo:s(i())}),Ho=p({success:S(),messageId:s(i()),error:s(i())});function Ko(e){return j(Bn,e)}r(Ko,"validateSendEmailRequest");var kt=["pull","push","admin","maintain","triage"];var Qe=p({owner:c(i(),g(1,"Repository owner is required")),repo:c(i(),g(1,"Repository name is required"))}),jn=b([...kt]),_s=p({userId:c(i(),g(1,"User ID is required")),githubUsername:c(i(),g(1,"GitHub username is required")),repoConfig:Qe,permission:s(jn,"push"),customClaims:s(v(i(),ne()))}),Ns=p({userId:c(i(),g(1,"User ID is required")),githubUsername:c(i(),g(1,"GitHub username is required")),repoConfig:Qe}),Fs=p({userId:c(i(),g(1,"User ID is required")),githubUsername:c(i(),g(1,"GitHub username is required")),repoConfig:Qe}),Us=p({provider:i(),purpose:b(["authentication","api-access"]),code:c(i(),g(1,"Authorization code is required")),redirectUri:c(i(),P("Valid redirect URI is required")),codeVerifier:s(i()),state:s(i()),instance:s(c(i(),P()))}),Ms=p({provider:i(),refreshToken:c(i(),g(1,"Refresh token is required")),redirectUri:c(i(),P("Valid redirect URI is required"))}),Ls=p({provider:i()}),Vs=p({userId:c(i(),g(1,"User ID is required"))});var Tt=p({name:i(),color:i(),icon:i(),customParameters:s(v(i(),i())),button:p({backgroundColor:i(),textColor:i(),borderColor:i(),hoverBackgroundColor:i(),focusOutlineColor:i(),fontWeight:s(i(),"500"),textKey:s(i())})}),qn=p({...Tt.entries,type:b(["auth","both"]),scopes:s(y(i())),firebaseProviderId:s(i())}),Pe=Y([R(""),c(i(),P())]),$n=p({authUrl:Pe,tokenUrl:Pe,profileUrl:Pe,revokeUrl:s(Pe)}),Gn=p({authentication:s(y(i())),"api-access":y(i())}),Wn=s(p({pkce:s(S(),!1),codeChallengeMethod:s(b(["S256","plain"]),"S256")})),Hn=p({...Tt.entries,type:b(["oauth","both"]),scopes:Gn,endpoints:$n,capabilities:Wn});var Hs={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"}}},Ks=v(i(),qn),zs=v(i(),Hn);var At={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"};var oa={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:At.ANALYTICS},marketing:{requiresConsent:At.MARKETING}};function Rt(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"}r(Rt,"detectErrorSource");function H(e){return(t,n)=>{if(t instanceof k)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new k(n||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let a=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(a=e.errorCodeMapping[o]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[o]),u||(u=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new k(n||u,a,{details:l,source:e.errorSource})}}r(H,"createErrorHandler");var De={"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"};var ge={"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."},Kn={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"},et={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function zn(e){return e in et}r(zn,"isEntityHookErrorType");var Z={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",...De},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",...De},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(Kn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:r(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:r(e=>{let t={originalError:e};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:De,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ge.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:r(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:ge["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ge.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:r(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},Yn=r(e=>e instanceof Oe?new k(ge["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):H(Z.validation)(e),"handleValidationError"),Xn=r(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&zn(e.type)){let t=et[e.type]||"unknown";return new k(e.message||ge[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&qe[e.code]){let t=qe[e.code];if(t){let n=et[t.type]||"unknown";return new k(t.message||ge[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return H(Z.entity)(e)},"handleEntityError"),It={auth:H(Z.auth),oauth:H(Z.oauth),api:H(Z.api),firebase:H(Z.firebase),ui:H(Z.ui),validation:Yn,entity:Xn,unknown:H(Z.unknown)};function _e(e,t,n){return e instanceof k?e:(It[t]||It.unknown)(e,n)}r(_e,"mapToDoNotDevError");function Ct(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,l])=>{if(typeof l!="function"&&u!=="originalError")try{a.setExtra(u,l)}catch{a.setExtra(u,`[${typeof l}]`)}}),Object.entries(n).forEach(([u,l])=>{if(typeof l!="function")try{a.setExtra(`context.${u}`,l)}catch{a.setExtra(`context.${u}`,`[${typeof l}]`)}}),(e.details?.userId||n.userId)&&a.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}r(Ct,"captureErrorToSentry");function Zn(){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}r(Zn,"isDev");function Qa(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:a={},log:u=!0,reportToSentry:l=!0,showNotification:m=!1,severity:d="error"}=n,h=Rt(e),f=e instanceof k?e:_e(e,h,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new k(o,f.code,{details:{...f.details,originalMessage:f.message},source:h,userMessageProvided:!0}):f=new k(f.message,f.code,{details:{...f.details,userMessage:o},source:h,userMessageProvided:!0})),u){let A=Zn()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:f.code,message:f.message,source:h};switch(d){case"warning":console.warn(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details}:O);break;case"info":console.info(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details}:O);break;case"success":console.log(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details}:O);break;default:console.error(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details,stack:f.stack}:O)}}return l&&Ct(f,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),f}r(Qa,"handleError");function cu(e,t,n,o){let a=o?` ${JSON.stringify(o)}`:"",u=`${t}.${n}(${a})`,l=_e(e,"auth",`${u}: ${Jn(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&l.code==="unknown"&&e.code!=="unknown"?new k(l.message,l.code,{details:{...l.details,originalCode:e.code},source:l.source}):l}r(cu,"wrapAuthError");function Jn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}r(Jn,"getErrorMessage");var wt={[X.GUEST]:0,[X.USER]:1,[X.ADMIN]:2,[X.SUPER]:3};function oe(e,t){if(!e)return!1;let n=wt[e]??-1,o=wt[t]??1/0;return n>=o}r(oe,"hasRoleAccess");var Ot="__DNDEV_SINGLETONS__";function Qn(){if(typeof globalThis<"u"){let e=globalThis,t=e[Ot];if(t)return t;let n=new Map;return e[Ot]=n,n}return new Map}r(Qn,"getSingletonRegistry");function Pt(e,t){let n=Qn();return n.has(e)||n.set(e,t()),n.get(e)}r(Pt,"getGlobalSingleton");function yu(e,...t){let n=null,o=!1;return r(function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}},"getInstance")}r(yu,"createSingleton");function Dt(){return Pt("providers",()=>({providers:null}))}r(Dt,"getProviderState");function Eu(e){let{providers:t}=Dt();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}r(Eu,"getProvider");function xu(e){return!!Dt().providers?.[e]}r(xu,"hasProvider");function er(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}r(er,"hasVisibility");function tr(e){if(er(e))return e.visibility}r(tr,"getFieldVisibility");function nr(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?oe(t,"admin"):n==="owner"?!1:oe(t,n)}r(nr,"isFieldVisible");function rr(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}r(rr,"isOwnerVisible");function _t(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let o=e.entries,a=[],{documentData:u,uid:l,ownership:m}=n??{},d=m&&l!=null&&u&&rr(u,l,m);for(let[h,f]of Object.entries(o)){let A=tr(f);if(A==="owner"){d&&a.push(h);continue}nr(A,t)&&a.push(h)}return a}r(_t,"getVisibleFields");function Cu(e,t,n,o){if(!e)return{};let a=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,u=_t(t,n,a),l={};for(let m of u)Object.prototype.hasOwnProperty.call(e,m)&&(l[m]=e[m]);return l}r(Cu,"filterVisibleFields");function Nt(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}r(Nt,"getListCardFieldNames");var ir=new Set(["http:","https:","mailto:","tel:","blob:"]);function _u(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(ir.has(n.protocol))return t}catch{return t}return""}r(_u,"sanitizeHref");var or=me.map(e=>({value:e,label:`crud:status.${e}`}));var Mu=[...Ae,"status"];function Ft(e){return Ae.some(t=>t===e)}r(Ft,"isBackendGeneratedField");var tt={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...or]}},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:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var nt=["text","textarea","richtext","field-array"];function Ne(e){return`${e}I18n`}r(Ne,"i18nFieldName");function Fe(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}r(Fe,"addMonths");function Ut(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}r(Ut,"addYears");function Bc(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=Fe(t,1):e==="3months"?n=Fe(t,3):e==="6months"?n=Fe(t,6):e==="1year"?n=Ut(t,1):e==="2years"?n=Ut(t,2):n=Fe(t,1),n.toISOString()}r(Bc,"calculateSubscriptionEndDate");function M(e){let t=e?.status;return typeof t=="string"?t:null}r(M,"statusOf");function Me({op:e,status:t,storedStatus:n}){return Ue(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}r(Me,"writeSchemaFor");function Mt({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let o=t??n;return o==null||o===n?!1:Ue(n,"holdIncomplete")&&!Ue(o,"holdIncomplete")}r(Mt,"entersVisibleStatus");function Lt(e){return e!=null&&Object.hasOwn(W,e)?W[e]:bt}r(Lt,"statusRow");function Ue(e,t){return Lt(e)[t]}r(Ue,"statusCan");function Le(e,t){let n=Lt(e).read;return n==="guest"||oe(t,n)}r(Le,"statusReadableBy");function rt(e){return Object.keys(W).filter(t=>W[t][e])}r(rt,"statusesThat");var Ve=r(e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(g(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(G(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(B(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?c(i(),...t):i()},"textValue"),ar=r(()=>c(i(),L("Invalid email address")),"emailValue"),ur=r(e=>e.validation?.minLength!==void 0?c(i(),g(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):i(),"passwordValue"),lr=r(()=>c(i(),P("Invalid URL")),"urlValue"),ye=r(e=>{let t=[];return e.validation?.min!==void 0&&t.push(C(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(V(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?c(x(),...t):x()},"numberValue"),Vt=r(()=>S(),"booleanValue"),it=r(()=>c(i(),Ee(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),"dateValue"),cr=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,pr=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,dr=/^\d{4}-(?:0[1-9]|1[0-2])$/,fr=r(()=>c(i(),B(cr,"Invalid time format")),"timeValue"),mr=r(()=>c(i(),B(pr,"Invalid week format")),"weekValue"),gr=r(()=>c(i(),B(dr,"Invalid month format")),"monthValue"),zt=p({url:i(),filename:i(),size:x(),mimeType:N(i()),uploadedAt:N(i())}),Bt=r(()=>zt,"fileValue"),jt=r(()=>y(zt),"filesValue"),Yt=p({fullUrl:i(),thumbUrl:i()}),yr=r(()=>Y([i(),Yt]),"pictureValue"),hr=r(()=>y(Y([i(),Yt])),"picturesValue"),vr=r(()=>p({lat:x(),lng:x()}),"geopointValue"),br=r(()=>p({formatted_address:i(),latitude:x(),longitude:x(),street_number:N(i()),route:N(i()),locality:N(i()),administrative_area_level_1:N(i()),administrative_area_level_2:N(i()),country:N(i()),postal_code:N(i())}),"addressValue"),Er=r(()=>v(i(),D()),"mapValue"),xr=r(()=>y(D()),"arrayValue"),Sr=r(()=>y(v(i(),D())),"fieldArrayValue"),ot=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?b(t.map(n=>n.value)):Y([i(),x()])},"selectValue"),kr=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?y(b(t.map(n=>n.value))):y(i())},"multiselectValue"),Xt=r(()=>c(i(),g(1,"Invalid ID format")),"referenceValue"),st=r(()=>i(),"stringValue"),Tr=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,Ar=r(e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Tr;return c(i(),B(t,"Invalid phone number"))},"telValue"),Rr=r(e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return c(i(),g(t,`IBAN must be at least ${t} characters`),G(n,`IBAN must not exceed ${n} characters`),B(new RegExp(o),"Invalid IBAN format"))},"ibanValue"),qt=r(()=>Ke(),"neverValue");function Zt(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}r(Zt,"stringSwitchValues");var Ir=r(e=>{let t=Zt(e);return t?b(t):S()},"switchValue"),$t=Se({gdprConsent:R(!0),gdprConsentDate:s(i()),gdprConsentVersion:s(i())},"GDPR consent must be given"),Cr=r(e=>e.validation?.required?$t:Y([R(!1),$t]),"gdprConsentValue"),wr=r(()=>p({amount:x(),currency:s(i()),vatIncluded:s(S()),discountPercent:s(c(x(),C(0),V(100)))}),"priceValue"),Jt={text:{schema:Ve,kind:"text"},textarea:{schema:Ve,kind:"text"},richtext:{schema:Ve,kind:"text"},color:{schema:Ve,kind:"text"},email:{schema:ar,kind:"text"},password:{schema:ur,kind:"text"},url:{schema:lr,kind:"text"},tel:{schema:Ar,kind:"text"},iban:{schema:Rr,kind:"text"},number:{schema:ye,kind:"number"},currency:{schema:ye,kind:"number"},range:{schema:ye,kind:"number"},year:{schema:ye,kind:"number"},rating:{schema:ye,kind:"number"},duration:{schema:ye,kind:"number"},price:{schema:wr,kind:"json"},boolean:{schema:Vt,kind:"boolean"},checkbox:{schema:Vt,kind:"boolean"},switch:{schema:Ir,kind:r(e=>Zt(e)?"text":"boolean","kind")},gdprConsent:{schema:Cr,kind:"json"},date:{schema:it,kind:"date"},"datetime-local":{schema:it,kind:"timestamp"},timestamp:{schema:it,kind:"timestamp"},time:{schema:fr,kind:"time"},week:{schema:mr,kind:"text"},month:{schema:gr,kind:"text"},file:{schema:Bt,kind:"json"},files:{schema:jt,kind:"json"},document:{schema:Bt,kind:"json"},documents:{schema:jt,kind:"json"},image:{schema:yr,kind:"json"},images:{schema:hr,kind:"json"},geopoint:{schema:vr,kind:"json"},address:{schema:br,kind:"json"},map:{schema:Er,kind:"json"},array:{schema:xr,kind:"json"},"field-array":{schema:Sr,kind:"json"},select:{schema:ot,kind:"text"},radio:{schema:ot,kind:"text"},combobox:{schema:ot,kind:"text"},multiselect:{schema:kr,kind:"json"},reference:{schema:Xt,kind:"ref"},hidden:{schema:st,kind:"text"},avatar:{schema:st,kind:"text"},badge:{schema:st,kind:"text"},submit:{schema:qt,kind:"text"},reset:{schema:qt,kind:"text"}},Or=new Set(xt);function Pr(e){return Or.has(e)}r(Pr,"isBuiltInFieldType");var Dr=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),_r=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),Nr=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),Fr={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function K(e,t){return t in e?Reflect.get(e,t):void 0}r(K,"prop");function Gt(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}r(Gt,"kindOfScalar");function Wt(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}r(Wt,"commonKind");function Be(e){if(typeof e!="object"||e===null)return;let t=K(e,"type");if(typeof t!="string")return;let n=Ur(e,t),o=K(e,"pipe");if(Array.isArray(o))for(let a of o.slice(1)){if(typeof a!="object"||a===null)continue;let u=K(a,"kind"),l=K(a,"type");if(typeof l=="string"){if(u==="schema")n=Be(a);else if(u==="transformation")Nr.has(l)||(n=void 0);else if(u==="validation"){l==="integer"&&n==="number"&&(n="integer");let m=Fr[l];m&&n==="text"&&(n=m)}}}return n}r(Be,"kindOfSchema");function Ur(e,t){if(Dr.has(t))return Be(K(e,"wrapped"));if(_r.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return Gt(K(e,"literal"));case"picklist":case"enum":{let n=K(e,"options");return Array.isArray(n)?Wt(n.map(Gt)):void 0}case"union":case"variant":{let n=K(e,"options");if(!Array.isArray(n))return;let o=n.filter(a=>{let u=typeof a=="object"&&a!==null?K(a,"type"):void 0;return u!=="null"&&u!=="undefined"});return Wt(o.map(Be))}default:return}}r(Ur,"kindOfRoot");function Ht(e,t){let{kind:n}=Jt[e];return typeof n=="function"?n(t):n}r(Ht,"builtinKind");function at(e,t=e.name){let n=e.validation?.reference,o=n?{ref:n}:{},a=e.type,u=Pr(a)?a:void 0,l=e.validation?.schema;if(l){let m=(n?"ref":void 0)??Be(l)??(u?Ht(u,e):void 0);if(!m)throw new Error(`Field '${t}' (custom type '${a}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:l,kind:m,...o}}if(n)return{schema:Xt(),kind:"ref",...o};if(u)return{schema:Jt[u].schema(e),kind:Ht(u,e)};throw new Error(`Field '${t}' has custom type '${a}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}r(at,"resolveFieldValue");function Mr(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}r(Mr,"requirementOf");function Lr(e,t){return t.visibility==="hidden"||t.editable===fe.GENERATED||Ft(e)?"never":t.editable===fe.FALSE?"program":t.editable===fe.COMPUTED?"derived":"user"}r(Lr,"writeClassOf");function Vr(e,t){return(n,o)=>{if(t!=="user")return!1;let a=e.editable;return a===void 0||a===fe.TRUE?e.visibility!=="technical":a===fe.CREATE_ONLY?o==="create":typeof a=="string"?oe(n,a):!1}}r(Vr,"editableForOf");function Br(e,t,n){let o=Lr(e,t);return{value:at(t,`${n}.${e}`),required:Mr(t),write:o,editableFor:Vr(t,o),visibleAt:t.visibility,...t.i18n===!0&&{companion:Ne(e)}}}r(Br,"describeField");var Kt=new WeakMap;function Qt(e){let t=Kt.get(e);if(t)return t;let n={};for(let[a,u]of Object.entries(e.fields))n[a]=Br(a,u,e.name);let o={name:e.name,collection:e.collection,fields:n};return Kt.set(e,o),o}r(Qt,"describeEntity");function jr(e,t){return t?c(e,Ee(n=>n!=="","Required")):N(e)}r(jr,"applyRequired");function se(e){return jr(at(e).schema,e.validation?.required)}r(se,"getSchemaType");function ue(e,t){return Object.assign(e,{visibility:t})}r(ue,"withVisibility");function ae(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}r(ae,"withMetadata");function qr(e){let t=se(e);return ue(t,e.visibility)}r(qr,"createFieldSchema");function $r(e,t){if(!nt.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${nt.join(", ")}.`);let n=se({...t,validation:{...t.validation,required:!1}});return ue(s(w(v(i(),n))),t.visibility)}r($r,"createTranslationsSchema");function he(e,t){for(let n of Object.keys(e)){let o=t[n];o?.i18n===!0&&(e[Ne(n)]=$r(n,o))}return e}r(he,"withTranslations");function ut(e){let t=se({...e,validation:{...e.validation,required:!1}});return ue(t,e.visibility)}r(ut,"createOptionalFieldSchema");function Gr(e){return e.validation?.required?ue(s(se(e)),e.visibility):ut(e)}r(Gr,"createUpdateFieldSchema");function mp(e){let t=e.fields,n=Qt(e).fields,o=r(I=>n[I]?.write==="never","isWriteExcluded"),a={};for(let[I,U]of Object.entries(t))n[I]?.visibleAt!=="hidden"&&(a[I]=ut(U));let u=ae(p(he({...a},t)),e),l={};for(let[I,U]of Object.entries(t))o(I)||(l[I]=qr(U));let m=ae(p(he({...l},t)),e),d={};for(let[I,U]of Object.entries(t))if(!o(I))if(I==="status"){let ee=b(rt("saveIncomplete"));d[I]=ue(ee,U.visibility)}else d[I]=ut(U);let h=ae(p(he({...d},t)),e),f={};for(let[I,U]of Object.entries(t))o(I)||(f[I]=Gr(U));f.id=ue(se(tt.id),"technical");let A=ae(p(he({...f},t)),e),O;if(e.listFields&&e.listFields.length>0){let I=["id","status"],U=[...new Set([...I,...e.listFields])];O={};for(let ee of U){let ve=a[ee];ve&&(O[ee]=ve)}}else O=a;let z=ae(p(he({...O},t)),e),J,Q=Nt(e);if(Q.length>0){let I=["id","status"],U=[...new Set([...I,...Q])];J={};for(let ee of U){let ve=a[ee];ve&&(J[ee]=ve)}}else J=a;let _=ae(p(he({...J},t)),e),le=ae(p({id:ue(se(tt.id),"technical")}),e);return{create:m,draft:h,update:A,get:u,list:z,listCard:_,delete:le}}r(mp,"createSchemas");var Wr=v(i(),D()),Hr=p({id:i(),patch:v(i(),D())}),Kr=i(),hp=p({inserts:s(y(Wr)),updates:s(y(Hr)),deletes:s(y(Kr))}),zr=p({insertedIds:y(i()),updatedIds:y(i()),deletedIds:y(i())}),Yr=re("op",[p({op:R("insert"),index:c(x(),$(),C(0)),id:s(i()),error:i()}),p({op:R("update"),id:i(),index:s(c(x(),$(),C(0))),error:i()}),p({op:R("delete"),id:i(),index:s(c(x(),$(),C(0))),error:i()})]),vp=p({...zr.entries,failed:s(y(Yr),()=>[])});function bp(e){let t=new Set((e.updates??[]).map(l=>l.id)),n=e.deletes??[],o=[];for(let l of n)t.has(l)&&o.push(l);if(o.length>0)return{collisions:o,where:"updates-deletes"};let a=e.inserts??[],u=[];for(let l of a)typeof l.id=="string"&&t.has(l.id)&&u.push(l.id);return u.length>0?{collisions:u,where:"inserts-updates"}:{collisions:[],where:null}}r(bp,"detectBulkCollisions");function en(e){let t=e.entries;if(!t||typeof t!="object")throw new k("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}r(en,"schemaKeys");function je(e,t){let n=[e.create,e.draft,e.update].filter(a=>a!==void 0);if(n.some(a=>a.type==="loose_object"))return[];let o=new Set([...n.flatMap(en),...Ae]);return Object.keys(t).filter(a=>!o.has(a))}r(je,"unknownKeysOf");function tn(e,t){let n={};for(let o of en(t))n[o]=null;for(let[o,a]of Object.entries(e))a!==void 0&&(n[o]=a);return n}r(tn,"wholeRecord");function Re(e,t,n,o,a){let u=j(t,n);if(!u.success)return{ok:!1,schemaKey:e,issues:[...u.issues],unknownKeys:a};let l=u.output,m={};for(let d of Object.keys(o))d!=="id"&&Object.hasOwn(l,d)&&(m[d]=l[d]);return{ok:!0,schemaKey:e,written:m,unknownKeys:a}}r(Re,"parseWritten");function nn(e){return M(e)??Ze}r(nn,"createStatus");function Xr(e,t){let n=nn(t),o=Me({op:"create",status:n}),a={...t,status:n},u=Re(o,o==="draft"?e.draft:e.create,a,a,je(e,t));return u.ok?{...u,written:{...u.written,status:n}}:u}r(Xr,"prepareCreate");function rn(e){return M(e)!==Je}r(rn,"updateNeedsStored");function on(e,t){let n={op:"update",status:M(e),storedStatus:M(t)};return{schemaKey:Me(n)==="draft"?"draft":"update",whole:Mt(n)}}r(on,"updateCheck");function sn(e,{id:t,patch:n,stored:o}){let a=M(n);if(!o&&rn(n))throw new k(`CRUD update rules: row "${t}" needs its stored row (the row's status${a===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:u,whole:l}=on(n,o),m=je(e,n);if(o&&l)return Re(u,e.update,tn({...o,...n,id:t},e.update),n,m);let d=u==="draft"?{...n,status:M(n)??M(o),id:t}:{...n,id:t};return Re(u,u==="draft"?e.draft:e.update,d,n,m)}r(sn,"prepareUpdate");function Zr(e,t){return sn(e,{id:t,patch:{status:Je}})}r(Zr,"prepareRemove");function Jr(e){return me.filter(t=>!Le(t,e))}r(Jr,"hiddenStatusesFor");function Qr(e,t){return Le(M(e),t)}r(Qr,"isReadableBy");export{ni as a,ri as b,ii as c,oi as d,ai as e,pe as f,V as g,g as h,C as i,B as j,vn as k,P as l,ne as m,y as n,S as o,En as p,R as q,Se as r,xn as s,w as t,x as u,p as v,s as w,b as x,v as y,i as z,Sn as A,Y as B,D as C,re as D,ze as E,c as F,j as G,An as H,mi as I,ft as J,xi as K,de as L,Zi as M,Qi as N,eo as O,so as P,yo as Q,Vn as R,St as S,Bn as T,Ko as U,k as V,_s as W,Ns as X,Fs as Y,Us as Z,Hs as _,Qa as $,cu as aa,oe as ba,yu as ca,Eu as da,xu as ea,nr as fa,Cu as ga,Nt as ha,_u as ia,Bc as ja,M as ka,Ue as la,mp as ma,hp as na,zr as oa,bp as pa,nn as qa,Xr as ra,on as sa,sn as ta,Zr as ua,Jr as va,Qr as wa};
22
- //# sourceMappingURL=chunk-Y6BR2QOV.js.map
21
+ import{a as r}from"./chunk-AYY7UXNI.js";var be={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"};var Ie={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},qe={[be.PERMISSION_DENIED]:{type:Ie.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[be.NOT_FOUND]:{type:Ie.NOT_FOUND,message:"The requested resource was not found"},[be.ALREADY_EXISTS]:{type:Ie.ALREADY_EXISTS,message:"The resource already exists"},[be.INVALID_ARGUMENT]:{type:Ie.VALIDATION_ERROR,message:"Invalid argument provided"}};function an(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}r(an,"hasCaptureStackTrace");var k=class e extends Error{static{r(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=be.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.userMessageProvided,this.name=this.constructor.name,an(Error)&&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 q={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Ce={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},ri={[q.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"]},[q.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[q.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}};var ii={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"}},oi=4,si={"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"}};var we,un={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function $e(e){return!e&&!we?un:{lang:e?.lang??we?.lang,message:e?.message,abortEarly:e?.abortEarly??we?.abortEarly,abortPipeEarly:e?.abortPipeEarly??we?.abortPipeEarly}}r($e,"getGlobalConfig");var ln;function cn(e){return ln?.get(e)}r(cn,"getGlobalMessage");var pn;function dn(e){return pn?.get(e)}r(dn,"getSchemaMessage");var fn;function mn(e,t){return fn?.get(e)?.get(t)}r(mn,"getSpecificMessage");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}r(te,"_stringify");function E(e,t,n,o,a){let u=a&&"input"in a?a.input:n.value,l=a?.expected??e.expects??null,m=a?.received??te(u),d={kind:e.kind,type:e.type,input:u,expected:l,received:m,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:a?.path,issues:a?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",f=a?.message??e.message??mn(e.reference,d.lang)??(h?dn(d.lang):null)??o.message??cn(d.lang);f!==void 0&&(d.message=typeof f=="function"?f(d):f),h&&(n.typed=!1),n.issues?n.issues.push(d):n.issues=[d]}r(E,"_addIssue");function gn(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}r(gn,"_isSameValueZero");function ct(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}r(ct,"_isValidObjectKey");function Ge(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}r(Ge,"_joinExpects");function T(e){return e["~standard"]={version:1,vendor:"valibot",validate:r(t=>e["~run"]({value:t},$e()),"validate")},e}r(T,"_standardSchema");var Oe=class extends Error{static{r(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function ui(e){return e instanceof Oe}r(ui,"isValiError");var yn=/^[\w+-]+(?:\.[\w+-]+)*@[\da-zA-Z]+(?:[.-][\da-zA-Z]+)*\.[a-zA-Z]{2,}$/u,li=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");var hn=/^\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;function Ee(e,t){return{kind:"validation",type:"check",reference:Ee,async:!1,expects:null,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement(n.value)&&E(this,"input",n,o),n}}}r(Ee,"check");function L(e){return{kind:"validation",type:"email",reference:L,expects:null,async:!1,requirement:yn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&E(this,"email",t,n),t}}}r(L,"email");function $(e){return{kind:"validation",type:"integer",reference:$,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&E(this,"integer",t,n),t}}}r($,"integer");function ce(e){return{kind:"validation",type:"iso_timestamp",reference:ce,async:!1,expects:null,requirement:hn,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&E(this,"timestamp",t,n),t}}}r(ce,"isoTimestamp");function pe(e,t){return{kind:"validation",type:"length",reference:pe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length!==this.requirement&&E(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(pe,"length");function G(e,t){return{kind:"validation",type:"max_length",reference:G,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length>this.requirement&&E(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(G,"maxLength");function V(e,t){return{kind:"validation",type:"max_value",reference:V,async:!1,expects:`<=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value<=this.requirement)&&E(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(V,"maxValue");function g(e,t){return{kind:"validation",type:"min_length",reference:g,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length<this.requirement&&E(this,"length",n,o,{received:`${n.value.length}`}),n}}}r(g,"minLength");function C(e,t){return{kind:"validation",type:"min_value",reference:C,async:!1,expects:`>=${e instanceof Date?e.toJSON():te(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value>=this.requirement)&&E(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():te(n.value)}),n}}}r(C,"minValue");function We(e){return{kind:"transformation",type:"raw_transform",reference:We,async:!1,"~run"(t,n){let o=e({dataset:t,config:n,addIssue:r(a=>E(this,a?.label??"input",t,n,a),"addIssue"),NEVER:null});return t.issues?t.typed=!1:t.value=o,t}}}r(We,"rawTransform");function B(e,t){return{kind:"validation",type:"regex",reference:B,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement.test(n.value)&&E(this,"format",n,o),n}}}r(B,"regex");function vn(e){return{kind:"transformation",type:"transform",reference:vn,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}r(vn,"transform");function P(e){return{kind:"validation",type:"url",reference:P,async:!1,expects:null,requirement(t){try{return URL.canParse?URL.canParse(t):(new URL(t),!0)}catch{return!1}},message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&E(this,"URL",t,n),t}}}r(P,"url");var bn={abortEarly:!0};function pt(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}r(pt,"getFallback");function xe(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}r(xe,"getDefault");function ne(){return T({kind:"schema",type:"any",reference:ne,expects:"any",async:!1,"~run"(e){return e.typed=!0,e}})}r(ne,"any");function y(e,t){return T({kind:"schema",type:"array",reference:y,expects:"Array",async:!1,item:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<a.length;u++){let l=a[u],m=this.item["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,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),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else E(this,"type",n,o);return n}})}r(y,"array");function S(e){return T({kind:"schema",type:"boolean",reference:S,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:E(this,"type",t,n),t}})}r(S,"boolean");function En(e,t){return T({kind:"schema",type:"custom",reference:En,expects:"unknown",async:!1,check:e,message:t,"~run"(n,o){return this.check(n.value)?n.typed=!0:E(this,"type",n,o),n}})}r(En,"custom");function He(e){return T({kind:"schema",type:"lazy",reference:He,expects:"unknown",async:!1,getter:e,"~run"(t,n){return this.getter(t.value)["~run"](t,n)}})}r(He,"lazy");function R(e,t){return T({kind:"schema",type:"literal",reference:R,expects:te(e),async:!1,literal:e,message:t,"~run"(n,o){return gn(n.value,this.literal)?n.typed=!0:E(this,"type",n,o),n}})}r(R,"literal");function Se(e,t){return T({kind:"schema",type:"loose_object",reference:Se,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=pt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(E(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}if(!n.issues||!o.abortEarly)for(let u in a)ct(a,u)&&!Object.prototype.hasOwnProperty.call(this.entries,u)&&(n.value[u]=a[u])}else E(this,"type",n,o);return n}})}r(Se,"looseObject");function Ke(e){return T({kind:"schema",type:"never",reference:Ke,expects:"never",async:!1,message:e,"~run"(t,n){return E(this,"type",t,n),t}})}r(Ke,"never");function xn(e){return T({kind:"schema",type:"null",reference:xn,expects:"null",async:!1,message:e,"~run"(t,n){return t.value===null?t.typed=!0:E(this,"type",t,n),t}})}r(xn,"null_");function w(e,t){return T({kind:"schema",type:"nullable",reference:w,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===null&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(w,"nullable");function N(e,t){return T({kind:"schema",type:"nullish",reference:N,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(N,"nullish");function x(e){return T({kind:"schema",type:"number",reference:x,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:E(this,"type",t,n),t}})}r(x,"number");function p(e,t){return T({kind:"schema",type:"object",reference:p,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let a=n.value;if(a&&typeof a=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in a||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=u in a?a[u]:xe(l),d=l["~run"]({value:m},o);if(d.issues){let h={type:"object",origin:"value",input:a,key:u,value:m};for(let f of d.issues)f.path?f.path.unshift(h):f.path=[h],n.issues?.push(f);if(n.issues||(n.issues=d.issues),o.abortEarly){n.typed=!1;break}}d.typed||(n.typed=!1),n.value[u]=d.value}else if(l.fallback!==void 0)n.value[u]=pt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(E(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:a,key:u,value:a[u]}]}),o.abortEarly))break}}else E(this,"type",n,o);return n}})}r(p,"object");function s(e,t){return T({kind:"schema",type:"optional",reference:s,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===void 0&&(this.default!==void 0&&(n.value=xe(this,n,o)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}r(s,"optional");function b(e,t){return T({kind:"schema",type:"picklist",reference:b,expects:Ge(e.map(te),"|"),async:!1,options:e,message:t,"~run"(n,o){return this.options.includes(n.value)?n.typed=!0:E(this,"type",n,o),n}})}r(b,"picklist");function v(e,t,n){return T({kind:"schema",type:"record",reference:v,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){o.typed=!0,o.value={};for(let l in u)if(ct(u,l)){let m=u[l],d=this.key["~run"]({value:l},a);if(d.issues){let f={type:"object",origin:"key",input:u,key:l,value:m};for(let A of d.issues)A.path=[f],o.issues?.push(A);if(o.issues||(o.issues=d.issues),a.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:m},a);if(h.issues){let f={type:"object",origin:"value",input:u,key:l,value:m};for(let A of h.issues)A.path?A.path.unshift(f):A.path=[f],o.issues?.push(A);if(o.issues||(o.issues=h.issues),a.abortEarly){o.typed=!1;break}}(!d.typed||!h.typed)&&(o.typed=!1),d.typed&&(o.value[d.value]=h.value)}}else E(this,"type",o,a);return o}})}r(v,"record");function i(e){return T({kind:"schema",type:"string",reference:i,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:E(this,"type",t,n),t}})}r(i,"string");function Sn(e,t){return T({kind:"schema",type:"tuple",reference:Sn,expects:"Array",async:!1,items:e,message:t,"~run"(n,o){let a=n.value;if(Array.isArray(a)){n.typed=!0,n.value=[];for(let u=0;u<this.items.length;u++){let l=a[u],m=this.items[u]["~run"]({value:l},o);if(m.issues){let d={type:"array",origin:"value",input:a,key:u,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),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value.push(m.value)}}else E(this,"type",n,o);return n}})}r(Sn,"tuple");function lt(e){let t;if(e)for(let n of e)if(t)for(let o of n.issues)t.push(o);else t=n.issues;return t}r(lt,"_subIssues");function Y(e,t){return T({kind:"schema",type:"union",reference:Y,expects:Ge(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,o){let a,u,l;for(let m of this.options){let d=m["~run"]({value:n.value},o);if(d.typed)if(d.issues)u?u.push(d):u=[d];else{a=d;break}else l?l.push(d):l=[d]}if(a)return a;if(u){if(u.length===1)return u[0];E(this,"type",n,o,{issues:lt(u)}),n.typed=!0}else{if(l?.length===1)return l[0];E(this,"type",n,o,{issues:lt(l)})}return n}})}r(Y,"union");function D(){return T({kind:"schema",type:"unknown",reference:D,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}r(D,"unknown");function re(e,t,n){return T({kind:"schema",type:"variant",reference:re,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(o,a){let u=o.value;if(u&&typeof u=="object"){let l,m=0,d=this.key,h=[],f=r((A,O)=>{for(let z of A.options){if(z.type==="variant")f(z,new Set(O).add(z.key));else{let J=!0,Q=0;for(let _ of O){let le=z.entries[_];if(_ in u?le["~run"]({typed:!1,value:u[_]},bn).issues:le.type!=="exact_optional"&&le.type!=="optional"&&le.type!=="nullish"){J=!1,d!==_&&(m<Q||m===Q&&_ in u&&!(d in u))&&(m=Q,d=_,h=[]),d===_&&h.push(z.entries[_].expects);break}Q++}if(J){let _=z["~run"]({value:u},a);(!l||!l.typed&&_.typed)&&(l=_)}}if(l&&!l.issues)break}},"parseOptions");if(f(this,new Set([this.key])),l)return l;E(this,"type",o,a,{input:u[d],expected:Ge(h,"|"),path:[{type:"object",origin:"value",input:u,key:d,value:u[d]}]})}else E(this,"type",o,a);return o}})}r(re,"variant");function ze(e,t,n){let o=e["~run"]({value:t},$e(n));if(o.issues)throw new Oe(o.issues);return o.value}r(ze,"parse");function c(...e){return T({...e[0],pipe:e,"~run"(t,n){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=o["~run"](t,n))}return t}})}r(c,"pipe");function j(e,t,n){let o=e["~run"]({value:t},$e(n));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}r(j,"safeParse");var dt=p({role:b([Ce.USER,Ce.ASSISTANT,Ce.SYSTEM]),content:c(i(),g(1)),id:s(i()),createdAt:s(i())}),Ye=He(()=>p({type:b(["string","number","boolean","array","object"]),description:s(i()),enum:s(y(i())),items:s(Ye),properties:s(v(i(),Ye)),required:s(y(i()))})),kn=p({description:c(i(),g(1)),parameters:p({type:R("object"),properties:v(i(),Ye),required:s(y(i()))})}),Tn=p({id:i(),name:i(),args:v(i(),D())}),An=p({messages:c(y(dt),g(1)),provider:s(b([q.ANTHROPIC,q.OPENAI,q.GOOGLE])),model:s(i()),maxTokens:s(c(x(),$(),C(1))),temperature:s(c(x(),C(0),V(2))),systemPrompt:s(i()),stream:s(S()),tools:s(v(i(),kn))}),Rn=p({promptTokens:x(),completionTokens:x(),totalTokens:x()}),fi=p({message:dt,usage:s(Rn),finishReason:s(i()),toolCalls:s(y(Tn))}),mi=p({provider:b([q.ANTHROPIC,q.OPENAI,q.GOOGLE]),model:s(i()),maxTokens:s(c(x(),$(),C(1))),temperature:s(c(x(),C(0),V(2))),systemPrompt:s(i())});function gi(e){return j(An,e)}r(gi,"validateAIChatRequest");var ft={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};var X={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};var Si={FREE:"free",PRO:"pro",PREMIUM:"premium"};var mt={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};var gt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function ke(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}r(ke,"picklistOptions");var wi=p({id:i(),email:s(w(c(i(),L()))),displayName:s(w(i())),photoURL:s(w(c(i(),P()))),emailVerified:s(S()),lastLoginAt:s(i()),providerData:s(y(p({providerId:i(),uid:i(),email:s(w(c(i(),L()))),displayName:s(w(i())),photoURL:s(w(c(i(),P()))),phoneNumber:s(w(i()))}))),role:s(b(ke(X))),customClaims:s(v(i(),ne()))}),de=p({tier:i(),status:i(),subscriptionEnd:w(c(i(),ce())),updatedAt:c(i(),ce()),isDefault:s(S()),features:s(y(i())),subscriptionId:s(w(i())),customerId:s(w(i())),cancelAtPeriodEnd:s(S())}),Oi=p({...de.entries,userId:i(),isActive:s(S())}),Pi=p({role:s(b(ke(X))),subscription:s(de),features:s(y(b(ke(mt)))),permissions:s(y(b(ke(gt)))),githubAccess:s(p({username:s(i()),teamAccess:s(y(i())),repoAccess:s(y(i()))}))});var Xe={PAYMENT:"payment",SUBSCRIPTION:"subscription"};var yt=100,wn=p({productId:c(i(),g(1),G(200)),quantity:c(x(),$(),C(1),V(1e4))}),Ji=c(p({billingConfigKey:s(c(i(),g(1))),lineItems:s(c(y(wn),g(1,"At least one line item is required"),G(yt,`At most ${yt} line items`))),successUrl:c(i(),P()),cancelUrl:c(i(),P()),customerEmail:s(c(i(),L())),metadata:s(v(i(),i())),allowPromotionCodes:s(S()),userId:s(i()),productId:s(i()),priceId:s(i()),currency:s(c(i(),pe(3,"Currency must be 3-letter ISO code"))),userEmail:s(c(i(),L())),mode:s(b([Xe.PAYMENT,Xe.SUBSCRIPTION]))}),We(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,a=o.billingConfigKey||o.metadata?.billingConfigKey;return a?{...o,billingConfigKey:a,lineItems:o.lineItems??[{productId:a,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),Qi=p({sessionId:i(),sessionUrl:w(c(i(),P()))}),Te=c(i(),g(1),B(/\S/)),On=p({sessionId:Te,billingConfigKey:Te}),Pn=p({sessionId:Te,orderId:Te,billingConfigKey:Te,sessionStatus:b(["open","complete","expired"]),paymentStatus:b(["paid","unpaid","no_payment_required"])});function eo(e){return j(On,e)}r(eo,"validateVerifyOrderCheckoutRequest");function to(e){return j(Pn,e)}r(to,"validateVerifyOrderCheckoutResult");var no=p({...de.entries,userId:i(),subscriptionId:w(i()),customerId:i(),cancelAtPeriodEnd:S()}),ro=p({id:i(),type:i(),data:p({object:ne()}),created:c(i(),ce())}),io=Se({userId:s(i()),firebaseUid:s(i()),productType:s(i())});var Dn=p({type:R("StripePayment"),name:c(i(),g(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:s(c(i(),g(1,"Stripe price ID is required"))),tier:c(i(),g(1,"Tier is required")),duration:c(i(),g(1,"Duration is required")),allowPromotionCodes:s(S()),metadata:s(v(i(),i()))}),_n=p({type:R("StripeSubscription"),name:c(i(),g(1,"Product name is required")),description:s(i()),price:i(),currency:s(c(i(),pe(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:c(i(),g(1,"Stripe price ID is required")),tier:c(i(),g(1,"Tier is required")),duration:b(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:s(S()),metadata:s(v(i(),i()))}),Nn=re("type",[Dn,_n]),oo=v(i(),Nn),so=v(i(),p({name:i(),price:i(),currency:i(),description:s(i()),features:s(y(i())),priceId:s(i()),allowPromotionCodes:s(S())})),ht={name:i(),price:x(),currency:i(),priceId:s(i()),tier:i(),duration:i(),description:s(i()),metadata:s(v(i(),i())),allowPromotionCodes:s(S())},Fn=re("mode",[p({mode:R("manual"),taxRateIds:c(y(c(i(),g(1))),g(1))}),p({mode:R("automatic")})]),vt=5,Un=p({allowedCountries:c(y(c(i(),B(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),g(1)),shippingRateIds:s(c(y(c(i(),g(1))),G(vt,`shippingRateIds: at most ${vt} (Stripe limit)`)))}),Mn=p({type:R("StripeOrder"),name:i(),currency:c(i(),pe(3)),description:s(i()),metadata:s(v(i(),i())),allowPromotionCodes:s(S()),tax:Fn,taxIdCollection:b(["disabled","optional","required"]),billingAddressCollection:b(["auto","required"]),shipping:s(Un),customerCreation:b(["always","if_required"]),invoiceCreation:S(),paymentMethodConfiguration:s(c(i(),g(1)))}),Ln=v(i(),re("type",[p({type:R("StripePayment"),...ht}),p({type:R("StripeSubscription"),...ht}),Mn]));function ao(e){return ze(Ln,e)}r(ao,"validateStripeBackConfig");var ho={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},fe={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"};var W={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},bt=W.available,me=Object.keys(W);function Et(e){let t=me.filter(n=>W[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}r(Et,"onlyStatusThat");var Ze=Et("isDefault"),Je=Et("isRemoved"),Vn=me.filter(e=>W[e].read!=="guest"),Ae=["id","createdAt","updatedAt","createdById","updatedById"],ie={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"};var xt=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var xo={EQ:ie.EQ,NEQ:ie.NEQ,LT:ie.LT,LTE:ie.LTE,GT:ie.GT,GTE:ie.GTE};var St=class extends Error{static{r(this,"BulkCollisionError")}collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}};var Oo=p({collection:c(i(),g(1,"Collection name is required")),data:v(i(),D()),idempotencyKey:s(i())}),Po=p({collection:c(i(),g(1,"Collection name is required")),id:c(i(),g(1,"Entity ID is required"))}),Do=p({collection:c(i(),g(1,"Collection name is required")),id:c(i(),g(1,"Entity ID is required")),data:v(i(),D()),merge:s(S(),!1)}),_o=p({collection:c(i(),g(1,"Collection name is required")),id:c(i(),g(1,"Entity ID is required"))}),No=p({collection:c(i(),g(1,"Collection name is required")),limit:s(c(x(),C(1),V(1e3)),1e3),offset:s(c(x(),C(0)),0),orderBy:s(i()),orderDirection:s(b(["asc","desc"]),"desc"),where:s(y(p({field:i(),operator:b(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:D()})))});var Bn=p({templateId:c(i(),g(1)),to:c(i(),L()),data:v(i(),D()),locale:s(c(i(),g(2),G(5)),"fr"),from:s(i()),replyTo:s(i())}),Ko=p({success:S(),messageId:s(i()),error:s(i())});function zo(e){return j(Bn,e)}r(zo,"validateSendEmailRequest");var kt=["pull","push","admin","maintain","triage"];var Qe=p({owner:c(i(),g(1,"Repository owner is required")),repo:c(i(),g(1,"Repository name is required"))}),jn=b([...kt]),Ns=p({userId:c(i(),g(1,"User ID is required")),githubUsername:c(i(),g(1,"GitHub username is required")),repoConfig:Qe,permission:s(jn,"push"),customClaims:s(v(i(),ne()))}),Fs=p({userId:c(i(),g(1,"User ID is required")),githubUsername:c(i(),g(1,"GitHub username is required")),repoConfig:Qe}),Us=p({userId:c(i(),g(1,"User ID is required")),githubUsername:c(i(),g(1,"GitHub username is required")),repoConfig:Qe}),Ms=p({provider:i(),purpose:b(["authentication","api-access"]),code:c(i(),g(1,"Authorization code is required")),redirectUri:c(i(),P("Valid redirect URI is required")),codeVerifier:s(i()),state:s(i()),instance:s(c(i(),P()))}),Ls=p({provider:i(),refreshToken:c(i(),g(1,"Refresh token is required")),redirectUri:c(i(),P("Valid redirect URI is required"))}),Vs=p({provider:i()}),Bs=p({userId:c(i(),g(1,"User ID is required"))});var Tt=p({name:i(),color:i(),icon:i(),customParameters:s(v(i(),i())),button:p({backgroundColor:i(),textColor:i(),borderColor:i(),hoverBackgroundColor:i(),focusOutlineColor:i(),fontWeight:s(i(),"500"),textKey:s(i())})}),qn=p({...Tt.entries,type:b(["auth","both"]),scopes:s(y(i())),firebaseProviderId:s(i())}),Pe=Y([R(""),c(i(),P())]),$n=p({authUrl:Pe,tokenUrl:Pe,profileUrl:Pe,revokeUrl:s(Pe)}),Gn=p({authentication:s(y(i())),"api-access":y(i())}),Wn=s(p({pkce:s(S(),!1),codeChallengeMethod:s(b(["S256","plain"]),"S256")})),Hn=p({...Tt.entries,type:b(["oauth","both"]),scopes:Gn,endpoints:$n,capabilities:Wn});var Ks={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"}}},zs=v(i(),qn),Ys=v(i(),Hn);var At={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"};var sa={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:At.ANALYTICS},marketing:{requiresConsent:At.MARKETING}};function Rt(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"}r(Rt,"detectErrorSource");function H(e){return(t,n)=>{if(t instanceof k)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new k(n||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let a=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(a=e.errorCodeMapping[o]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[o]),u||(u=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new k(n||u,a,{details:l,source:e.errorSource})}}r(H,"createErrorHandler");var De={"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"};var ge={"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."},Kn={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"},et={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function zn(e){return e in et}r(zn,"isEntityHookErrorType");var Z={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",...De},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",...De},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(Kn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:r(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:r(e=>{let t={originalError:e};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:De,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ge.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:r(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:ge["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ge.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:r(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},Yn=r(e=>e instanceof Oe?new k(ge["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):H(Z.validation)(e),"handleValidationError"),Xn=r(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&zn(e.type)){let t=et[e.type]||"unknown";return new k(e.message||ge[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&qe[e.code]){let t=qe[e.code];if(t){let n=et[t.type]||"unknown";return new k(t.message||ge[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return H(Z.entity)(e)},"handleEntityError"),It={auth:H(Z.auth),oauth:H(Z.oauth),api:H(Z.api),firebase:H(Z.firebase),ui:H(Z.ui),validation:Yn,entity:Xn,unknown:H(Z.unknown)};function _e(e,t,n){return e instanceof k?e:(It[t]||It.unknown)(e,n)}r(_e,"mapToDoNotDevError");function Ct(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(a=>{a.setTag("errorSource",t),a.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,l])=>{if(typeof l!="function"&&u!=="originalError")try{a.setExtra(u,l)}catch{a.setExtra(u,`[${typeof l}]`)}}),Object.entries(n).forEach(([u,l])=>{if(typeof l!="function")try{a.setExtra(`context.${u}`,l)}catch{a.setExtra(`context.${u}`,`[${typeof l}]`)}}),(e.details?.userId||n.userId)&&a.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}r(Ct,"captureErrorToSentry");function Zn(){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}r(Zn,"isDev");function eu(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:a={},log:u=!0,reportToSentry:l=!0,showNotification:m=!1,severity:d="error"}=n,h=Rt(e),f=e instanceof k?e:_e(e,h,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new k(o,f.code,{details:{...f.details,originalMessage:f.message},source:h,userMessageProvided:!0}):f=new k(f.message,f.code,{details:{...f.details,userMessage:o},source:h,userMessageProvided:!0})),u){let A=Zn()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:f.code,message:f.message,source:h};switch(d){case"warning":console.warn(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details}:O);break;case"info":console.info(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details}:O);break;case"success":console.log(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details}:O);break;default:console.error(`[DoNotDev] ${f.code}: ${f.message}`,A?{...O,details:f.details,stack:f.stack}:O)}}return l&&Ct(f,h,a),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),f}r(eu,"handleError");function pu(e,t,n,o){let a=o?` ${JSON.stringify(o)}`:"",u=`${t}.${n}(${a})`,l=_e(e,"auth",`${u}: ${Jn(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&l.code==="unknown"&&e.code!=="unknown"?new k(l.message,l.code,{details:{...l.details,originalCode:e.code},source:l.source}):l}r(pu,"wrapAuthError");function Jn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}r(Jn,"getErrorMessage");var wt={[X.GUEST]:0,[X.USER]:1,[X.ADMIN]:2,[X.SUPER]:3};function oe(e,t){if(!e)return!1;let n=wt[e]??-1,o=wt[t]??1/0;return n>=o}r(oe,"hasRoleAccess");var Ot="__DNDEV_SINGLETONS__";function Qn(){if(typeof globalThis<"u"){let e=globalThis,t=e[Ot];if(t)return t;let n=new Map;return e[Ot]=n,n}return new Map}r(Qn,"getSingletonRegistry");function Pt(e,t){let n=Qn();return n.has(e)||n.set(e,t()),n.get(e)}r(Pt,"getGlobalSingleton");function hu(e,...t){let n=null,o=!1;return r(function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}},"getInstance")}r(hu,"createSingleton");function Dt(){return Pt("providers",()=>({providers:null}))}r(Dt,"getProviderState");function xu(e){let{providers:t}=Dt();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}r(xu,"getProvider");function Su(e){return!!Dt().providers?.[e]}r(Su,"hasProvider");function er(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}r(er,"hasVisibility");function tr(e){if(er(e))return e.visibility}r(tr,"getFieldVisibility");function nr(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?oe(t,"admin"):n==="owner"?!1:oe(t,n)}r(nr,"isFieldVisible");function rr(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}r(rr,"isOwnerVisible");function _t(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let o=e.entries,a=[],{documentData:u,uid:l,ownership:m}=n??{},d=m&&l!=null&&u&&rr(u,l,m);for(let[h,f]of Object.entries(o)){let A=tr(f);if(A==="owner"){d&&a.push(h);continue}nr(A,t)&&a.push(h)}return a}r(_t,"getVisibleFields");function wu(e,t,n,o){if(!e)return{};let a=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,u=_t(t,n,a),l={};for(let m of u)Object.prototype.hasOwnProperty.call(e,m)&&(l[m]=e[m]);return l}r(wu,"filterVisibleFields");function Nt(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}r(Nt,"getListCardFieldNames");var ir=new Set(["http:","https:","mailto:","tel:","blob:"]);function Nu(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(ir.has(n.protocol))return t}catch{return t}return""}r(Nu,"sanitizeHref");var or=me.map(e=>({value:e,label:`crud:status.${e}`}));var Lu=[...Ae,"status"];function Ft(e){return Ae.some(t=>t===e)}r(Ft,"isBackendGeneratedField");var tt={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...or]}},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:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var nt=["text","textarea","richtext","field-array"];function Ne(e){return`${e}I18n`}r(Ne,"i18nFieldName");function Fe(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}r(Fe,"addMonths");function Ut(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}r(Ut,"addYears");function zc(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=Fe(t,1):e==="3months"?n=Fe(t,3):e==="6months"?n=Fe(t,6):e==="1year"?n=Ut(t,1):e==="2years"?n=Ut(t,2):n=Fe(t,1),n.toISOString()}r(zc,"calculateSubscriptionEndDate");function M(e){let t=e?.status;return typeof t=="string"?t:null}r(M,"statusOf");function Me({op:e,status:t,storedStatus:n}){return Ue(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}r(Me,"writeSchemaFor");function Mt({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let o=t??n;return o==null||o===n?!1:Ue(n,"holdIncomplete")&&!Ue(o,"holdIncomplete")}r(Mt,"entersVisibleStatus");function Lt(e){return e!=null&&Object.hasOwn(W,e)?W[e]:bt}r(Lt,"statusRow");function Ue(e,t){return Lt(e)[t]}r(Ue,"statusCan");function Le(e,t){let n=Lt(e).read;return n==="guest"||oe(t,n)}r(Le,"statusReadableBy");function rt(e){return Object.keys(W).filter(t=>W[t][e])}r(rt,"statusesThat");var Ve=r(e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(g(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(G(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(B(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?c(i(),...t):i()},"textValue"),ur=r(()=>c(i(),L("Invalid email address")),"emailValue"),lr=r(e=>e.validation?.minLength!==void 0?c(i(),g(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):i(),"passwordValue"),cr=r(()=>c(i(),P("Invalid URL")),"urlValue"),ye=r(e=>{let t=[];return e.validation?.min!==void 0&&t.push(C(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(V(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?c(x(),...t):x()},"numberValue"),Vt=r(()=>S(),"booleanValue"),it=r(()=>c(i(),Ee(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),"dateValue"),pr=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,dr=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,fr=/^\d{4}-(?:0[1-9]|1[0-2])$/,mr=r(()=>c(i(),B(pr,"Invalid time format")),"timeValue"),gr=r(()=>c(i(),B(dr,"Invalid week format")),"weekValue"),yr=r(()=>c(i(),B(fr,"Invalid month format")),"monthValue"),zt=p({url:i(),filename:i(),size:x(),mimeType:N(i()),uploadedAt:N(i())}),Bt=r(()=>zt,"fileValue"),jt=r(()=>y(zt),"filesValue"),Yt=p({fullUrl:i(),thumbUrl:i()}),hr=r(()=>Y([i(),Yt]),"pictureValue"),vr=r(()=>y(Y([i(),Yt])),"picturesValue"),br=r(()=>p({lat:x(),lng:x()}),"geopointValue"),Er=r(()=>p({formatted_address:i(),latitude:x(),longitude:x(),street_number:N(i()),route:N(i()),locality:N(i()),administrative_area_level_1:N(i()),administrative_area_level_2:N(i()),country:N(i()),postal_code:N(i())}),"addressValue"),xr=r(()=>v(i(),D()),"mapValue"),Sr=r(()=>y(D()),"arrayValue"),kr=r(()=>y(v(i(),D())),"fieldArrayValue"),ot=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?b(t.map(n=>n.value)):Y([i(),x()])},"selectValue"),Tr=r(e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?y(b(t.map(n=>n.value))):y(i())},"multiselectValue"),Xt=r(()=>c(i(),g(1,"Invalid ID format")),"referenceValue"),st=r(()=>i(),"stringValue"),Ar=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,Rr=r(e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Ar;return c(i(),B(t,"Invalid phone number"))},"telValue"),Ir=r(e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return c(i(),g(t,`IBAN must be at least ${t} characters`),G(n,`IBAN must not exceed ${n} characters`),B(new RegExp(o),"Invalid IBAN format"))},"ibanValue"),qt=r(()=>Ke(),"neverValue");function Zt(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}r(Zt,"stringSwitchValues");var Cr=r(e=>{let t=Zt(e);return t?b(t):S()},"switchValue"),$t=Se({gdprConsent:R(!0),gdprConsentDate:s(i()),gdprConsentVersion:s(i())},"GDPR consent must be given"),wr=r(e=>e.validation?.required?$t:Y([R(!1),$t]),"gdprConsentValue"),Or=r(()=>p({amount:x(),currency:s(i()),vatIncluded:s(S()),discountPercent:s(c(x(),C(0),V(100)))}),"priceValue"),Jt={text:{schema:Ve,kind:"text"},textarea:{schema:Ve,kind:"text"},richtext:{schema:Ve,kind:"text"},color:{schema:Ve,kind:"text"},email:{schema:ur,kind:"text"},password:{schema:lr,kind:"text"},url:{schema:cr,kind:"text"},tel:{schema:Rr,kind:"text"},iban:{schema:Ir,kind:"text"},number:{schema:ye,kind:"number"},currency:{schema:ye,kind:"number"},range:{schema:ye,kind:"number"},year:{schema:ye,kind:"number"},rating:{schema:ye,kind:"number"},duration:{schema:ye,kind:"number"},price:{schema:Or,kind:"json"},boolean:{schema:Vt,kind:"boolean"},checkbox:{schema:Vt,kind:"boolean"},switch:{schema:Cr,kind:r(e=>Zt(e)?"text":"boolean","kind")},gdprConsent:{schema:wr,kind:"json"},date:{schema:it,kind:"date"},"datetime-local":{schema:it,kind:"timestamp"},timestamp:{schema:it,kind:"timestamp"},time:{schema:mr,kind:"time"},week:{schema:gr,kind:"text"},month:{schema:yr,kind:"text"},file:{schema:Bt,kind:"json"},files:{schema:jt,kind:"json"},document:{schema:Bt,kind:"json"},documents:{schema:jt,kind:"json"},image:{schema:hr,kind:"json"},images:{schema:vr,kind:"json"},geopoint:{schema:br,kind:"json"},address:{schema:Er,kind:"json"},map:{schema:xr,kind:"json"},array:{schema:Sr,kind:"json"},"field-array":{schema:kr,kind:"json"},select:{schema:ot,kind:"text"},radio:{schema:ot,kind:"text"},combobox:{schema:ot,kind:"text"},multiselect:{schema:Tr,kind:"json"},reference:{schema:Xt,kind:"ref"},hidden:{schema:st,kind:"text"},avatar:{schema:st,kind:"text"},badge:{schema:st,kind:"text"},submit:{schema:qt,kind:"text"},reset:{schema:qt,kind:"text"}},Pr=new Set(xt);function Dr(e){return Pr.has(e)}r(Dr,"isBuiltInFieldType");var _r=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),Nr=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),Fr=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),Ur={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function K(e,t){return t in e?Reflect.get(e,t):void 0}r(K,"prop");function Gt(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}r(Gt,"kindOfScalar");function Wt(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}r(Wt,"commonKind");function Be(e){if(typeof e!="object"||e===null)return;let t=K(e,"type");if(typeof t!="string")return;let n=Mr(e,t),o=K(e,"pipe");if(Array.isArray(o))for(let a of o.slice(1)){if(typeof a!="object"||a===null)continue;let u=K(a,"kind"),l=K(a,"type");if(typeof l=="string"){if(u==="schema")n=Be(a);else if(u==="transformation")Fr.has(l)||(n=void 0);else if(u==="validation"){l==="integer"&&n==="number"&&(n="integer");let m=Ur[l];m&&n==="text"&&(n=m)}}}return n}r(Be,"kindOfSchema");function Mr(e,t){if(_r.has(t))return Be(K(e,"wrapped"));if(Nr.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return Gt(K(e,"literal"));case"picklist":case"enum":{let n=K(e,"options");return Array.isArray(n)?Wt(n.map(Gt)):void 0}case"union":case"variant":{let n=K(e,"options");if(!Array.isArray(n))return;let o=n.filter(a=>{let u=typeof a=="object"&&a!==null?K(a,"type"):void 0;return u!=="null"&&u!=="undefined"});return Wt(o.map(Be))}default:return}}r(Mr,"kindOfRoot");function Ht(e,t){let{kind:n}=Jt[e];return typeof n=="function"?n(t):n}r(Ht,"builtinKind");function at(e,t=e.name){let n=e.validation?.reference,o=n?{ref:n}:{},a=e.type,u=Dr(a)?a:void 0,l=e.validation?.schema;if(l){let m=(n?"ref":void 0)??Be(l)??(u?Ht(u,e):void 0);if(!m)throw new Error(`Field '${t}' (custom type '${a}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:l,kind:m,...o}}if(n)return{schema:Xt(),kind:"ref",...o};if(u)return{schema:Jt[u].schema(e),kind:Ht(u,e)};throw new Error(`Field '${t}' has custom type '${a}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}r(at,"resolveFieldValue");function Lr(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}r(Lr,"requirementOf");function Vr(e,t){return t.visibility==="hidden"||t.editable===fe.GENERATED||Ft(e)?"never":t.editable===fe.FALSE?"program":t.editable===fe.COMPUTED?"derived":"user"}r(Vr,"writeClassOf");function Br(e,t){return(n,o)=>{if(t!=="user")return!1;let a=e.editable;return a===void 0||a===fe.TRUE?e.visibility!=="technical":a===fe.CREATE_ONLY?o==="create":typeof a=="string"?oe(n,a):!1}}r(Br,"editableForOf");function jr(e,t,n){let o=Vr(e,t);return{value:at(t,`${n}.${e}`),required:Lr(t),write:o,editableFor:Br(t,o),visibleAt:t.visibility,...t.i18n===!0&&{companion:Ne(e)}}}r(jr,"describeField");var Kt=new WeakMap;function Qt(e){let t=Kt.get(e);if(t)return t;let n={};for(let[a,u]of Object.entries(e.fields))n[a]=jr(a,u,e.name);let o={name:e.name,collection:e.collection,fields:n};return Kt.set(e,o),o}r(Qt,"describeEntity");function qr(e,t){return t?c(e,Ee(n=>n!=="","Required")):N(e)}r(qr,"applyRequired");function se(e){return qr(at(e).schema,e.validation?.required)}r(se,"getSchemaType");function ue(e,t){return Object.assign(e,{visibility:t})}r(ue,"withVisibility");function ae(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}r(ae,"withMetadata");function $r(e){let t=se(e);return ue(t,e.visibility)}r($r,"createFieldSchema");function Gr(e,t){if(!nt.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${nt.join(", ")}.`);let n=se({...t,validation:{...t.validation,required:!1}});return ue(s(w(v(i(),n))),t.visibility)}r(Gr,"createTranslationsSchema");function he(e,t){for(let n of Object.keys(e)){let o=t[n];o?.i18n===!0&&(e[Ne(n)]=Gr(n,o))}return e}r(he,"withTranslations");function ut(e){let t=se({...e,validation:{...e.validation,required:!1}});return ue(t,e.visibility)}r(ut,"createOptionalFieldSchema");function Wr(e){return e.validation?.required?ue(s(se(e)),e.visibility):ut(e)}r(Wr,"createUpdateFieldSchema");function Sp(e){let t=e.fields,n=Qt(e).fields,o=r(I=>n[I]?.write==="never","isWriteExcluded"),a={};for(let[I,U]of Object.entries(t))n[I]?.visibleAt!=="hidden"&&(a[I]=ut(U));let u=ae(p(he({...a},t)),e),l={};for(let[I,U]of Object.entries(t))o(I)||(l[I]=$r(U));let m=ae(p(he({...l},t)),e),d={};for(let[I,U]of Object.entries(t))if(!o(I))if(I==="status"){let ee=b(rt("saveIncomplete"));d[I]=ue(ee,U.visibility)}else d[I]=ut(U);let h=ae(p(he({...d},t)),e),f={};for(let[I,U]of Object.entries(t))o(I)||(f[I]=Wr(U));f.id=ue(se(tt.id),"technical");let A=ae(p(he({...f},t)),e),O;if(e.listFields&&e.listFields.length>0){let I=["id","status"],U=[...new Set([...I,...e.listFields])];O={};for(let ee of U){let ve=a[ee];ve&&(O[ee]=ve)}}else O=a;let z=ae(p(he({...O},t)),e),J,Q=Nt(e);if(Q.length>0){let I=["id","status"],U=[...new Set([...I,...Q])];J={};for(let ee of U){let ve=a[ee];ve&&(J[ee]=ve)}}else J=a;let _=ae(p(he({...J},t)),e),le=ae(p({id:ue(se(tt.id),"technical")}),e);return{create:m,draft:h,update:A,get:u,list:z,listCard:_,delete:le}}r(Sp,"createSchemas");var Hr=v(i(),D()),Kr=p({id:i(),patch:v(i(),D())}),zr=i(),Ap=p({inserts:s(y(Hr)),updates:s(y(Kr)),deletes:s(y(zr))}),Yr=p({insertedIds:y(i()),updatedIds:y(i()),deletedIds:y(i())}),Xr=re("op",[p({op:R("insert"),index:c(x(),$(),C(0)),id:s(i()),error:i()}),p({op:R("update"),id:i(),index:s(c(x(),$(),C(0))),error:i()}),p({op:R("delete"),id:i(),index:s(c(x(),$(),C(0))),error:i()})]),Rp=p({...Yr.entries,failed:s(y(Xr),()=>[])});function Ip(e){let t=new Set((e.updates??[]).map(l=>l.id)),n=e.deletes??[],o=[];for(let l of n)t.has(l)&&o.push(l);if(o.length>0)return{collisions:o,where:"updates-deletes"};let a=e.inserts??[],u=[];for(let l of a)typeof l.id=="string"&&t.has(l.id)&&u.push(l.id);return u.length>0?{collisions:u,where:"inserts-updates"}:{collisions:[],where:null}}r(Ip,"detectBulkCollisions");function en(e){let t=e.entries;if(!t||typeof t!="object")throw new k("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}r(en,"schemaKeys");function je(e,t){let n=[e.create,e.draft,e.update].filter(a=>a!==void 0);if(n.some(a=>a.type==="loose_object"))return[];let o=new Set([...n.flatMap(en),...Ae]);return Object.keys(t).filter(a=>!o.has(a))}r(je,"unknownKeysOf");function tn(e,t){let n={};for(let o of en(t))n[o]=null;for(let[o,a]of Object.entries(e))a!==void 0&&(n[o]=a);return n}r(tn,"wholeRecord");function Re(e,t,n,o,a){let u=j(t,n);if(!u.success)return{ok:!1,schemaKey:e,issues:[...u.issues],unknownKeys:a};let l=u.output,m={};for(let d of Object.keys(o))d!=="id"&&Object.hasOwn(l,d)&&(m[d]=l[d]);return{ok:!0,schemaKey:e,written:m,unknownKeys:a}}r(Re,"parseWritten");function nn(e){return M(e)??Ze}r(nn,"createStatus");function Zr(e,t){let n=nn(t),o=Me({op:"create",status:n}),a={...t,status:n},u=Re(o,o==="draft"?e.draft:e.create,a,a,je(e,t));return u.ok?{...u,written:{...u.written,status:n}}:u}r(Zr,"prepareCreate");function rn(e){return M(e)!==Je}r(rn,"updateNeedsStored");function on(e,t){let n={op:"update",status:M(e),storedStatus:M(t)};return{schemaKey:Me(n)==="draft"?"draft":"update",whole:Mt(n)}}r(on,"updateCheck");function sn(e,{id:t,patch:n,stored:o}){let a=M(n);if(!o&&rn(n))throw new k(`CRUD update rules: row "${t}" needs its stored row (the row's status${a===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:u,whole:l}=on(n,o),m=je(e,n);if(o&&l)return Re(u,e.update,tn({...o,...n,id:t},e.update),n,m);let d=u==="draft"?{...n,status:M(n)??M(o),id:t}:{...n,id:t};return Re(u,u==="draft"?e.draft:e.update,d,n,m)}r(sn,"prepareUpdate");function Jr(e,t){return sn(e,{id:t,patch:{status:Je}})}r(Jr,"prepareRemove");function Qr(e){return me.filter(t=>!Le(t,e))}r(Qr,"hiddenStatusesFor");function ei(e,t){return Le(M(e),t)}r(ei,"isReadableBy");export{ri as a,ii as b,oi as c,si as d,ui as e,pe as f,V as g,g as h,C as i,B as j,vn as k,P as l,ne as m,y as n,S as o,En as p,R as q,Se as r,xn as s,w as t,x as u,p as v,s as w,b as x,v as y,i as z,Sn as A,Y as B,D as C,re as D,ze as E,c as F,j as G,An as H,gi as I,ft as J,Si as K,de as L,Ji as M,eo as N,to as O,ao as P,ho as Q,Vn as R,St as S,Bn as T,zo as U,k as V,Ns as W,Fs as X,Us as Y,Ms as Z,Ks as _,eu as $,pu as aa,oe as ba,hu as ca,xu as da,Su as ea,nr as fa,wu as ga,Nt as ha,Nu as ia,zc as ja,M as ka,Ue as la,Sp as ma,Ap as na,Yr as oa,Ip as pa,nn as qa,Zr as ra,on as sa,sn as ta,Jr as ua,Qr as va,ei as wa};
22
+ //# sourceMappingURL=chunk-FGXZMPSY.js.map
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{o as y}from"./chunk-LJXSA7EP.js";import{N as m,O as p,U as f}from"./chunk-Y6BR2QOV.js";import{a as g}from"./chunk-W6W4L44F.js";import{a as c}from"./chunk-AYY7UXNI.js";async function R(r,a){let o="validation",t="invalid";try{let l=m(r);if(!l.success)throw new Error;let e=l.output,{userId:n,billingConfig:d}=a;if(o="auth",t="rejected",typeof n!="string"||!n.trim())throw new Error;if(o="config",t="invalid",!Object.hasOwn(d,e.billingConfigKey)||d[e.billingConfigKey]?.type!=="StripeOrder")throw new Error;o="binding",t="unavailable";let s=await a.resolveOrderBinding({...e,userId:n});if(t="rejected",!s||s.userId!==n||s.sessionId!==e.sessionId||s.billingConfigKey!==e.billingConfigKey||typeof s.orderId!="string"||!s.orderId.trim())throw new Error;o="provider",t="unavailable";let i=await a.retrieveStripeSession(e.sessionId);if(o="response",t="rejected",i.id!==e.sessionId||i.mode!=="payment"||i.metadata?.userId!==n||i.metadata?.billingConfigKey!==e.billingConfigKey||i.metadata?.[y]!==s.orderId)throw new Error;t="invalid";let u=p({sessionId:i.id,orderId:s.orderId,billingConfigKey:e.billingConfigKey,sessionStatus:i.status,paymentStatus:i.payment_status});if(!u.success)throw new Error;return u.output}catch{try{await g.warn("[Checkout verification] Failed",{stage:o,category:t})}catch{}throw new Error("Checkout verification denied")}}c(R,"verifyOrderCheckoutAlgorithm");async function h(r,a,o){let t=f(r);if(!t.success)return{success:!1,error:`Invalid email request: ${t.issues?.map(i=>i.message).join(", ")}`};let l=a.templates[r.templateId];if(!l)return{success:!1,error:`Template not found: ${r.templateId}`};let e=r.locale||"fr",n=l.subject(r.data,e),d=l.html(r.data,e);return{success:!0,messageId:(await o.send({from:r.from||a.defaultFrom,to:r.to,subject:n,html:d,replyTo:r.replyTo||a.replyTo})).messageId}}c(h,"handleEmailRequest");var v="https://api.resend.com/emails";function C(r){if(!r)throw new Error("Resend API key is required");return{async send({from:a,to:o,subject:t,html:l,replyTo:e}){let n={from:a,to:o,subject:t,html:l};e&&(n.reply_to=e);let d=await fetch(v,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!d.ok){let i=await d.text().catch(()=>"Unknown error");throw new Error(`Resend API error (${d.status}): ${i}`)}return{messageId:(await d.json()).id}}}}c(C,"createResendProvider");export{R as a,h as b,C as c};
22
- //# sourceMappingURL=chunk-NP4Y2LAO.js.map
21
+ import{o as y}from"./chunk-6PXANFSJ.js";import{N as m,O as p,U as f}from"./chunk-FGXZMPSY.js";import{a as g}from"./chunk-W6W4L44F.js";import{a as c}from"./chunk-AYY7UXNI.js";async function R(r,a){let o="validation",t="invalid";try{let l=m(r);if(!l.success)throw new Error;let e=l.output,{userId:n,billingConfig:d}=a;if(o="auth",t="rejected",typeof n!="string"||!n.trim())throw new Error;if(o="config",t="invalid",!Object.hasOwn(d,e.billingConfigKey)||d[e.billingConfigKey]?.type!=="StripeOrder")throw new Error;o="binding",t="unavailable";let s=await a.resolveOrderBinding({...e,userId:n});if(t="rejected",!s||s.userId!==n||s.sessionId!==e.sessionId||s.billingConfigKey!==e.billingConfigKey||typeof s.orderId!="string"||!s.orderId.trim())throw new Error;o="provider",t="unavailable";let i=await a.retrieveStripeSession(e.sessionId);if(o="response",t="rejected",i.id!==e.sessionId||i.mode!=="payment"||i.metadata?.userId!==n||i.metadata?.billingConfigKey!==e.billingConfigKey||i.metadata?.[y]!==s.orderId)throw new Error;t="invalid";let u=p({sessionId:i.id,orderId:s.orderId,billingConfigKey:e.billingConfigKey,sessionStatus:i.status,paymentStatus:i.payment_status});if(!u.success)throw new Error;return u.output}catch{try{await g.warn("[Checkout verification] Failed",{stage:o,category:t})}catch{}throw new Error("Checkout verification denied")}}c(R,"verifyOrderCheckoutAlgorithm");async function h(r,a,o){let t=f(r);if(!t.success)return{success:!1,error:`Invalid email request: ${t.issues?.map(i=>i.message).join(", ")}`};let l=a.templates[r.templateId];if(!l)return{success:!1,error:`Template not found: ${r.templateId}`};let e=r.locale||"fr",n=l.subject(r.data,e),d=l.html(r.data,e);return{success:!0,messageId:(await o.send({from:r.from||a.defaultFrom,to:r.to,subject:n,html:d,replyTo:r.replyTo||a.replyTo})).messageId}}c(h,"handleEmailRequest");var v="https://api.resend.com/emails";function C(r){if(!r)throw new Error("Resend API key is required");return{async send({from:a,to:o,subject:t,html:l,replyTo:e}){let n={from:a,to:o,subject:t,html:l};e&&(n.reply_to=e);let d=await fetch(v,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!d.ok){let i=await d.text().catch(()=>"Unknown error");throw new Error(`Resend API error (${d.status}): ${i}`)}return{messageId:(await d.json()).id}}}}c(C,"createResendProvider");export{R as a,h as b,C as c};
22
+ //# sourceMappingURL=chunk-GIKHRVAH.js.map
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{b as D,c as b,d as p}from"./chunk-WJUL2W7Y.js";import{E as x,F as a,G as f,V as g,e as w,f as k,h as u,i as y,j as I,m as A,u as T,v as m,w as d,z as c}from"./chunk-Y6BR2QOV.js";import{a as s}from"./chunk-AYY7UXNI.js";import{logger as B}from"firebase-functions/v2";var E={webhookEvent:m({id:a(c(),u(1,"Event ID is required")),type:a(c(),u(1,"Event type is required")),data:m({object:A()}),created:a(T(),y(0,"Valid timestamp required"))}),purchaseRequest:m({userId:a(c(),u(1,"User ID is required")),productType:a(c(),u(1,"Product type is required")),githubUsername:d(a(c(),I(/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,"Invalid GitHub username"))),sessionId:a(c(),u(1,"Session ID is required")),amount:d(a(T(),y(0,"Amount must be positive"))),currency:d(a(c(),k(3,"Currency must be 3 characters")))})};function j(e){try{return{isValid:!0,data:x(E.webhookEvent,e),errors:[]}}catch(r){if(w(r)){let t=r.issues.map(n=>`${n.path?.map(o=>o.key).join(".")||""}: ${n.message}`);return B.warn("Webhook event validation failed",{errors:t,data:e}),{isValid:!1,errors:t}}return{isValid:!1,errors:["Unknown validation error"]}}}s(j,"validateWebhookEvent");function _(e){try{return{isValid:!0,data:x(E.purchaseRequest,e),errors:[]}}catch(r){if(w(r)){let t=r.issues.map(n=>`${n.path?.map(o=>o.key).join(".")||""}: ${n.message}`);return B.warn("Purchase request validation failed",{errors:t,data:e}),{isValid:!1,errors:t}}return{isValid:!1,errors:["Unknown validation error"]}}}s(_,"validatePurchaseRequest");function M(e){return/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/.test(e)}s(M,"validateGitHubUsername");function z(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}s(z,"validateEmail");function L(e){return e.startsWith("price_")&&e.length>6}s(L,"validateStripePriceId");function Z(e){return e.startsWith("cs_")&&e.length>3}s(Z,"validateStripeSessionId");function H(e,r="URL"){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid protocol: ${t.protocol}`);return e}catch(t){throw new Error(`Invalid ${r}: ${e}. ${t instanceof Error?t.message:"Invalid URL format"}`)}}s(H,"validateUrl");function W(e){let r={};for(let[t,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${t}' must be a string, got ${typeof n}`);let o=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(o.length>1e3)throw new Error(`Metadata value for key '${t}' is too long (max 1000 characters)`);if(t.length>100)throw new Error(`Metadata key '${t}' is too long (max 100 characters)`);r[t]=o}return r}s(W,"validateMetadata");function v(e,r,t){let o=f(t||r,e);return o.success?{success:!0,data:o.output}:{success:!1,error:`Validation failed: ${o.issues.map(i=>i.message).join(", ")}`}}s(v,"validateRequestData");function q(e,r){return async(t,n)=>{let o=v(t.data,e,n);if(!o.success)throw new Error(o.error);return await r(t,o.data)}}s(q,"withSchemaValidation");function S(e,r){return async(t,n,o)=>{let i=v(t.body,e,o);return i.success?await r(t,n,i.data):n.status(400).json({error:i.error})}}s(S,"withVercelSchemaValidation");function J(e,r){let t=q(e,r);return{standard:s(n=>t(n),"standard"),withSchema:s((n,o)=>t(n,o),"withSchema")}}s(J,"createFirebaseFunction");function K(e,r){return S(e,r)}s(K,"createVercelFunction");import{onCall as V}from"firebase-functions/v2/https";function C(e,r,t){let n=q(r,t);return{onCall:V(e,async o=>await n(o)),withSchema:s(async(o,i)=>await n(o,i),"withSchema")}}s(C,"createFirebaseCallable");function re(e,r,t){let{onCall:n,withSchema:o}=C(e,r,t);return{[t.name||"mainFunction"]:n,[`${t.name||"mainFunction"}WithSchema`]:o}}s(re,"createFirebaseFunctionExports");function ie(e,r){return S(e,r)}s(ie,"createVercelHandler");function ae(e,r,t){return async(n,o,i)=>{if(n.method!==e)return o.status(405).json({error:"Method not allowed"});let l=v(n.body,r,i);return l.success?await t(n,o,l.data):o.status(400).json({error:l.error})}}s(ae,"createVercelApiHandler");function me(e){if(e instanceof Date)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 new Error("Invalid date format");return t.toISOString()}let r=new Date(e);if(isNaN(r.getTime()))throw new Error("Invalid date format");return r.toISOString()}s(me,"toISOString");function R(e,r){let t=new Date(e),n=t.getDate();return t.setMonth(t.getMonth()+r),t.getDate()!==n&&t.setDate(0),t}s(R,"addMonths");function F(e,r){let t=new Date(e),n=t.getDate();return t.setFullYear(t.getFullYear()+r),t.getDate()!==n&&t.setDate(0),t}s(F,"addYears");function de(e,r=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let t;return e==="1month"?t=R(r,1):e==="3months"?t=R(r,3):e==="6months"?t=R(r,6):e==="1year"?t=F(r,1):e==="2years"?t=F(r,2):t=R(r,1),t.toISOString()}s(de,"calculateSubscriptionEndDate");async function he(e,r){return[]}s(he,"findReferences");function $(e){return{price_pro_monthly:"pro",price_ai_monthly:"ai",price_pro_yearly:"pro",price_ai_yearly:"ai"}[e]||"free"}s($,"getTierFromPriceId");async function N(e,r){if(!e)throw new Error("Firebase UID is required to cancel subscription");let t={tier:"free",subscriptionId:null,customerId:r.customer,status:"canceled",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{let n=b(),o=p(),l=(await n.getUser(e)).customClaims||{};await n.setCustomUserClaims(e,{...l,subscription:t}),await o.collection("subscriptions").doc(e).update({...t,updatedAt:new Date().toISOString()}),console.log(`Subscription canceled for user ${e}:`,{subscriptionId:r.id})}catch(n){throw console.error("Failed to cancel user subscription:",n),new Error("Failed to cancel user subscription")}}s(N,"cancelUserSubscription");async function U(e){try{return(await b().getUser(e)).customClaims?.subscription||null}catch(r){return console.error("Failed to get user subscription:",r),null}}s(U,"getUserSubscription");async function De(){return await D()}s(De,"initializeFirebaseAdmin");import{logger as h}from"firebase-functions/v2";async function Ve(e,r){let t=p();try{let o=await t.collection("idempotency").doc(`${r}_${e}`).get();if(o.exists){let i=o.data();return h.info("Operation already processed (idempotency)",{key:e,operation:r,processedAt:i.processedAt,processedBy:i.processedBy}),i.result}return null}catch(n){throw h.error("Idempotency check failed",{key:e,operation:r,error:n instanceof Error?n.message:String(n)}),new Error(`Idempotency check failed for ${r}/${e}: ${n instanceof Error?n.message:String(n)}`)}}s(Ve,"checkIdempotency");async function Ce(e,r,t,n){try{await p().collection("idempotency").doc(`${r}_${e}`).set({result:t,processedAt:new Date().toISOString(),processedBy:n}),h.info("Idempotency result stored",{key:e,operation:r,processedBy:n})}catch(o){h.error("Failed to store idempotency result",{key:e,operation:r,processedBy:n,error:o instanceof Error?o.message:String(o)})}}s(Ce,"storeIdempotencyResult");function Oe(e){try{return JSON.parse(e)}catch{return null}}s(Oe,"safeJsonParse");function je(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}s(je,"validateCollectionName");function _e(e,r){if(!e||typeof e!="object")throw new g("Invalid document data","invalid-argument");if(Array.isArray(e))throw new g("Document data cannot be an array","invalid-argument");if(r){let t=f(r,e);if(!t.success){let n=t.issues.map(o=>`${o.path?.map(i=>i.key).join(".")||"root"}: ${o.message}`).join("; ");throw new g(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:t.issues}})}}}s(_e,"validateDocument");async function Ye(e,r){let{code:t,redirectUri:n,codeVerifier:o}=e;return await r.exchangeCodeForToken({code:t,redirectUri:n,codeVerifier:o})}s(Ye,"exchangeTokenAlgorithm");async function Qe(e,r,t,n,o){return await o.grantAccess({userId:e,provider:r,accessToken:t,refreshToken:n})}s(Qe,"grantAccessAlgorithm");export{E as a,j as b,_ as c,M as d,z as e,L as f,Z as g,H as h,W as i,v as j,q as k,S as l,J as m,K as n,C as o,re as p,ie as q,ae as r,me as s,de as t,he as u,$ as v,N as w,U as x,De as y,Ve as z,Ce as A,Oe as B,je as C,_e as D,Ye as E,Qe as F};
22
- //# sourceMappingURL=chunk-MJ5VZTLM.js.map
21
+ import{b as D,c as b,d as p}from"./chunk-KVU7ZB5P.js";import{E as x,F as a,G as f,V as g,e as w,f as k,h as u,i as y,j as I,m as A,u as T,v as m,w as d,z as c}from"./chunk-FGXZMPSY.js";import{a as s}from"./chunk-AYY7UXNI.js";import{logger as B}from"firebase-functions/v2";var E={webhookEvent:m({id:a(c(),u(1,"Event ID is required")),type:a(c(),u(1,"Event type is required")),data:m({object:A()}),created:a(T(),y(0,"Valid timestamp required"))}),purchaseRequest:m({userId:a(c(),u(1,"User ID is required")),productType:a(c(),u(1,"Product type is required")),githubUsername:d(a(c(),I(/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,"Invalid GitHub username"))),sessionId:a(c(),u(1,"Session ID is required")),amount:d(a(T(),y(0,"Amount must be positive"))),currency:d(a(c(),k(3,"Currency must be 3 characters")))})};function j(e){try{return{isValid:!0,data:x(E.webhookEvent,e),errors:[]}}catch(r){if(w(r)){let t=r.issues.map(n=>`${n.path?.map(o=>o.key).join(".")||""}: ${n.message}`);return B.warn("Webhook event validation failed",{errors:t,data:e}),{isValid:!1,errors:t}}return{isValid:!1,errors:["Unknown validation error"]}}}s(j,"validateWebhookEvent");function _(e){try{return{isValid:!0,data:x(E.purchaseRequest,e),errors:[]}}catch(r){if(w(r)){let t=r.issues.map(n=>`${n.path?.map(o=>o.key).join(".")||""}: ${n.message}`);return B.warn("Purchase request validation failed",{errors:t,data:e}),{isValid:!1,errors:t}}return{isValid:!1,errors:["Unknown validation error"]}}}s(_,"validatePurchaseRequest");function M(e){return/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/.test(e)}s(M,"validateGitHubUsername");function z(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}s(z,"validateEmail");function L(e){return e.startsWith("price_")&&e.length>6}s(L,"validateStripePriceId");function Z(e){return e.startsWith("cs_")&&e.length>3}s(Z,"validateStripeSessionId");function H(e,r="URL"){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid protocol: ${t.protocol}`);return e}catch(t){throw new Error(`Invalid ${r}: ${e}. ${t instanceof Error?t.message:"Invalid URL format"}`)}}s(H,"validateUrl");function W(e){let r={};for(let[t,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${t}' must be a string, got ${typeof n}`);let o=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(o.length>1e3)throw new Error(`Metadata value for key '${t}' is too long (max 1000 characters)`);if(t.length>100)throw new Error(`Metadata key '${t}' is too long (max 100 characters)`);r[t]=o}return r}s(W,"validateMetadata");function v(e,r,t){let o=f(t||r,e);return o.success?{success:!0,data:o.output}:{success:!1,error:`Validation failed: ${o.issues.map(i=>i.message).join(", ")}`}}s(v,"validateRequestData");function q(e,r){return async(t,n)=>{let o=v(t.data,e,n);if(!o.success)throw new Error(o.error);return await r(t,o.data)}}s(q,"withSchemaValidation");function S(e,r){return async(t,n,o)=>{let i=v(t.body,e,o);return i.success?await r(t,n,i.data):n.status(400).json({error:i.error})}}s(S,"withVercelSchemaValidation");function J(e,r){let t=q(e,r);return{standard:s(n=>t(n),"standard"),withSchema:s((n,o)=>t(n,o),"withSchema")}}s(J,"createFirebaseFunction");function K(e,r){return S(e,r)}s(K,"createVercelFunction");import{onCall as V}from"firebase-functions/v2/https";function C(e,r,t){let n=q(r,t);return{onCall:V(e,async o=>await n(o)),withSchema:s(async(o,i)=>await n(o,i),"withSchema")}}s(C,"createFirebaseCallable");function re(e,r,t){let{onCall:n,withSchema:o}=C(e,r,t);return{[t.name||"mainFunction"]:n,[`${t.name||"mainFunction"}WithSchema`]:o}}s(re,"createFirebaseFunctionExports");function ie(e,r){return S(e,r)}s(ie,"createVercelHandler");function ae(e,r,t){return async(n,o,i)=>{if(n.method!==e)return o.status(405).json({error:"Method not allowed"});let l=v(n.body,r,i);return l.success?await t(n,o,l.data):o.status(400).json({error:l.error})}}s(ae,"createVercelApiHandler");function me(e){if(e instanceof Date)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 new Error("Invalid date format");return t.toISOString()}let r=new Date(e);if(isNaN(r.getTime()))throw new Error("Invalid date format");return r.toISOString()}s(me,"toISOString");function R(e,r){let t=new Date(e),n=t.getDate();return t.setMonth(t.getMonth()+r),t.getDate()!==n&&t.setDate(0),t}s(R,"addMonths");function F(e,r){let t=new Date(e),n=t.getDate();return t.setFullYear(t.getFullYear()+r),t.getDate()!==n&&t.setDate(0),t}s(F,"addYears");function de(e,r=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let t;return e==="1month"?t=R(r,1):e==="3months"?t=R(r,3):e==="6months"?t=R(r,6):e==="1year"?t=F(r,1):e==="2years"?t=F(r,2):t=R(r,1),t.toISOString()}s(de,"calculateSubscriptionEndDate");async function he(e,r){return[]}s(he,"findReferences");function $(e){return{price_pro_monthly:"pro",price_ai_monthly:"ai",price_pro_yearly:"pro",price_ai_yearly:"ai"}[e]||"free"}s($,"getTierFromPriceId");async function N(e,r){if(!e)throw new Error("Firebase UID is required to cancel subscription");let t={tier:"free",subscriptionId:null,customerId:r.customer,status:"canceled",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{let n=b(),o=p(),l=(await n.getUser(e)).customClaims||{};await n.setCustomUserClaims(e,{...l,subscription:t}),await o.collection("subscriptions").doc(e).update({...t,updatedAt:new Date().toISOString()}),console.log(`Subscription canceled for user ${e}:`,{subscriptionId:r.id})}catch(n){throw console.error("Failed to cancel user subscription:",n),new Error("Failed to cancel user subscription")}}s(N,"cancelUserSubscription");async function U(e){try{return(await b().getUser(e)).customClaims?.subscription||null}catch(r){return console.error("Failed to get user subscription:",r),null}}s(U,"getUserSubscription");async function De(){return await D()}s(De,"initializeFirebaseAdmin");import{logger as h}from"firebase-functions/v2";async function Ve(e,r){let t=p();try{let o=await t.collection("idempotency").doc(`${r}_${e}`).get();if(o.exists){let i=o.data();return h.info("Operation already processed (idempotency)",{key:e,operation:r,processedAt:i.processedAt,processedBy:i.processedBy}),i.result}return null}catch(n){throw h.error("Idempotency check failed",{key:e,operation:r,error:n instanceof Error?n.message:String(n)}),new Error(`Idempotency check failed for ${r}/${e}: ${n instanceof Error?n.message:String(n)}`)}}s(Ve,"checkIdempotency");async function Ce(e,r,t,n){try{await p().collection("idempotency").doc(`${r}_${e}`).set({result:t,processedAt:new Date().toISOString(),processedBy:n}),h.info("Idempotency result stored",{key:e,operation:r,processedBy:n})}catch(o){h.error("Failed to store idempotency result",{key:e,operation:r,processedBy:n,error:o instanceof Error?o.message:String(o)})}}s(Ce,"storeIdempotencyResult");function Oe(e){try{return JSON.parse(e)}catch{return null}}s(Oe,"safeJsonParse");function je(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}s(je,"validateCollectionName");function _e(e,r){if(!e||typeof e!="object")throw new g("Invalid document data","invalid-argument");if(Array.isArray(e))throw new g("Document data cannot be an array","invalid-argument");if(r){let t=f(r,e);if(!t.success){let n=t.issues.map(o=>`${o.path?.map(i=>i.key).join(".")||"root"}: ${o.message}`).join("; ");throw new g(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:t.issues}})}}}s(_e,"validateDocument");async function Ye(e,r){let{code:t,redirectUri:n,codeVerifier:o}=e;return await r.exchangeCodeForToken({code:t,redirectUri:n,codeVerifier:o})}s(Ye,"exchangeTokenAlgorithm");async function Qe(e,r,t,n,o){return await o.grantAccess({userId:e,provider:r,accessToken:t,refreshToken:n})}s(Qe,"grantAccessAlgorithm");export{E as a,j as b,_ as c,M as d,z as e,L as f,Z as g,H as h,W as i,v as j,q as k,S as l,J as m,K as n,C as o,re as p,ie as q,ae as r,me as s,de as t,he as u,$ as v,N as w,U as x,De as y,Ve as z,Ce as A,Oe as B,je as C,_e as D,Ye as E,Qe as F};
22
+ //# sourceMappingURL=chunk-H5ZLI4H4.js.map
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a as l}from"./chunk-W6W4L44F.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-YXYTPMRF.js");return i()}o(u,"getFirestore");var s=new Map;async function p(i,e){let a=Date.now(),n=s.get(i);if(n?.blockUntil&&a<n.blockUntil)return{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)};n&&a>=n.windowStart+e.windowMs&&s.delete(i);let t=s.get(i)||{attempts:0,windowStart:a,blockUntil:null};return t.attempts>=e.maxAttempts?(t.blockUntil=a+e.blockDurationMs,s.set(i,t),l.warn("Rate limit exceeded",{key:i,attempts:t.attempts,blockUntil:new Date(t.blockUntil)}),{allowed:!1,remaining:0,resetAt:new Date(t.blockUntil),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)}):(t.attempts+=1,s.set(i,t),{allowed:!0,remaining:e.maxAttempts-t.attempts,resetAt:new Date(t.windowStart+e.windowMs),blockRemainingSeconds:null})}o(p,"checkRateLimit");async function R(i,e){let a=await u(),n=a.collection("rateLimits").doc(i);try{let t=Date.now(),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return await a.runTransaction(async c=>{let d=await c.get(n);if(!d.exists){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}let r=d.data();if(r.blockUntil&&t<r.blockUntil){m={allowed:!1,remaining:0,resetAt:new Date(r.blockUntil),blockRemainingSeconds:Math.ceil((r.blockUntil-t)/1e3)};return}if(t>=r.windowStart+e.windowMs){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}if(r.attempts>=e.maxAttempts){let w=t+e.blockDurationMs;c.update(n,{blockUntil:w,lastUpdated:t}),l.warn("Rate limit exceeded (Firestore)",{key:i,attempts:r.attempts,blockUntil:new Date(w)}),m={allowed:!1,remaining:0,resetAt:new Date(w),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)};return}c.update(n,{attempts:r.attempts+1,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-(r.attempts+1),resetAt:new Date(r.windowStart+e.windowMs),blockRemainingSeconds:null}}),m}catch(t){return l.error("Rate limit check failed",{key:i,error:t instanceof Error?t.message:String(t)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}o(R,"checkRateLimitWithFirestore");function k(i){s.delete(i),l.info("Rate limit reset",{key:i})}o(k,"resetRateLimit");async function g(i){let a=(await u()).collection("rateLimits").doc(i);try{await a.delete(),l.info("Rate limit reset (Firestore)",{key:i})}catch(n){l.error("Failed to reset rate limit",{key:i,error:n instanceof Error?n.message:String(n)})}}o(g,"resetRateLimitInFirestore");function A(i,e){let a=Date.now(),n=s.get(i);return n?n.blockUntil&&a<n.blockUntil?{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)}:a>=n.windowStart+e.windowMs?{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}:{allowed:n.attempts<e.maxAttempts,remaining:Math.max(0,e.maxAttempts-n.attempts),resetAt:new Date(n.windowStart+e.windowMs),blockRemainingSeconds:null}:{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}}o(A,"getRateLimitStatus");var S={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};export{p as a,R as b,k as c,g as d,A as e,S as f};
22
- //# sourceMappingURL=chunk-4BJP372Z.js.map
21
+ import{a as l}from"./chunk-W6W4L44F.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-BABJRPD3.js");return i()}o(u,"getFirestore");var s=new Map;async function p(i,e){let a=Date.now(),n=s.get(i);if(n?.blockUntil&&a<n.blockUntil)return{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)};n&&a>=n.windowStart+e.windowMs&&s.delete(i);let t=s.get(i)||{attempts:0,windowStart:a,blockUntil:null};return t.attempts>=e.maxAttempts?(t.blockUntil=a+e.blockDurationMs,s.set(i,t),l.warn("Rate limit exceeded",{key:i,attempts:t.attempts,blockUntil:new Date(t.blockUntil)}),{allowed:!1,remaining:0,resetAt:new Date(t.blockUntil),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)}):(t.attempts+=1,s.set(i,t),{allowed:!0,remaining:e.maxAttempts-t.attempts,resetAt:new Date(t.windowStart+e.windowMs),blockRemainingSeconds:null})}o(p,"checkRateLimit");async function R(i,e){let a=await u(),n=a.collection("rateLimits").doc(i);try{let t=Date.now(),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return await a.runTransaction(async c=>{let d=await c.get(n);if(!d.exists){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}let r=d.data();if(r.blockUntil&&t<r.blockUntil){m={allowed:!1,remaining:0,resetAt:new Date(r.blockUntil),blockRemainingSeconds:Math.ceil((r.blockUntil-t)/1e3)};return}if(t>=r.windowStart+e.windowMs){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}if(r.attempts>=e.maxAttempts){let w=t+e.blockDurationMs;c.update(n,{blockUntil:w,lastUpdated:t}),l.warn("Rate limit exceeded (Firestore)",{key:i,attempts:r.attempts,blockUntil:new Date(w)}),m={allowed:!1,remaining:0,resetAt:new Date(w),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)};return}c.update(n,{attempts:r.attempts+1,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-(r.attempts+1),resetAt:new Date(r.windowStart+e.windowMs),blockRemainingSeconds:null}}),m}catch(t){return l.error("Rate limit check failed",{key:i,error:t instanceof Error?t.message:String(t)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}o(R,"checkRateLimitWithFirestore");function k(i){s.delete(i),l.info("Rate limit reset",{key:i})}o(k,"resetRateLimit");async function g(i){let a=(await u()).collection("rateLimits").doc(i);try{await a.delete(),l.info("Rate limit reset (Firestore)",{key:i})}catch(n){l.error("Failed to reset rate limit",{key:i,error:n instanceof Error?n.message:String(n)})}}o(g,"resetRateLimitInFirestore");function A(i,e){let a=Date.now(),n=s.get(i);return n?n.blockUntil&&a<n.blockUntil?{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)}:a>=n.windowStart+e.windowMs?{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}:{allowed:n.attempts<e.maxAttempts,remaining:Math.max(0,e.maxAttempts-n.attempts),resetAt:new Date(n.windowStart+e.windowMs),blockRemainingSeconds:null}:{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}}o(A,"getRateLimitStatus");var S={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};export{p as a,R as b,k as c,g as d,A as e,S as f};
22
+ //# sourceMappingURL=chunk-ID7MUXVQ.js.map
@@ -18,6 +18,6 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{$ as s,E as k,aa as P,ca as z,e as $}from"./chunk-Y6BR2QOV.js";import{a as i}from"./chunk-AYY7UXNI.js";import{initializeApp as W,getApps as Z,cert as X}from"firebase-admin/app";import{getAuth as ee}from"firebase-admin/auth";import{getFirestore as te}from"firebase-admin/firestore";import{getFunctions as re}from"firebase-admin/functions";function ne(){let e=Z(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=W({credential:X({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
21
+ import{$ as s,E as k,aa as P,ca as z,e as $}from"./chunk-FGXZMPSY.js";import{a as i}from"./chunk-AYY7UXNI.js";import{initializeApp as W,getApps as Z,cert as X}from"firebase-admin/app";import{getAuth as ee}from"firebase-admin/auth";import{getFirestore as te}from"firebase-admin/firestore";import{getFunctions as re}from"firebase-admin/functions";function ne(){let e=Z(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=W({credential:X({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
22
22
  `)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=W():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:ee(t),firestore:te(t),functions:re(t)}}i(ne,"initializeFirebaseAdminServices");var x=z(ne);async function Se(){try{return x()}catch(e){throw s(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}i(Se,"initFirebaseAdmin");async function L(){let e=x();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}i(L,"getFirebaseAdminApp");function E(){let e=x();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}i(E,"getFirebaseAdminAuth");function J(){let e=x();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}i(J,"getFirebaseAdminFirestore");function Te(){let e=x();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}i(Te,"getFirebaseAdminFunctions");var G=class{static{i(this,"FirebaseServerAuthAdapter")}async verifyToken(t){try{let r=await E().verifyIdToken(t);return{uid:r.uid,email:r.email,claims:r}}catch(r){throw P(r,"FirebaseServerAuthAdapter","verifyToken")}}async getUser(t){try{let r=await E().getUser(t);return{uid:r.uid,email:r.email,displayName:r.displayName,customClaims:r.customClaims??{}}}catch(r){if((typeof r=="object"&&r!==null&&"code"in r?r.code:void 0)==="auth/user-not-found")return null;throw P(r,"FirebaseServerAuthAdapter","getUser",{uid:t})}}async setCustomClaims(t,r){try{let o=(await E().getUser(t)).customClaims??{};await E().setCustomUserClaims(t,{...o,...r})}catch(n){throw P(n,"FirebaseServerAuthAdapter","setCustomClaims",{uid:t})}}};var O={async getServerAdmin(){try{return L()}catch(e){throw s(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return J()}catch(e){throw s(e,"Error getting Admin Firestore")}},async generateServerId(){return(await O.getServerFirestore()).collection("_").doc().id}},Pe=O.getServerAdmin,g=O.getServerFirestore,Oe=O.generateServerId;function H(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:i(()=>new Date(e),"toDate"),toMillis:i(()=>e.getTime(),"toMillis"),isEqual:i(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:i(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}i(H,"createTimestamp");function Ve(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return H(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return H(e)}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to Timestamp")}}i(Ve,"toTimestamp");function oe(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw s(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 s(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to ISO string")}}i(oe,"firestoreToISOString");function ie(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}i(ie,"isTimestamp");function se(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}i(se,"isISODateString");function _e(e){return _(e)}i(_e,"convertISOStringsToDates");function _(e){if(!e)return e;if(Array.isArray(e))return e.map(_);if(typeof e=="string"&&se(e))return new Date(e);if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=_(n);return t}return e}i(_,"convertISOStrings");function D(e,t=!1){return C(e,t)}i(D,"transformFirestoreData");function C(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e.data(),n=C(r);return{id:e.id,...typeof n=="object"?n:{}}}if(Array.isArray(e))return e.map(r=>C(r));if(ie(e))return oe(e);if(typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))r[n]=C(o);return r}return e}i(C,"transformFirestoreValue");function q(e,t=[]){return M(e,t)}i(q,"prepareForFirestore");function M(e,t){if(!e)return e;if(Array.isArray(e))return e.map(r=>M(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))t.includes(n)||o!==void 0&&(r[n]=M(o,t));return r}return e}i(M,"prepareValueForFirestore");function Me(e,t){let r={};for(let[n,o]of Object.entries(t)){if(!(n in e)){r[n]=o;continue}JSON.stringify(e[n])!==JSON.stringify(o)&&(r[n]=o)}return{...r,updatedAt:new Date().toISOString()}}i(Me,"createFirestorePartialUpdate");var F=typeof window<"u";function ce(e){return e.length>0&&typeof e[0]=="string"}i(ce,"isIdList");var b={async batchWrite(e,t,r,n,o={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:a="id",generateIds:d=!0,maxBatchSize:u=450,removeFields:c=[],validate:v=!!n}=o,l={successes:0,failures:0,failedItems:[]};try{let y=[],w=await g(),p=w.batch(),h=0;for(let S=0;S<t.length;S++){let m=t[S];if(!m){l.failures++,l.failedItems?.push({index:S,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!m[a])throw s(new Error(`Missing ID for delete operation (${a})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:a,operation:r}});let f=w.collection(e).doc(m[a]);p.delete(f)}else{if(v&&n)try{k(n,m)}catch(Q){throw s(Q,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:a,itemId:m[a]}})}let f=m[a];if(!f&&r==="create"&&d)f=w.collection(e).doc().id,m={...m,[a]:f};else if(!f)throw s(new Error(`Missing ID for ${r} operation (${a})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:a,operation:r}});let V=[a,...c],T=q(m,V),N=w.collection(e).doc(f);r==="create"?p.create(N,T):r==="update"&&p.update(N,T)}h++,h>=u&&(y.push({batch:p,size:h}),p=w.batch(),h=0)}catch(f){l.failures++,l.failedItems?.push({index:S,error:f instanceof Error?f:new Error(String(f))})}}h>0&&y.push({batch:p,size:h});let R=0;for(let{batch:S,size:m}of y){try{await S.commit(),l.successes+=m}catch(f){let V=f instanceof Error?f:new Error(String(f));for(let T=R;T<R+m;T++)l.failures++,l.failedItems?.push({index:T,error:V})}R+=m}return l}catch(y){throw s(y,{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 b.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return b.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(ce(t)){let n=r.idField||"id",o=t.map(a=>({[n]:a}));return b.batchWrite(e,o,"delete",void 0,r)}return b.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await g()).runTransaction(e)}catch(t){throw s(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:o=!0}=r;try{let a=[];for(let c=0;c<t.length;c+=n)a.push(t.slice(c,c+n));let d=a.map(async c=>{let y=await(await g()).collection(e).where("__name__","in",c).get(),w=new Map;return y.forEach(p=>{w.set(p.id,p.data())}),c.map(p=>{let h=w.get(p);return h?o?D({id:p,...h}):{id:p,...h}:null})});return(await Promise.all(d)).flat()}catch(a){throw s(a,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},A=i(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),ze=F?A("batchWrite"):b.batchWrite,We=F?A("batchCreate"):b.batchCreate,Le=F?A("batchUpdate"):b.batchUpdate,Je=F?A("batchDelete"):b.batchDelete,Ge=F?A("runTransaction"):b.runTransaction,He=F?A("bulkGet"):b.bulkGet;function I(e,t){return s(e,{userMessage:t?`Error during ${t}`:void 0,context:{operation:t}})}i(I,"handleFirebaseError");async function ue(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{let d=await(await g()).collection(r).where(n,"==",e).where("status","==","active").limit(1).get();if(d.empty)return null;let u=d.docs[0];if(!u)return null;let c=u.data();return D({id:u.id,...c})}catch(o){throw I(o,"getActiveSubscription")}}i(ue,"getActiveSubscription");async function ot(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{return(await(await g()).collection(r).where(n,"==",e).orderBy("createdAt","desc").get()).docs.map(u=>D({id:u.id,...u.data()}))}catch(o){throw I(o,"getUserSubscriptions")}}i(ot,"getUserSubscriptions");async function de(e,t={}){let{collection:r="subscriptions"}=t;try{let n=await g(),o=new Date().toISOString(),a={...e,createdAt:e.createdAt||o,updatedAt:o},d=q(a),{id:u,...c}=d,v=u?n.collection(r).doc(u):n.collection(r).doc();return await v.set(c,{merge:!0}),{...a,id:v.id}}catch(n){throw I(n,"saveSubscription")}}i(de,"saveSubscription");async function le(e,t,r={}){let{collection:n="subscriptions"}=r;try{await(await g()).collection(n).doc(e).update({status:t,updatedAt:new Date().toISOString()})}catch(o){throw I(o,"updateSubscriptionStatus")}}i(le,"updateSubscriptionStatus");async function it(e,t,r={}){try{let n=await ue(e,r);return n?n.features&&Array.isArray(n.features)?n.features.includes(t):n.metadata&&n.metadata[t]?n.metadata[t]==="true":!1:!1}catch(n){throw s(n,{userMessage:"Failed to check feature access",severity:"error",context:{function:"hasFeatureAccess",userId:e,featureKey:t}})}}i(it,"hasFeatureAccess");async function st(e){let{rawBody:t,signature:r,webhookSecret:n,...o}=e,a;try{let u=await import("stripe"),c=u.default??u;a=new c("placeholder",{apiVersion:"2023-10-16"})}catch{throw s(new Error("stripe package is not installed"),{userMessage:"Stripe package missing \u2014 cannot verify webhook signature",severity:"error"})}let d;try{d=a.webhooks.constructEvent(t,r,n)}catch(u){throw s(u,{userMessage:"Stripe webhook signature verification failed",severity:"error",context:{function:"verifyAndHandleStripeWebhook"}})}await fe(d,o)}i(st,"verifyAndHandleStripeWebhook");async function fe(e,t={}){let r=e.type,n=e.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await pe(n,t);break;case"customer.subscription.deleted":await le(n.id,"canceled",t);break;default:}}catch(o){throw s(o,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:e.id}})}}i(fe,"handleStripeWebhookEvent");async function pe(e,t={}){if(!e.items.data.length)throw s(new Error("[subscription] Stripe subscription has no items"),{userMessage:"Stripe subscription has no items \u2014 cannot determine plan",severity:"error",context:{subscriptionId:e.id}});let r={id:e.id,customerId:e.customer,status:e.status,planId:e.items.data[0]?.plan.id||"",currentPeriodStart:new Date(e.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(e.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:e.cancel_at_period_end,metadata:e.metadata||{},createdAt:new Date(e.created*1e3).toISOString(),updatedAt:new Date().toISOString()};e.canceled_at&&(r.canceledAt=new Date(e.canceled_at*1e3).toISOString()),await de(r,t)}i(pe,"saveSubscriptionFromStripeEvent");var U={};function B(e){U.uniqueConstraintValidator=e}i(B,"registerUniqueConstraintValidator");function K(){return U.uniqueConstraintValidator}i(K,"getUniqueConstraintValidator");function me(){return!!U.uniqueConstraintValidator}i(me,"hasUniqueConstraintValidator");async function Y(){let e=await g(),t={checkDuplicate:i(async(r,n,o,a)=>{if(o==null)return!1;try{return(await e.collection(r).where(n,"==",o).get()).docs.some(c=>c.id!==a&&c.data()[n]===o)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:o}})}},"checkDuplicate")};return B(t),t}i(Y,"createFirestoreValidator");async function ge(){let e=await g(),t={checkDuplicate:i(async(r,n,o,a)=>{if(o==null)return!1;try{return(await e.collection(r).where(n,"==",o).get()).docs.some(c=>c.id!==a&&c.data()[n]===o)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:o}})}},"checkDuplicate")};return B(t),t}i(ge,"createAdminFirestoreValidator");async function j(e,t,r,n){if(!t.length)return;let o=K();o||(o=await Y());let a=[],u=(await Promise.allSettled(t.map(async({field:c,errorMessage:v})=>{let l=r[c];if(l==null)return;await o.checkDuplicate(e,c,l,n)&&a.push({field:c,message:v||`The ${c} must be unique`})}))).find(c=>c.status==="rejected");if(u&&u.status==="rejected")throw u.reason;if(a.length>0)throw s(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:a,collection:e}})}i(j,"validateUniqueness");async function gt(e,t,r,n){try{k(e,t),e.metadata?.uniqueFields?.length&&await j(e.metadata.collection,e.metadata.uniqueFields,t,n),e.metadata?.customValidate&&await e.metadata.customValidate(t,r)}catch(o){throw $(o)?s(o,{userMessage:"Document validation failed",context:{validationErrors:o.issues,data:t},severity:"warning"}):s(o,{userMessage:"Document validation failed",context:{collection:e.metadata?.collection||"unknown"},severity:"error"})}}i(gt,"validateFirestoreDocument");function ht(e,t){return Object.assign(e,{metadata:t})}i(ht,"enhanceSchema");import{FieldValue as kt,Query as Pt,Timestamp as Ot}from"firebase-admin/firestore";export{Se as a,L as b,E as c,J as d,Te as e,G as f,Pe as g,g as h,Oe as i,H as j,Ve as k,oe as l,ie as m,_e as n,D as o,q as p,Me as q,ze as r,We as s,Le as t,Je as u,Ge as v,He as w,ue as x,ot as y,de as z,le as A,it as B,st as C,B as D,K as E,me as F,Y as G,ge as H,j as I,gt as J,ht as K,kt as L,Pt as M,Ot as N};
23
- //# sourceMappingURL=chunk-WJUL2W7Y.js.map
23
+ //# sourceMappingURL=chunk-KVU7ZB5P.js.map