@vee_stack/cli 6.2.3 → 6.2.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 (2) hide show
  1. package/dist/index.js +20 -20
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import {createRequire}from'module';import*as re from'fs';import {existsSync,readFileSync,writeFileSync,statSync}from'fs';import*as Je from'path';import {join,resolve,dirname}from'path';import {fileURLToPath}from'url';import {glob}from'glob';import*as de from'crypto';import de__default from'crypto';import h from'chalk';import {Command}from'commander';import _i from'ora';import ki from'cli-table3';import Si from'cli-progress';import*as ct from'os';import {homedir}from'os';import*as L from'fs/promises';import br from'prompts';import qi from'readline';import ta from'open';import {execSync}from'child_process';import Ma from'omelette';createRequire(import.meta.url);
3
- var as=Object.defineProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var zn=(t,e)=>{for(var n in e)as(t,n,{get:e[n],enumerable:true});};function _s(){let t=vs,e=0;for(;t!==dirname(t)&&e<10;){let n=join(t,"package.json");try{if(existsSync(n)){let r=JSON.parse(readFileSync(n,"utf-8"));if(r.name==="vee_stack")return r}}catch{}t=dirname(t),e++;}return null}var ys,vs,qn,ie,gn,V,B,hn,ae,Qe,Ut,vn,_n=G(()=>{ys=fileURLToPath(import.meta.url),vs=dirname(ys),qn="6.2.3",ie={snapshot:"2.0.0",engine_target:"2.0.0",audit:"3.0",session_payload:"2.0.0",rules:"2.0.0",analysis:"2.0.0",api:"v2",min_node:20};gn=_s();gn&&(qn=gn.version,ie=gn.versions||ie);V=qn,B=V,hn=`vs_cli_v${V}`,ae=ie.snapshot,Qe=ie.engine_target,Ut=ie.audit,ie.session_payload,ie.rules,ie.analysis,vn=ie.api,ie.min_node;});var T,kn,g,ce,mt=G(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let o={};for(let a of s)o[a]=a;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(let i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(let a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o;})(T||(T={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n});})(kn||(kn={}));g=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ce=t=>{switch(typeof t){case "undefined":return g.undefined;case "string":return g.string;case "number":return Number.isNaN(t)?g.nan:g.number;case "boolean":return g.boolean;case "function":return g.function;case "bigint":return g.bigint;case "symbol":return g.symbol;case "object":return Array.isArray(t)?g.array:t===null?g.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?g.promise:typeof Map<"u"&&t instanceof Map?g.map:typeof Set<"u"&&t instanceof Set?g.set:typeof Date<"u"&&t instanceof Date?g.date:g.object;default:return g.unknown}};});var u,Ts,Y,$t=G(()=>{mt();u=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ts=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Y=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r];},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r];};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e;}format(e){let n=e||function(o){return o.message},r={_errors:[]},s=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else {let i=r,l=0;for(;l<a.path.length;){let c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(n(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++;}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(e(s));}else r.push(e(s));return {formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Y.create=t=>new Y(t);});var xs,pe,En=G(()=>{$t();mt();xs=(t,e)=>{let n;switch(t.code){case u.invalid_type:t.received===g.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case u.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,T.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:n=`Unrecognized key(s) in object: ${T.joinValues(t.keys,", ")}`;break;case u.invalid_union:n="Invalid input";break;case u.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${T.joinValues(t.options)}`;break;case u.invalid_enum_value:n=`Invalid enum value. Expected ${T.joinValues(t.options)}, received '${t.received}'`;break;case u.invalid_arguments:n="Invalid function arguments";break;case u.invalid_return_type:n="Invalid function return type";break;case u.invalid_date:n="Invalid date";break;case u.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:T.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case u.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case u.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case u.custom:n="Invalid input";break;case u.invalid_intersection_types:n="Intersection results could not be merged";break;case u.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case u.not_finite:n="Number must be finite";break;default:n=e.defaultError,T.assertNever(t);}return {message:n}},pe=xs;});function As(t){Xn=t;}function et(){return Xn}var Xn,Mt=G(()=>{En();Xn=pe;});function p(t,e){let n=et(),r=ht({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===pe?void 0:pe].filter(s=>!!s)});t.common.issues.push(r);}var ht,Rs,$,y,Re,M,Ft,Vt,ke,tt,Sn=G(()=>{Mt();En();ht=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return {...s,path:o,message:s.message};let i="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)i=c(a,{data:e,defaultError:i}).message;return {...s,path:o,message:i}},Rs=[];$=class t{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return y;s.status==="dirty"&&e.dirty(),r.push(s.value);}return {status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let o=await s.key,a=await s.value;r.push({key:o,value:a});}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return y;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value);}return {status:e.value,value:r}}},y=Object.freeze({status:"aborted"}),Re=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),Ft=t=>t.status==="aborted",Vt=t=>t.status==="dirty",ke=t=>t.status==="valid",tt=t=>typeof Promise<"u"&&t instanceof Promise;});var Qn=G(()=>{});var m,er=G(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message;})(m||(m={}));});function S(t){if(!t)return {};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:s}}function sr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function zs(t){return new RegExp(`^${sr(t)}$`)}function or(t){let e=`${rr}T${sr(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ws(t,e){return !!((e==="v4"||!e)&&Us.test(t)||(e==="v6"||!e)&&Ms.test(t))}function Gs(t,e){if(!Ds.test(t))return false;try{let[n]=t.split(".");if(!n)return !1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return !(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return false}}function Ys(t,e){return !!((e==="v4"||!e)&&$s.test(t)||(e==="v6"||!e)&&Fs.test(t))}function Zs(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function nt(t){if(t instanceof Z){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ee.create(nt(r));}return new Z({...t._def,shape:()=>e})}else return t instanceof me?new me({...t._def,type:nt(t.element)}):t instanceof ee?ee.create(nt(t.unwrap())):t instanceof ue?ue.create(nt(t.unwrap())):t instanceof le?le.create(t.items.map(e=>nt(e))):t}function Tn(t,e){let n=ce(t),r=ce(e);if(t===e)return {valid:true,data:t};if(n===g.object&&r===g.object){let s=T.objectKeys(e),o=T.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(let i of o){let l=Tn(t[i],e[i]);if(!l.valid)return {valid:false};a[i]=l.data;}return {valid:true,data:a}}else if(n===g.array&&r===g.array){if(t.length!==e.length)return {valid:false};let s=[];for(let o=0;o<t.length;o++){let a=t[o],i=e[o],l=Tn(a,i);if(!l.valid)return {valid:false};s.push(l.data);}return {valid:true,data:s}}else return n===g.date&&r===g.date&&+t==+e?{valid:true,data:t}:{valid:false}}function ir(t,e){return new $e({values:t,typeName:v.ZodEnum,...S(e)})}function nr(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function ar(t,e={},n){return t?Se.create().superRefine((r,s)=>{let o=t(r);if(o instanceof Promise)return o.then(a=>{if(!a){let i=nr(e,r),l=i.fatal??n??true;s.addIssue({code:"custom",...i,fatal:l});}});if(!o){let a=nr(e,r),i=a.fatal??n??true;s.addIssue({code:"custom",...a,fatal:i});}}):Se.create()}var te,tr,w,bs,Cs,Is,Ns,Os,Ds,Ps,js,Ls,wn,Us,$s,Ms,Fs,Vs,Bs,rr,Hs,Ee,be,Ce,Ie,Ne,rt,Oe,De,Se,ge,se,st,me,Z,Pe,fe,Bt,je,le,Ht,ot,it,zt,Le,Ue,$e,Me,we,ne,ee,ue,Fe,Ve,at,Js,yt,vt,Be,Ks,v,qs,cr,lr,Xs,Qs,ur,eo,to,no,ro,so,oo,io,ao,co,lo,uo,po,fo,go,mo,ho,yo,vo,_o,ko,Eo,So,wo,To,xo,Ao,Ro,bo,Co,Io,No,Oo,Do,Po,dr=G(()=>{$t();Mt();er();Sn();mt();te=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s;}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},tr=(t,e)=>{if(ke(e))return {success:true,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let n=new Y(t.common.issues);return this._error=n,this._error}}};w=class{get description(){return this._def.description}_getType(e){return ce(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new $,ctx:{common:e.parent.common,data:e.data,parsedType:ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(tt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??false,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ce(e)},s=this._parseSync({data:e,path:r.path,parent:r});return tr(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ce(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ke(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),n.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:n}).then(r=>ke(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:true},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ce(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(tt(s)?s:Promise.resolve(s));return tr(r,o)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let a=e(s),i=()=>o.addIssue({code:u.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?true:(i(),false)):a?true:(i(),false)})}refinement(e,n){return this._refinement((r,s)=>e(r)?true:(s.addIssue(typeof n=="function"?n(r,s):n),false))}_refinement(e){return new ne({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)};}optional(){return ee.create(this,this._def)}nullable(){return ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return we.create(this,this._def)}or(e){return Pe.create([this,e],this._def)}and(e){return je.create(this,e,this._def)}transform(e){return new ne({...S(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Fe({...S(this._def),innerType:this,defaultValue:n,typeName:v.ZodDefault})}brand(){return new yt({typeName:v.ZodBranded,type:this,...S(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ve({...S(this._def),innerType:this,catchValue:n,typeName:v.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return vt.create(this,e)}readonly(){return Be.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bs=/^c[^\s-]{8,}$/i,Cs=/^[0-9a-z]+$/,Is=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ns=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Os=/^[a-z0-9_-]{21}$/i,Ds=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ps=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,js=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ls="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Us=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$s=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ms=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Fs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Bs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Hs=new RegExp(`^${rr}$`);Ee=class t extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==g.string){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_type,expected:g.string,received:o.parsedType}),y}let r=new $,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,minimum:o.value,type:"string",inclusive:true,exact:false,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,maximum:o.value,type:"string",inclusive:true,exact:false,message:o.message}),r.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?p(s,{code:u.too_big,maximum:o.value,type:"string",inclusive:true,exact:true,message:o.message}):i&&p(s,{code:u.too_small,minimum:o.value,type:"string",inclusive:true,exact:true,message:o.message}),r.dirty());}else if(o.kind==="email")js.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")wn||(wn=new RegExp(Ls,"u")),wn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Ns.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Os.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")bs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Cs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Is.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data);}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:u.invalid_string,message:o.message}),r.dirty();}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:u.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?or(o).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Hs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?zs(o).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Ps.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ws(e.data,o.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Gs(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Ys(e.data,o.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Vs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Bs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:u.invalid_string,message:o.message}),r.dirty()):T.assertNever(o);return {status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:u.invalid_string,...m.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...m.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...m.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...m.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...m.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...m.errToObj(n)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return !!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return !!this._def.checks.find(e=>e.kind==="date")}get isTime(){return !!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return !!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return !!this._def.checks.find(e=>e.kind==="email")}get isURL(){return !!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return !!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return !!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return !!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return !!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return !!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return !!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return !!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return !!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return !!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return !!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ee.create=t=>new Ee({checks:[],typeName:v.ZodString,coerce:t?.coerce??false,...S(t)});be=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf;}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==g.number){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_type,expected:g.number,received:o.parsedType}),y}let r,s=new $;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:u.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),s.dirty()):o.kind==="multipleOf"?Zs(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:u.not_finite,message:o.message}),s.dirty()):T.assertNever(o);return {status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,true,m.toString(n))}gt(e,n){return this.setLimit("min",e,false,m.toString(n))}lte(e,n){return this.setLimit("max",e,true,m.toString(n))}lt(e,n){return this.setLimit("max",e,false,m.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:m.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:m.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return !!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return true;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);}return Number.isFinite(n)&&Number.isFinite(e)}};be.create=t=>new be({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||false,...S(t)});Ce=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data);}catch{return this._getInvalidInput(e)}if(this._getType(e)!==g.bigint)return this._getInvalidInput(e);let r,s=new $;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):T.assertNever(o);return {status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:g.bigint,received:n.parsedType}),y}gte(e,n){return this.setLimit("min",e,true,m.toString(n))}gt(e,n){return this.setLimit("min",e,false,m.toString(n))}lte(e,n){return this.setLimit("max",e,true,m.toString(n))}lt(e,n){return this.setLimit("max",e,false,m.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:m.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:m.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ce.create=t=>new Ce({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??false,...S(t)});Ie=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.boolean,received:r.parsedType}),y}return M(e.data)}};Ie.create=t=>new Ie({typeName:v.ZodBoolean,coerce:t?.coerce||false,...S(t)});Ne=class t extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==g.date){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_type,expected:g.date,received:o.parsedType}),y}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_date}),y}let r=new $,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,message:o.message,inclusive:true,exact:false,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,message:o.message,inclusive:true,exact:false,maximum:o.value,type:"date"}),r.dirty()):T.assertNever(o);return {status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Ne.create=t=>new Ne({checks:[],coerce:t?.coerce||false,typeName:v.ZodDate,...S(t)});rt=class extends w{_parse(e){if(this._getType(e)!==g.symbol){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.symbol,received:r.parsedType}),y}return M(e.data)}};rt.create=t=>new rt({typeName:v.ZodSymbol,...S(t)});Oe=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.undefined,received:r.parsedType}),y}return M(e.data)}};Oe.create=t=>new Oe({typeName:v.ZodUndefined,...S(t)});De=class extends w{_parse(e){if(this._getType(e)!==g.null){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.null,received:r.parsedType}),y}return M(e.data)}};De.create=t=>new De({typeName:v.ZodNull,...S(t)});Se=class extends w{constructor(){super(...arguments),this._any=true;}_parse(e){return M(e.data)}};Se.create=t=>new Se({typeName:v.ZodAny,...S(t)});ge=class extends w{constructor(){super(...arguments),this._unknown=true;}_parse(e){return M(e.data)}};ge.create=t=>new ge({typeName:v.ZodUnknown,...S(t)});se=class extends w{_parse(e){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:g.never,received:n.parsedType}),y}};se.create=t=>new se({typeName:v.ZodNever,...S(t)});st=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.void,received:r.parsedType}),y}return M(e.data)}};st.create=t=>new st({typeName:v.ZodVoid,...S(t)});me=class t extends w{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==g.array)return p(n,{code:u.invalid_type,expected:g.array,received:n.parsedType}),y;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,i=n.data.length<s.exactLength.value;(a||i)&&(p(n,{code:a?u.too_big:u.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:s.exactLength.message}),r.dirty());}if(s.minLength!==null&&n.data.length<s.minLength.value&&(p(n,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:true,exact:false,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(p(n,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:true,exact:false,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,i)=>s.type._parseAsync(new te(n,a,n.path,i)))).then(a=>$.mergeArray(r,a));let o=[...n.data].map((a,i)=>s.type._parseSync(new te(n,a,n.path,i)));return $.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:m.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:m.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:m.toString(n)}})}nonempty(e){return this.min(1,e)}};me.create=(t,e)=>new me({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...S(e)});Z=class t extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend;}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=T.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==g.object){let c=this._getOrReturnCtx(e);return p(c,{code:u.invalid_type,expected:g.object,received:c.parsedType}),y}let{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof se&&this._def.unknownKeys==="strip"))for(let c in s.data)a.includes(c)||i.push(c);let l=[];for(let c of a){let f=o[c],_=s.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new te(s,_,s.path,c)),alwaysSet:c in s.data});}if(this._def.catchall instanceof se){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of i)l.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")i.length>0&&(p(s,{code:u.unrecognized_keys,keys:i}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let c=this._def.catchall;for(let f of i){let _=s.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new te(s,_,s.path,f)),alwaysSet:f in s.data});}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let _=await f.key,b=await f.value;c.push({key:_,value:b,alwaysSet:f.alwaysSet});}return c}).then(c=>$.mergeObjectSync(r,c)):$.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:m.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of T.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of T.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return nt(this)}partial(e){let n={};for(let r of T.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional();}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of T.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else {let o=this.shape[r];for(;o instanceof ee;)o=o._def.innerType;n[r]=o;}return new t({...this._def,shape:()=>n})}keyof(){return ir(T.objectKeys(this.shape))}};Z.create=(t,e)=>new Z({shape:()=>t,unknownKeys:"strip",catchall:se.create(),typeName:v.ZodObject,...S(e)});Z.strictCreate=(t,e)=>new Z({shape:()=>t,unknownKeys:"strict",catchall:se.create(),typeName:v.ZodObject,...S(e)});Z.lazycreate=(t,e)=>new Z({shape:t,unknownKeys:"strip",catchall:se.create(),typeName:v.ZodObject,...S(e)});Pe=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(o){for(let i of o)if(i.result.status==="valid")return i.result;for(let i of o)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(i=>new Y(i.ctx.common.issues));return p(n,{code:u.invalid_union,unionErrors:a}),y}if(n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return {result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o,a=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:c}),c.common.issues.length&&a.push(c.common.issues);}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(l=>new Y(l));return p(n,{code:u.invalid_union,unionErrors:i}),y}}get options(){return this._def.options}};Pe.create=(t,e)=>new Pe({options:t,typeName:v.ZodUnion,...S(e)});fe=t=>t instanceof Le?fe(t.schema):t instanceof ne?fe(t.innerType()):t instanceof Ue?[t.value]:t instanceof $e?t.options:t instanceof Me?T.objectValues(t.enum):t instanceof Fe?fe(t._def.innerType):t instanceof Oe?[void 0]:t instanceof De?[null]:t instanceof ee?[void 0,...fe(t.unwrap())]:t instanceof ue?[null,...fe(t.unwrap())]:t instanceof yt||t instanceof Be?fe(t.unwrap()):t instanceof Ve?fe(t._def.innerType):[],Bt=class t extends w{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.object)return p(n,{code:u.invalid_type,expected:g.object,received:n.parsedType}),y;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(p(n,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let o of n){let a=fe(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o);}}return new t({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...S(r)})}};je=class extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(o,a)=>{if(Ft(o)||Ft(a))return y;let i=Tn(o.value,a.value);return i.valid?((Vt(o)||Vt(a))&&n.dirty(),{status:n.value,value:i.data}):(p(r,{code:u.invalid_intersection_types}),y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};je.create=(t,e,n)=>new je({left:t,right:e,typeName:v.ZodIntersection,...S(n)});le=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.array)return p(r,{code:u.invalid_type,expected:g.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return p(r,{code:u.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:u.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),n.dirty());let o=[...r.data].map((a,i)=>{let l=this._def.items[i]||this._def.rest;return l?l._parse(new te(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>$.mergeArray(n,a)):$.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};le.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new le({items:t,typeName:v.ZodTuple,rest:null,...S(e)})};Ht=class t extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.object)return p(r,{code:u.invalid_type,expected:g.object,received:r.parsedType}),y;let s=[],o=this._def.keyType,a=this._def.valueType;for(let i in r.data)s.push({key:o._parse(new te(r,i,r.path,i)),value:a._parse(new te(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?$.mergeObjectAsync(n,s):$.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof w?new t({keyType:e,valueType:n,typeName:v.ZodRecord,...S(r)}):new t({keyType:Ee.create(),valueType:e,typeName:v.ZodRecord,...S(n)})}},ot=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.map)return p(r,{code:u.invalid_type,expected:g.map,received:r.parsedType}),y;let s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([i,l],c)=>({key:s._parse(new te(r,i,r.path,[c,"key"])),value:o._parse(new te(r,l,r.path,[c,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let l of a){let c=await l.key,f=await l.value;if(c.status==="aborted"||f.status==="aborted")return y;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),i.set(c.value,f.value);}return {status:n.value,value:i}})}else {let i=new Map;for(let l of a){let c=l.key,f=l.value;if(c.status==="aborted"||f.status==="aborted")return y;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),i.set(c.value,f.value);}return {status:n.value,value:i}}}};ot.create=(t,e,n)=>new ot({valueType:e,keyType:t,typeName:v.ZodMap,...S(n)});it=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.set)return p(r,{code:u.invalid_type,expected:g.set,received:r.parsedType}),y;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(p(r,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:true,exact:false,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(p(r,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:true,exact:false,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function a(l){let c=new Set;for(let f of l){if(f.status==="aborted")return y;f.status==="dirty"&&n.dirty(),c.add(f.value);}return {status:n.value,value:c}}let i=[...r.data.values()].map((l,c)=>o._parse(new te(r,l,r.path,c)));return r.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(e,n){return new t({...this._def,minSize:{value:e,message:m.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:m.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};it.create=(t,e)=>new it({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...S(e)});zt=class t extends w{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.function)return p(n,{code:u.invalid_type,expected:g.function,received:n.parsedType}),y;function r(i,l){return ht({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,et(),pe].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(i,l){return ht({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,et(),pe].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof we){let i=this;return M(async function(...l){let c=new Y([]),f=await i._def.args.parseAsync(l,o).catch(x=>{throw c.addIssue(r(l,x)),c}),_=await Reflect.apply(a,this,f);return await i._def.returns._def.type.parseAsync(_,o).catch(x=>{throw c.addIssue(s(_,x)),c})})}else {let i=this;return M(function(...l){let c=i._def.args.safeParse(l,o);if(!c.success)throw new Y([r(l,c.error)]);let f=Reflect.apply(a,this,c.data),_=i._def.returns.safeParse(f,o);if(!_.success)throw new Y([s(f,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:le.create(e).rest(ge.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||le.create([]).rest(ge.create()),returns:n||ge.create(),typeName:v.ZodFunction,...S(r)})}},Le=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Le.create=(t,e)=>new Le({getter:t,typeName:v.ZodLazy,...S(e)});Ue=class extends w{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return p(n,{received:n.data,code:u.invalid_literal,expected:this._def.value}),y}return {status:"valid",value:e.data}}get value(){return this._def.value}};Ue.create=(t,e)=>new Ue({value:t,typeName:v.ZodLiteral,...S(e)});$e=class t extends w{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return p(n,{expected:T.joinValues(r),received:n.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return p(n,{received:n.data,code:u.invalid_enum_value,options:r}),y}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};$e.create=ir;Me=class extends w{_parse(e){let n=T.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==g.string&&r.parsedType!==g.number){let s=T.objectValues(n);return p(r,{expected:T.joinValues(s),received:r.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(T.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=T.objectValues(n);return p(r,{received:r.data,code:u.invalid_enum_value,options:s}),y}return M(e.data)}get enum(){return this._def.values}};Me.create=(t,e)=>new Me({values:t,typeName:v.ZodNativeEnum,...S(e)});we=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.promise&&n.common.async===false)return p(n,{code:u.invalid_type,expected:g.promise,received:n.parsedType}),y;let r=n.parsedType===g.promise?n.data:Promise.resolve(n.data);return M(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};we.create=(t,e)=>new we({type:t,typeName:v.ZodPromise,...S(e)});ne=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{p(r,a),a.fatal?n.abort():n.dirty();},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async i=>{if(n.value==="aborted")return y;let l=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return l.status==="aborted"?y:l.status==="dirty"?Re(l.value):n.value==="dirty"?Re(l.value):l});{if(n.value==="aborted")return y;let i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?y:i.status==="dirty"?Re(i.value):n.value==="dirty"?Re(i.value):i}}if(s.type==="refinement"){let a=i=>{let l=s.refinement(i,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===false){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?y:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?y:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.value}))))}if(s.type==="transform")if(r.common.async===false){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ke(a))return y;let i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ke(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:n.value,value:i})):y);T.assertNever(s);}};ne.create=(t,e,n)=>new ne({schema:t,typeName:v.ZodEffects,effect:e,...S(n)});ne.createWithPreprocess=(t,e,n)=>new ne({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...S(n)});ee=class extends w{_parse(e){return this._getType(e)===g.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ee.create=(t,e)=>new ee({innerType:t,typeName:v.ZodOptional,...S(e)});ue=class extends w{_parse(e){return this._getType(e)===g.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ue.create=(t,e)=>new ue({innerType:t,typeName:v.ZodNullable,...S(e)});Fe=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===g.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Fe.create=(t,e)=>new Fe({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});Ve=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return tt(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Y(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Y(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ve.create=(t,e)=>new Ve({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});at=class extends w{_parse(e){if(this._getType(e)!==g.nan){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.nan,received:r.parsedType}),y}return {status:"valid",value:e.data}}};at.create=t=>new at({typeName:v.ZodNaN,...S(t)});Js=Symbol("zod_brand"),yt=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},vt=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return (async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?y:o.status==="dirty"?(n.dirty(),Re(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?y:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:v.ZodPipeline})}},Be=class extends w{_parse(e){let n=this._def.innerType._parse(e),r=s=>(ke(s)&&(s.value=Object.freeze(s.value)),s);return tt(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:v.ZodReadonly,...S(e)});Ks={object:Z.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly";})(v||(v={}));qs=(t,e={message:`Input not instance of ${t.name}`})=>ar(n=>n instanceof t,e),cr=Ee.create,lr=be.create,Xs=at.create,Qs=Ce.create,ur=Ie.create,eo=Ne.create,to=rt.create,no=Oe.create,ro=De.create,so=Se.create,oo=ge.create,io=se.create,ao=st.create,co=me.create,lo=Z.create,uo=Z.strictCreate,po=Pe.create,fo=Bt.create,go=je.create,mo=le.create,ho=Ht.create,yo=ot.create,vo=it.create,_o=zt.create,ko=Le.create,Eo=Ue.create,So=$e.create,wo=Me.create,To=we.create,xo=ne.create,Ao=ee.create,Ro=ue.create,bo=ne.createWithPreprocess,Co=vt.create,Io=()=>cr().optional(),No=()=>lr().optional(),Oo=()=>ur().optional(),Do={string:(t=>Ee.create({...t,coerce:true})),number:(t=>be.create({...t,coerce:true})),boolean:(t=>Ie.create({...t,coerce:true})),bigint:(t=>Ce.create({...t,coerce:true})),date:(t=>Ne.create({...t,coerce:true}))},Po=y;});var d={};zn(d,{BRAND:()=>Js,DIRTY:()=>Re,EMPTY_PATH:()=>Rs,INVALID:()=>y,NEVER:()=>Po,OK:()=>M,ParseStatus:()=>$,Schema:()=>w,ZodAny:()=>Se,ZodArray:()=>me,ZodBigInt:()=>Ce,ZodBoolean:()=>Ie,ZodBranded:()=>yt,ZodCatch:()=>Ve,ZodDate:()=>Ne,ZodDefault:()=>Fe,ZodDiscriminatedUnion:()=>Bt,ZodEffects:()=>ne,ZodEnum:()=>$e,ZodError:()=>Y,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>zt,ZodIntersection:()=>je,ZodIssueCode:()=>u,ZodLazy:()=>Le,ZodLiteral:()=>Ue,ZodMap:()=>ot,ZodNaN:()=>at,ZodNativeEnum:()=>Me,ZodNever:()=>se,ZodNull:()=>De,ZodNullable:()=>ue,ZodNumber:()=>be,ZodObject:()=>Z,ZodOptional:()=>ee,ZodParsedType:()=>g,ZodPipeline:()=>vt,ZodPromise:()=>we,ZodReadonly:()=>Be,ZodRecord:()=>Ht,ZodSchema:()=>w,ZodSet:()=>it,ZodString:()=>Ee,ZodSymbol:()=>rt,ZodTransformer:()=>ne,ZodTuple:()=>le,ZodType:()=>w,ZodUndefined:()=>Oe,ZodUnion:()=>Pe,ZodUnknown:()=>ge,ZodVoid:()=>st,addIssueToContext:()=>p,any:()=>so,array:()=>co,bigint:()=>Qs,boolean:()=>ur,coerce:()=>Do,custom:()=>ar,date:()=>eo,datetimeRegex:()=>or,defaultErrorMap:()=>pe,discriminatedUnion:()=>fo,effect:()=>xo,enum:()=>So,function:()=>_o,getErrorMap:()=>et,getParsedType:()=>ce,instanceof:()=>qs,intersection:()=>go,isAborted:()=>Ft,isAsync:()=>tt,isDirty:()=>Vt,isValid:()=>ke,late:()=>Ks,lazy:()=>ko,literal:()=>Eo,makeIssue:()=>ht,map:()=>yo,nan:()=>Xs,nativeEnum:()=>wo,never:()=>io,null:()=>ro,nullable:()=>Ro,number:()=>lr,object:()=>lo,objectUtil:()=>kn,oboolean:()=>Oo,onumber:()=>No,optional:()=>Ao,ostring:()=>Io,pipeline:()=>Co,preprocess:()=>bo,promise:()=>To,quotelessJson:()=>Ts,record:()=>ho,set:()=>vo,setErrorMap:()=>As,strictObject:()=>uo,string:()=>cr,symbol:()=>to,transformer:()=>xo,tuple:()=>mo,undefined:()=>no,union:()=>po,unknown:()=>oo,util:()=>T,void:()=>ao});var xn=G(()=>{Mt();Sn();Qn();mt();dr();$t();});var pr=G(()=>{xn();xn();});function Uo(){try{return Lo.parse(process.env)}catch(t){if(t instanceof d.ZodError){let e=t.errors.map(n=>n.path.join(".")).join(", ");throw new Error(`Environment validation failed:
2
+ import {createRequire}from'module';import*as re from'fs';import {existsSync,readFileSync,writeFileSync,statSync}from'fs';import*as Je from'path';import {join,resolve,dirname}from'path';import {fileURLToPath}from'url';import {glob}from'glob';import*as pe from'crypto';import pe__default from'crypto';import h from'chalk';import {Command}from'commander';import _i from'ora';import ki from'cli-table3';import Si from'cli-progress';import*as ct from'os';import {homedir}from'os';import*as L from'fs/promises';import br from'prompts';import qi from'readline';import ta from'open';import {execSync}from'child_process';import Ma from'omelette';createRequire(import.meta.url);
3
+ var as=Object.defineProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var zn=(t,e)=>{for(var n in e)as(t,n,{get:e[n],enumerable:true});};function _s(){let t=vs,e=0;for(;t!==dirname(t)&&e<10;){let n=join(t,"package.json");try{if(existsSync(n)){let r=JSON.parse(readFileSync(n,"utf-8"));if(r.name==="vee_stack")return r}}catch{}t=dirname(t),e++;}return null}var ys,vs,qn,ae,gn,V,B,hn,ce,Qe,Ut,vn,_n=G(()=>{ys=fileURLToPath(import.meta.url),vs=dirname(ys),qn="6.2.4",ae={snapshot:"2.0.0",engine_target:"2.0.0",audit:"3.0",session_payload:"2.0.0",rules:"2.0.0",analysis:"2.0.0",api:"v2",min_node:20};gn=_s();gn&&(qn=gn.version,ae=gn.versions||ae);V=qn,B=V,hn=`vs_cli_v${V}`,ce=ae.snapshot,Qe=ae.engine_target,Ut=ae.audit,ae.session_payload,ae.rules,ae.analysis,vn=ae.api,ae.min_node;});var T,kn,g,le,mt=G(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let o={};for(let a of s)o[a]=a;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(let i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(let a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o;})(T||(T={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n});})(kn||(kn={}));g=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),le=t=>{switch(typeof t){case "undefined":return g.undefined;case "string":return g.string;case "number":return Number.isNaN(t)?g.nan:g.number;case "boolean":return g.boolean;case "function":return g.function;case "bigint":return g.bigint;case "symbol":return g.symbol;case "object":return Array.isArray(t)?g.array:t===null?g.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?g.promise:typeof Map<"u"&&t instanceof Map?g.map:typeof Set<"u"&&t instanceof Set?g.set:typeof Date<"u"&&t instanceof Date?g.date:g.object;default:return g.unknown}};});var u,Ts,Y,$t=G(()=>{mt();u=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ts=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Y=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r];},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r];};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e;}format(e){let n=e||function(o){return o.message},r={_errors:[]},s=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else {let i=r,l=0;for(;l<a.path.length;){let c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(n(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++;}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(e(s));}else r.push(e(s));return {formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Y.create=t=>new Y(t);});var xs,fe,En=G(()=>{$t();mt();xs=(t,e)=>{let n;switch(t.code){case u.invalid_type:t.received===g.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case u.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,T.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:n=`Unrecognized key(s) in object: ${T.joinValues(t.keys,", ")}`;break;case u.invalid_union:n="Invalid input";break;case u.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${T.joinValues(t.options)}`;break;case u.invalid_enum_value:n=`Invalid enum value. Expected ${T.joinValues(t.options)}, received '${t.received}'`;break;case u.invalid_arguments:n="Invalid function arguments";break;case u.invalid_return_type:n="Invalid function return type";break;case u.invalid_date:n="Invalid date";break;case u.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:T.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case u.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case u.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case u.custom:n="Invalid input";break;case u.invalid_intersection_types:n="Intersection results could not be merged";break;case u.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case u.not_finite:n="Number must be finite";break;default:n=e.defaultError,T.assertNever(t);}return {message:n}},fe=xs;});function As(t){Xn=t;}function et(){return Xn}var Xn,Mt=G(()=>{En();Xn=fe;});function p(t,e){let n=et(),r=ht({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===fe?void 0:fe].filter(s=>!!s)});t.common.issues.push(r);}var ht,Rs,$,y,Re,M,Ft,Vt,ke,tt,Sn=G(()=>{Mt();En();ht=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return {...s,path:o,message:s.message};let i="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)i=c(a,{data:e,defaultError:i}).message;return {...s,path:o,message:i}},Rs=[];$=class t{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return y;s.status==="dirty"&&e.dirty(),r.push(s.value);}return {status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let o=await s.key,a=await s.value;r.push({key:o,value:a});}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return y;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value);}return {status:e.value,value:r}}},y=Object.freeze({status:"aborted"}),Re=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),Ft=t=>t.status==="aborted",Vt=t=>t.status==="dirty",ke=t=>t.status==="valid",tt=t=>typeof Promise<"u"&&t instanceof Promise;});var Qn=G(()=>{});var m,er=G(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message;})(m||(m={}));});function S(t){if(!t)return {};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:s}}function sr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function zs(t){return new RegExp(`^${sr(t)}$`)}function or(t){let e=`${rr}T${sr(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ws(t,e){return !!((e==="v4"||!e)&&Us.test(t)||(e==="v6"||!e)&&Ms.test(t))}function Gs(t,e){if(!Ds.test(t))return false;try{let[n]=t.split(".");if(!n)return !1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return !(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return false}}function Ys(t,e){return !!((e==="v4"||!e)&&$s.test(t)||(e==="v6"||!e)&&Fs.test(t))}function Zs(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function nt(t){if(t instanceof Z){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ee.create(nt(r));}return new Z({...t._def,shape:()=>e})}else return t instanceof he?new he({...t._def,type:nt(t.element)}):t instanceof ee?ee.create(nt(t.unwrap())):t instanceof de?de.create(nt(t.unwrap())):t instanceof ue?ue.create(t.items.map(e=>nt(e))):t}function Tn(t,e){let n=le(t),r=le(e);if(t===e)return {valid:true,data:t};if(n===g.object&&r===g.object){let s=T.objectKeys(e),o=T.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(let i of o){let l=Tn(t[i],e[i]);if(!l.valid)return {valid:false};a[i]=l.data;}return {valid:true,data:a}}else if(n===g.array&&r===g.array){if(t.length!==e.length)return {valid:false};let s=[];for(let o=0;o<t.length;o++){let a=t[o],i=e[o],l=Tn(a,i);if(!l.valid)return {valid:false};s.push(l.data);}return {valid:true,data:s}}else return n===g.date&&r===g.date&&+t==+e?{valid:true,data:t}:{valid:false}}function ir(t,e){return new $e({values:t,typeName:v.ZodEnum,...S(e)})}function nr(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function ar(t,e={},n){return t?Se.create().superRefine((r,s)=>{let o=t(r);if(o instanceof Promise)return o.then(a=>{if(!a){let i=nr(e,r),l=i.fatal??n??true;s.addIssue({code:"custom",...i,fatal:l});}});if(!o){let a=nr(e,r),i=a.fatal??n??true;s.addIssue({code:"custom",...a,fatal:i});}}):Se.create()}var te,tr,w,bs,Cs,Is,Ns,Os,Ds,Ps,js,Ls,wn,Us,$s,Ms,Fs,Vs,Bs,rr,Hs,Ee,be,Ce,Ie,Ne,rt,Oe,De,Se,me,se,st,he,Z,Pe,ge,Bt,je,ue,Ht,ot,it,zt,Le,Ue,$e,Me,we,ne,ee,de,Fe,Ve,at,Js,yt,vt,Be,Ks,v,qs,cr,lr,Xs,Qs,ur,eo,to,no,ro,so,oo,io,ao,co,lo,uo,po,fo,go,mo,ho,yo,vo,_o,ko,Eo,So,wo,To,xo,Ao,Ro,bo,Co,Io,No,Oo,Do,Po,dr=G(()=>{$t();Mt();er();Sn();mt();te=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s;}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},tr=(t,e)=>{if(ke(e))return {success:true,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let n=new Y(t.common.issues);return this._error=n,this._error}}};w=class{get description(){return this._def.description}_getType(e){return le(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new $,ctx:{common:e.parent.common,data:e.data,parsedType:le(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(tt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??false,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:le(e)},s=this._parseSync({data:e,path:r.path,parent:r});return tr(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:le(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ke(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),n.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:n}).then(r=>ke(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:true},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:le(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(tt(s)?s:Promise.resolve(s));return tr(r,o)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let a=e(s),i=()=>o.addIssue({code:u.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?true:(i(),false)):a?true:(i(),false)})}refinement(e,n){return this._refinement((r,s)=>e(r)?true:(s.addIssue(typeof n=="function"?n(r,s):n),false))}_refinement(e){return new ne({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)};}optional(){return ee.create(this,this._def)}nullable(){return de.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return he.create(this)}promise(){return we.create(this,this._def)}or(e){return Pe.create([this,e],this._def)}and(e){return je.create(this,e,this._def)}transform(e){return new ne({...S(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Fe({...S(this._def),innerType:this,defaultValue:n,typeName:v.ZodDefault})}brand(){return new yt({typeName:v.ZodBranded,type:this,...S(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ve({...S(this._def),innerType:this,catchValue:n,typeName:v.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return vt.create(this,e)}readonly(){return Be.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bs=/^c[^\s-]{8,}$/i,Cs=/^[0-9a-z]+$/,Is=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ns=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Os=/^[a-z0-9_-]{21}$/i,Ds=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ps=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,js=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ls="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Us=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$s=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ms=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Fs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Bs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Hs=new RegExp(`^${rr}$`);Ee=class t extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==g.string){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_type,expected:g.string,received:o.parsedType}),y}let r=new $,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,minimum:o.value,type:"string",inclusive:true,exact:false,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,maximum:o.value,type:"string",inclusive:true,exact:false,message:o.message}),r.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?p(s,{code:u.too_big,maximum:o.value,type:"string",inclusive:true,exact:true,message:o.message}):i&&p(s,{code:u.too_small,minimum:o.value,type:"string",inclusive:true,exact:true,message:o.message}),r.dirty());}else if(o.kind==="email")js.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")wn||(wn=new RegExp(Ls,"u")),wn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Ns.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Os.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")bs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Cs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Is.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data);}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:u.invalid_string,message:o.message}),r.dirty();}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:u.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?or(o).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Hs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?zs(o).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Ps.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ws(e.data,o.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Gs(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Ys(e.data,o.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Vs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Bs.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:u.invalid_string,message:o.message}),r.dirty()):T.assertNever(o);return {status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:u.invalid_string,...m.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...m.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...m.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...m.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...m.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...m.errToObj(n)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return !!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return !!this._def.checks.find(e=>e.kind==="date")}get isTime(){return !!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return !!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return !!this._def.checks.find(e=>e.kind==="email")}get isURL(){return !!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return !!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return !!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return !!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return !!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return !!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return !!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return !!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return !!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return !!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return !!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ee.create=t=>new Ee({checks:[],typeName:v.ZodString,coerce:t?.coerce??false,...S(t)});be=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf;}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==g.number){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_type,expected:g.number,received:o.parsedType}),y}let r,s=new $;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:u.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),s.dirty()):o.kind==="multipleOf"?Zs(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:u.not_finite,message:o.message}),s.dirty()):T.assertNever(o);return {status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,true,m.toString(n))}gt(e,n){return this.setLimit("min",e,false,m.toString(n))}lte(e,n){return this.setLimit("max",e,true,m.toString(n))}lt(e,n){return this.setLimit("max",e,false,m.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:m.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:m.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return !!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return true;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);}return Number.isFinite(n)&&Number.isFinite(e)}};be.create=t=>new be({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||false,...S(t)});Ce=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data);}catch{return this._getInvalidInput(e)}if(this._getType(e)!==g.bigint)return this._getInvalidInput(e);let r,s=new $;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),p(r,{code:u.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):T.assertNever(o);return {status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:g.bigint,received:n.parsedType}),y}gte(e,n){return this.setLimit("min",e,true,m.toString(n))}gt(e,n){return this.setLimit("min",e,false,m.toString(n))}lte(e,n){return this.setLimit("max",e,true,m.toString(n))}lt(e,n){return this.setLimit("max",e,false,m.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:m.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:m.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ce.create=t=>new Ce({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??false,...S(t)});Ie=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.boolean,received:r.parsedType}),y}return M(e.data)}};Ie.create=t=>new Ie({typeName:v.ZodBoolean,coerce:t?.coerce||false,...S(t)});Ne=class t extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==g.date){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_type,expected:g.date,received:o.parsedType}),y}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return p(o,{code:u.invalid_date}),y}let r=new $,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,message:o.message,inclusive:true,exact:false,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,message:o.message,inclusive:true,exact:false,maximum:o.value,type:"date"}),r.dirty()):T.assertNever(o);return {status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Ne.create=t=>new Ne({checks:[],coerce:t?.coerce||false,typeName:v.ZodDate,...S(t)});rt=class extends w{_parse(e){if(this._getType(e)!==g.symbol){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.symbol,received:r.parsedType}),y}return M(e.data)}};rt.create=t=>new rt({typeName:v.ZodSymbol,...S(t)});Oe=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.undefined,received:r.parsedType}),y}return M(e.data)}};Oe.create=t=>new Oe({typeName:v.ZodUndefined,...S(t)});De=class extends w{_parse(e){if(this._getType(e)!==g.null){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.null,received:r.parsedType}),y}return M(e.data)}};De.create=t=>new De({typeName:v.ZodNull,...S(t)});Se=class extends w{constructor(){super(...arguments),this._any=true;}_parse(e){return M(e.data)}};Se.create=t=>new Se({typeName:v.ZodAny,...S(t)});me=class extends w{constructor(){super(...arguments),this._unknown=true;}_parse(e){return M(e.data)}};me.create=t=>new me({typeName:v.ZodUnknown,...S(t)});se=class extends w{_parse(e){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:g.never,received:n.parsedType}),y}};se.create=t=>new se({typeName:v.ZodNever,...S(t)});st=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.void,received:r.parsedType}),y}return M(e.data)}};st.create=t=>new st({typeName:v.ZodVoid,...S(t)});he=class t extends w{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==g.array)return p(n,{code:u.invalid_type,expected:g.array,received:n.parsedType}),y;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,i=n.data.length<s.exactLength.value;(a||i)&&(p(n,{code:a?u.too_big:u.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:s.exactLength.message}),r.dirty());}if(s.minLength!==null&&n.data.length<s.minLength.value&&(p(n,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:true,exact:false,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(p(n,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:true,exact:false,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,i)=>s.type._parseAsync(new te(n,a,n.path,i)))).then(a=>$.mergeArray(r,a));let o=[...n.data].map((a,i)=>s.type._parseSync(new te(n,a,n.path,i)));return $.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:m.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:m.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:m.toString(n)}})}nonempty(e){return this.min(1,e)}};he.create=(t,e)=>new he({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...S(e)});Z=class t extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend;}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=T.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==g.object){let c=this._getOrReturnCtx(e);return p(c,{code:u.invalid_type,expected:g.object,received:c.parsedType}),y}let{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof se&&this._def.unknownKeys==="strip"))for(let c in s.data)a.includes(c)||i.push(c);let l=[];for(let c of a){let f=o[c],_=s.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new te(s,_,s.path,c)),alwaysSet:c in s.data});}if(this._def.catchall instanceof se){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of i)l.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")i.length>0&&(p(s,{code:u.unrecognized_keys,keys:i}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let c=this._def.catchall;for(let f of i){let _=s.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new te(s,_,s.path,f)),alwaysSet:f in s.data});}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let _=await f.key,b=await f.value;c.push({key:_,value:b,alwaysSet:f.alwaysSet});}return c}).then(c=>$.mergeObjectSync(r,c)):$.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:m.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of T.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of T.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return nt(this)}partial(e){let n={};for(let r of T.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional();}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of T.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else {let o=this.shape[r];for(;o instanceof ee;)o=o._def.innerType;n[r]=o;}return new t({...this._def,shape:()=>n})}keyof(){return ir(T.objectKeys(this.shape))}};Z.create=(t,e)=>new Z({shape:()=>t,unknownKeys:"strip",catchall:se.create(),typeName:v.ZodObject,...S(e)});Z.strictCreate=(t,e)=>new Z({shape:()=>t,unknownKeys:"strict",catchall:se.create(),typeName:v.ZodObject,...S(e)});Z.lazycreate=(t,e)=>new Z({shape:t,unknownKeys:"strip",catchall:se.create(),typeName:v.ZodObject,...S(e)});Pe=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(o){for(let i of o)if(i.result.status==="valid")return i.result;for(let i of o)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(i=>new Y(i.ctx.common.issues));return p(n,{code:u.invalid_union,unionErrors:a}),y}if(n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return {result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o,a=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:c}),c.common.issues.length&&a.push(c.common.issues);}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(l=>new Y(l));return p(n,{code:u.invalid_union,unionErrors:i}),y}}get options(){return this._def.options}};Pe.create=(t,e)=>new Pe({options:t,typeName:v.ZodUnion,...S(e)});ge=t=>t instanceof Le?ge(t.schema):t instanceof ne?ge(t.innerType()):t instanceof Ue?[t.value]:t instanceof $e?t.options:t instanceof Me?T.objectValues(t.enum):t instanceof Fe?ge(t._def.innerType):t instanceof Oe?[void 0]:t instanceof De?[null]:t instanceof ee?[void 0,...ge(t.unwrap())]:t instanceof de?[null,...ge(t.unwrap())]:t instanceof yt||t instanceof Be?ge(t.unwrap()):t instanceof Ve?ge(t._def.innerType):[],Bt=class t extends w{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.object)return p(n,{code:u.invalid_type,expected:g.object,received:n.parsedType}),y;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(p(n,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let o of n){let a=ge(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o);}}return new t({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...S(r)})}};je=class extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(o,a)=>{if(Ft(o)||Ft(a))return y;let i=Tn(o.value,a.value);return i.valid?((Vt(o)||Vt(a))&&n.dirty(),{status:n.value,value:i.data}):(p(r,{code:u.invalid_intersection_types}),y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};je.create=(t,e,n)=>new je({left:t,right:e,typeName:v.ZodIntersection,...S(n)});ue=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.array)return p(r,{code:u.invalid_type,expected:g.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return p(r,{code:u.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:u.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),n.dirty());let o=[...r.data].map((a,i)=>{let l=this._def.items[i]||this._def.rest;return l?l._parse(new te(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>$.mergeArray(n,a)):$.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ue.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ue({items:t,typeName:v.ZodTuple,rest:null,...S(e)})};Ht=class t extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.object)return p(r,{code:u.invalid_type,expected:g.object,received:r.parsedType}),y;let s=[],o=this._def.keyType,a=this._def.valueType;for(let i in r.data)s.push({key:o._parse(new te(r,i,r.path,i)),value:a._parse(new te(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?$.mergeObjectAsync(n,s):$.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof w?new t({keyType:e,valueType:n,typeName:v.ZodRecord,...S(r)}):new t({keyType:Ee.create(),valueType:e,typeName:v.ZodRecord,...S(n)})}},ot=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.map)return p(r,{code:u.invalid_type,expected:g.map,received:r.parsedType}),y;let s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([i,l],c)=>({key:s._parse(new te(r,i,r.path,[c,"key"])),value:o._parse(new te(r,l,r.path,[c,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let l of a){let c=await l.key,f=await l.value;if(c.status==="aborted"||f.status==="aborted")return y;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),i.set(c.value,f.value);}return {status:n.value,value:i}})}else {let i=new Map;for(let l of a){let c=l.key,f=l.value;if(c.status==="aborted"||f.status==="aborted")return y;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),i.set(c.value,f.value);}return {status:n.value,value:i}}}};ot.create=(t,e,n)=>new ot({valueType:e,keyType:t,typeName:v.ZodMap,...S(n)});it=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.set)return p(r,{code:u.invalid_type,expected:g.set,received:r.parsedType}),y;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(p(r,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:true,exact:false,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(p(r,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:true,exact:false,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function a(l){let c=new Set;for(let f of l){if(f.status==="aborted")return y;f.status==="dirty"&&n.dirty(),c.add(f.value);}return {status:n.value,value:c}}let i=[...r.data.values()].map((l,c)=>o._parse(new te(r,l,r.path,c)));return r.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(e,n){return new t({...this._def,minSize:{value:e,message:m.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:m.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};it.create=(t,e)=>new it({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...S(e)});zt=class t extends w{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.function)return p(n,{code:u.invalid_type,expected:g.function,received:n.parsedType}),y;function r(i,l){return ht({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,et(),fe].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(i,l){return ht({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,et(),fe].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof we){let i=this;return M(async function(...l){let c=new Y([]),f=await i._def.args.parseAsync(l,o).catch(x=>{throw c.addIssue(r(l,x)),c}),_=await Reflect.apply(a,this,f);return await i._def.returns._def.type.parseAsync(_,o).catch(x=>{throw c.addIssue(s(_,x)),c})})}else {let i=this;return M(function(...l){let c=i._def.args.safeParse(l,o);if(!c.success)throw new Y([r(l,c.error)]);let f=Reflect.apply(a,this,c.data),_=i._def.returns.safeParse(f,o);if(!_.success)throw new Y([s(f,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ue.create(e).rest(me.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||ue.create([]).rest(me.create()),returns:n||me.create(),typeName:v.ZodFunction,...S(r)})}},Le=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Le.create=(t,e)=>new Le({getter:t,typeName:v.ZodLazy,...S(e)});Ue=class extends w{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return p(n,{received:n.data,code:u.invalid_literal,expected:this._def.value}),y}return {status:"valid",value:e.data}}get value(){return this._def.value}};Ue.create=(t,e)=>new Ue({value:t,typeName:v.ZodLiteral,...S(e)});$e=class t extends w{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return p(n,{expected:T.joinValues(r),received:n.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return p(n,{received:n.data,code:u.invalid_enum_value,options:r}),y}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};$e.create=ir;Me=class extends w{_parse(e){let n=T.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==g.string&&r.parsedType!==g.number){let s=T.objectValues(n);return p(r,{expected:T.joinValues(s),received:r.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(T.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=T.objectValues(n);return p(r,{received:r.data,code:u.invalid_enum_value,options:s}),y}return M(e.data)}get enum(){return this._def.values}};Me.create=(t,e)=>new Me({values:t,typeName:v.ZodNativeEnum,...S(e)});we=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.promise&&n.common.async===false)return p(n,{code:u.invalid_type,expected:g.promise,received:n.parsedType}),y;let r=n.parsedType===g.promise?n.data:Promise.resolve(n.data);return M(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};we.create=(t,e)=>new we({type:t,typeName:v.ZodPromise,...S(e)});ne=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{p(r,a),a.fatal?n.abort():n.dirty();},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async i=>{if(n.value==="aborted")return y;let l=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return l.status==="aborted"?y:l.status==="dirty"?Re(l.value):n.value==="dirty"?Re(l.value):l});{if(n.value==="aborted")return y;let i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?y:i.status==="dirty"?Re(i.value):n.value==="dirty"?Re(i.value):i}}if(s.type==="refinement"){let a=i=>{let l=s.refinement(i,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===false){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?y:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?y:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.value}))))}if(s.type==="transform")if(r.common.async===false){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ke(a))return y;let i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ke(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:n.value,value:i})):y);T.assertNever(s);}};ne.create=(t,e,n)=>new ne({schema:t,typeName:v.ZodEffects,effect:e,...S(n)});ne.createWithPreprocess=(t,e,n)=>new ne({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...S(n)});ee=class extends w{_parse(e){return this._getType(e)===g.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ee.create=(t,e)=>new ee({innerType:t,typeName:v.ZodOptional,...S(e)});de=class extends w{_parse(e){return this._getType(e)===g.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};de.create=(t,e)=>new de({innerType:t,typeName:v.ZodNullable,...S(e)});Fe=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===g.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Fe.create=(t,e)=>new Fe({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});Ve=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return tt(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Y(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Y(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ve.create=(t,e)=>new Ve({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});at=class extends w{_parse(e){if(this._getType(e)!==g.nan){let r=this._getOrReturnCtx(e);return p(r,{code:u.invalid_type,expected:g.nan,received:r.parsedType}),y}return {status:"valid",value:e.data}}};at.create=t=>new at({typeName:v.ZodNaN,...S(t)});Js=Symbol("zod_brand"),yt=class extends w{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},vt=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return (async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?y:o.status==="dirty"?(n.dirty(),Re(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?y:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:v.ZodPipeline})}},Be=class extends w{_parse(e){let n=this._def.innerType._parse(e),r=s=>(ke(s)&&(s.value=Object.freeze(s.value)),s);return tt(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:v.ZodReadonly,...S(e)});Ks={object:Z.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly";})(v||(v={}));qs=(t,e={message:`Input not instance of ${t.name}`})=>ar(n=>n instanceof t,e),cr=Ee.create,lr=be.create,Xs=at.create,Qs=Ce.create,ur=Ie.create,eo=Ne.create,to=rt.create,no=Oe.create,ro=De.create,so=Se.create,oo=me.create,io=se.create,ao=st.create,co=he.create,lo=Z.create,uo=Z.strictCreate,po=Pe.create,fo=Bt.create,go=je.create,mo=ue.create,ho=Ht.create,yo=ot.create,vo=it.create,_o=zt.create,ko=Le.create,Eo=Ue.create,So=$e.create,wo=Me.create,To=we.create,xo=ne.create,Ao=ee.create,Ro=de.create,bo=ne.createWithPreprocess,Co=vt.create,Io=()=>cr().optional(),No=()=>lr().optional(),Oo=()=>ur().optional(),Do={string:(t=>Ee.create({...t,coerce:true})),number:(t=>be.create({...t,coerce:true})),boolean:(t=>Ie.create({...t,coerce:true})),bigint:(t=>Ce.create({...t,coerce:true})),date:(t=>Ne.create({...t,coerce:true}))},Po=y;});var d={};zn(d,{BRAND:()=>Js,DIRTY:()=>Re,EMPTY_PATH:()=>Rs,INVALID:()=>y,NEVER:()=>Po,OK:()=>M,ParseStatus:()=>$,Schema:()=>w,ZodAny:()=>Se,ZodArray:()=>he,ZodBigInt:()=>Ce,ZodBoolean:()=>Ie,ZodBranded:()=>yt,ZodCatch:()=>Ve,ZodDate:()=>Ne,ZodDefault:()=>Fe,ZodDiscriminatedUnion:()=>Bt,ZodEffects:()=>ne,ZodEnum:()=>$e,ZodError:()=>Y,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>zt,ZodIntersection:()=>je,ZodIssueCode:()=>u,ZodLazy:()=>Le,ZodLiteral:()=>Ue,ZodMap:()=>ot,ZodNaN:()=>at,ZodNativeEnum:()=>Me,ZodNever:()=>se,ZodNull:()=>De,ZodNullable:()=>de,ZodNumber:()=>be,ZodObject:()=>Z,ZodOptional:()=>ee,ZodParsedType:()=>g,ZodPipeline:()=>vt,ZodPromise:()=>we,ZodReadonly:()=>Be,ZodRecord:()=>Ht,ZodSchema:()=>w,ZodSet:()=>it,ZodString:()=>Ee,ZodSymbol:()=>rt,ZodTransformer:()=>ne,ZodTuple:()=>ue,ZodType:()=>w,ZodUndefined:()=>Oe,ZodUnion:()=>Pe,ZodUnknown:()=>me,ZodVoid:()=>st,addIssueToContext:()=>p,any:()=>so,array:()=>co,bigint:()=>Qs,boolean:()=>ur,coerce:()=>Do,custom:()=>ar,date:()=>eo,datetimeRegex:()=>or,defaultErrorMap:()=>fe,discriminatedUnion:()=>fo,effect:()=>xo,enum:()=>So,function:()=>_o,getErrorMap:()=>et,getParsedType:()=>le,instanceof:()=>qs,intersection:()=>go,isAborted:()=>Ft,isAsync:()=>tt,isDirty:()=>Vt,isValid:()=>ke,late:()=>Ks,lazy:()=>ko,literal:()=>Eo,makeIssue:()=>ht,map:()=>yo,nan:()=>Xs,nativeEnum:()=>wo,never:()=>io,null:()=>ro,nullable:()=>Ro,number:()=>lr,object:()=>lo,objectUtil:()=>kn,oboolean:()=>Oo,onumber:()=>No,optional:()=>Ao,ostring:()=>Io,pipeline:()=>Co,preprocess:()=>bo,promise:()=>To,quotelessJson:()=>Ts,record:()=>ho,set:()=>vo,setErrorMap:()=>As,strictObject:()=>uo,string:()=>cr,symbol:()=>to,transformer:()=>xo,tuple:()=>mo,undefined:()=>no,union:()=>po,unknown:()=>oo,util:()=>T,void:()=>ao});var xn=G(()=>{Mt();Sn();Qn();mt();dr();$t();});var pr=G(()=>{xn();xn();});function Uo(){try{return Lo.parse(process.env)}catch(t){if(t instanceof d.ZodError){let e=t.errors.map(n=>n.path.join(".")).join(", ");throw new Error(`Environment validation failed:
4
4
  Missing or invalid variables: ${e}
5
- Please check your .env file and ensure all required variables are set.`)}throw t}}function $o(){return An||(An=Uo()),An}function Mo(t=jo.api.rateLimit){let{windowMs:e,maxRequests:n,message:r}=t;return {check(s){let o=Date.now(),a=He.get(s);a&&o>a.resetTime&&He.delete(s);let i=He.get(s)||{count:0,resetTime:o+e};return i.count>=n?{success:false,remaining:0,resetTime:i.resetTime,error:r||"Too many requests"}:(i.count++,He.set(s,i),{success:true,remaining:n-i.count,resetTime:i.resetTime})},reset(s){He.delete(s);},cleanup(){let s=Date.now();for(let[o,a]of He.entries())s>a.resetTime&&He.delete(o);}}}var jo,Lo,An,k,fr,Wt,E,He,K=G(()=>{_n();_n();pr();jo={versions:{cli:V,engine:V,frontend:V,api:vn,snapshot:ae,engine_target:Qe},analysis:{maxFileSize:2*1024*1024,maxFileCount:2e3,maxDependencyCount:2e3,maxDirectoryDepth:10,timeout:5e3},scoring:{baseScore:100,CRITICAL:25,HIGH:15,MEDIUM:8,LOW:3,severityBands:{HEALTHY:{min:90,max:100},STABLE:{min:75,max:89},STRUCTURAL_CONCERN:{min:60,max:74},HIGH_RISK:{min:0,max:59}}},api:{rateLimit:{windowMs:900*1e3,maxRequests:100},timeout:1e4},snapshot:{schemaVersion:ae,engineTargetVersion:Qe},usage:{free:{scansPerMonth:3,retentionDays:7},pro:{scansPerMonth:100,retentionDays:90}},security:{bcryptRounds:10,jwtExpiration:"7d",maxLoginAttempts:5,lockoutDuration:900*1e3},storage:{bucketName:"snapshots",maxRetries:3,chunkSize:1024*1024},ui:{maxFindingsPerPage:50,maxReportHistory:100}},d.object({snapshot_version:d.string(),engine_target_version:d.string(),project_id:d.string(),generated_at:d.string(),root_path_hash:d.string(),metadata:d.object({total_files:d.number().int().nonnegative(),total_dependencies:d.number().int().nonnegative(),total_size_bytes:d.number().int().nonnegative(),total_lines:d.number().int().nonnegative(),max_directory_depth:d.number().int().nonnegative(),language_breakdown:d.record(d.string(),d.number().int().nonnegative())}),files:d.array(d.object({id:d.string(),path_hash:d.string(),depth:d.number().int().nonnegative(),size_bytes:d.number().int().nonnegative(),estimated_lines:d.number().int().nonnegative(),extension:d.string(),is_binary:d.boolean(),import_count:d.number().int().nonnegative().optional(),function_count:d.number().int().nonnegative().optional(),class_count:d.number().int().nonnegative().optional()})),dependencies:d.array(d.object({id:d.string(),name_hash:d.string(),major_version:d.number().int().nonnegative(),minor_version:d.number().int().nonnegative(),category:d.enum(["dev","prod","peer"])}))}),d.object({name:d.string().min(1).max(100)}),d.object({analysis_version:d.string(),snapshot_schema_version:d.string(),total_score:d.number().min(0).max(100),severity_band:d.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),engines:d.array(d.object({engine_name:d.string(),score_impact:d.number(),risk_level:d.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),metrics:d.record(d.number()),findings:d.array(d.object({rule_id:d.string(),title:d.string(),message:d.string(),severity:d.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:d.enum(["SECURITY","STRUCTURE","COMPLEXITY","DEPENDENCY","REPOSITORY_HYGIENE","DOCUMENTATION","QUALITY"]),evidence:d.array(d.string()).optional(),explanation:d.string().optional(),impact:d.string().optional(),effort:d.enum(["Low","Medium","High"]).optional(),recommendations:d.array(d.string()).optional()}))})),summary:d.object({total_findings:d.number().int().nonnegative(),critical_count:d.number().int().nonnegative(),high_count:d.number().int().nonnegative(),medium_count:d.number().int().nonnegative(),low_count:d.number().int().nonnegative(),categories:d.record(d.string(),d.number().int().nonnegative())}),generated_at:d.string()}),Lo=d.object({NEXT_PUBLIC_SUPABASE_URL:d.string().url("Invalid SUPABASE_URL"),NEXT_PUBLIC_SUPABASE_ANON_KEY:d.string().min(1,"SUPABASE_ANON_KEY is required"),SUPABASE_SERVICE_ROLE_KEY:d.string().min(1,"SERVICE_ROLE_KEY is required"),NODE_ENV:d.enum(["development","production","test"],{errorMap:()=>({message:"NODE_ENV must be development, production, or test"})}),JWT_SECRET:d.string().min(32,"JWT_SECRET must be at least 32 characters").optional()});An=null;new Proxy({},{get(t,e){return $o()[e]}}),k={plans:{FREE:{name:"free",scansPerMonth:10,projects:3,snapshots:10,reports:10,maxFileSizeMB:5,maxFilesPerSnapshot:100,storageMB:100,teamMembers:1,support:"community",features:["basic-analysis","security-scan"]},PRO:{name:"pro",scansPerMonth:-1,projects:-1,snapshots:-1,reports:-1,maxFileSizeMB:50,maxFilesPerSnapshot:1e3,storageMB:1e4,teamMembers:10,support:"priority",features:["basic-analysis","security-scan","advanced-analytics","api-access","team-collaboration","priority-support"]}},roles:{MEMBER:"member",SUPPORT:"support",ADMIN:"admin",OWNER:"owner"},permissions:{PROJECT_READ:"project:read",PROJECT_CREATE:"project:create",PROJECT_UPDATE:"project:update",PROJECT_DELETE:"project:delete",SNAPSHOT_READ:"snapshot:read",SNAPSHOT_CREATE:"snapshot:create",SNAPSHOT_DELETE:"snapshot:delete",REPORT_READ:"report:read",REPORT_DOWNLOAD:"report:download",TEAM_READ:"team:read",TEAM_INVITE:"team:invite",TEAM_REMOVE:"team:remove",USER_READ:"user:read",USER_UPDATE:"user:update",USER_DELETE:"user:delete",SYSTEM_MANAGE:"system:manage",ALL:"*",READ_OWN:"read:own",CREATE_OWN:"create:own",UPDATE_OWN:"update:own",DELETE_OWN:"delete:own",READ_ALL:"read:all",CREATE_ALL:"create:all",UPDATE_ALL:"update:all",DELETE_ALL:"delete:all",SCAN_OWN:"scan:own",REPORT_OWN:"report:own",ANALYTICS_VIEW:"analytics:view",SUPPORT_ACCESS:"support:access",SUPPORT_VIEW_TICKETS:"support:view-tickets"},features:{BASIC_ANALYSIS:"basic-analysis",SECURITY_SCAN:"security-scan",ADVANCED_ANALYTICS:"advanced-analytics",API_ACCESS:"api-access",TEAM_COLLAB:"team-collaboration",PRIORITY_SUPPORT:"priority-support"}},fr={FREE:k.plans.FREE.name,PRO:k.plans.PRO.name},{BASIC_ANALYSIS:k.features.BASIC_ANALYSIS,SECURITY_SCAN:k.features.SECURITY_SCAN,ADVANCED_ANALYTICS:k.features.ADVANCED_ANALYTICS,API_ACCESS:k.features.API_ACCESS,TEAM_COLLAB:k.features.TEAM_COLLAB,PRIORITY_SUPPORT:k.features.PRIORITY_SUPPORT},{[fr.FREE]:k.plans.FREE,[fr.PRO]:k.plans.PRO},Wt={MEMBER:k.roles.MEMBER,SUPPORT:k.roles.SUPPORT,ADMIN:k.roles.ADMIN,OWNER:k.roles.OWNER},E={PROJECT_READ:k.permissions.PROJECT_READ,PROJECT_CREATE:k.permissions.PROJECT_CREATE,PROJECT_UPDATE:k.permissions.PROJECT_UPDATE,PROJECT_DELETE:k.permissions.PROJECT_DELETE,SNAPSHOT_READ:k.permissions.SNAPSHOT_READ,SNAPSHOT_CREATE:k.permissions.SNAPSHOT_CREATE,SNAPSHOT_DELETE:k.permissions.SNAPSHOT_DELETE,REPORT_READ:k.permissions.REPORT_READ,REPORT_DOWNLOAD:k.permissions.REPORT_DOWNLOAD,TEAM_READ:k.permissions.TEAM_READ,TEAM_INVITE:k.permissions.TEAM_INVITE,TEAM_REMOVE:k.permissions.TEAM_REMOVE,USER_READ:k.permissions.USER_READ,USER_UPDATE:k.permissions.USER_UPDATE,USER_DELETE:k.permissions.USER_DELETE,SYSTEM_MANAGE:k.permissions.SYSTEM_MANAGE,ALL:k.permissions.ALL,READ_OWN:k.permissions.READ_OWN,CREATE_OWN:k.permissions.CREATE_OWN,UPDATE_OWN:k.permissions.UPDATE_OWN,DELETE_OWN:k.permissions.DELETE_OWN,READ_ALL:k.permissions.READ_ALL,CREATE_ALL:k.permissions.CREATE_ALL,UPDATE_ALL:k.permissions.UPDATE_ALL,DELETE_ALL:k.permissions.DELETE_ALL,SCAN_OWN:k.permissions.SCAN_OWN,REPORT_OWN:k.permissions.REPORT_OWN,ANALYTICS_VIEW:k.permissions.ANALYTICS_VIEW,SUPPORT_ACCESS:k.permissions.SUPPORT_ACCESS,SUPPORT_VIEW_TICKETS:k.permissions.SUPPORT_VIEW_TICKETS},{[Wt.MEMBER]:[E.READ_OWN,E.CREATE_OWN,E.UPDATE_OWN,E.DELETE_OWN,E.SCAN_OWN,E.REPORT_OWN,E.PROJECT_READ,E.PROJECT_CREATE,E.PROJECT_UPDATE,E.PROJECT_DELETE,E.SNAPSHOT_READ,E.SNAPSHOT_CREATE,E.SNAPSHOT_DELETE,E.REPORT_READ,E.REPORT_DOWNLOAD],[Wt.SUPPORT]:[E.READ_ALL,E.PROJECT_READ,E.SNAPSHOT_READ,E.REPORT_READ,E.USER_READ,E.SUPPORT_ACCESS,E.SUPPORT_VIEW_TICKETS],[Wt.ADMIN]:[E.READ_ALL,E.CREATE_ALL,E.UPDATE_ALL,E.DELETE_ALL,E.USER_READ,E.USER_UPDATE,E.USER_DELETE,E.SYSTEM_MANAGE,E.REPORT_READ,E.ANALYTICS_VIEW],[Wt.OWNER]:[E.ALL]},{projects:{read:E.PROJECT_READ,create:E.PROJECT_CREATE,update:E.PROJECT_UPDATE,delete:E.PROJECT_DELETE},snapshots:{read:E.SNAPSHOT_READ,create:E.SNAPSHOT_CREATE,delete:E.SNAPSHOT_DELETE},reports:{read:E.REPORT_READ},users:{read:E.USER_READ,update:E.USER_UPDATE}},He=new Map;Mo();});var on,an,Pr=G(()=>{on={BASE_SCORE:100,MIN_SCORE:0,MAX_SCORE:100},an={HEALTHY:{min:90,max:100},STABLE:{min:75,max:89},STRUCTURAL_CONCERN:{min:60,max:74},HIGH_RISK:{min:0,max:59}};});var Pn={};zn(Pn,{CoreEngine:()=>Ii,ProjectScanner:()=>Vr,RULES:()=>Gi,ReportGenerator:()=>Fr,RuleRegistry:()=>$r,ScoringEngine:()=>Mr,SnapshotValidator:()=>Ur,scanProject:()=>Ji});async function Ji(t,e,n){return new Vr({projectPath:t,...n}).scan(e)}var jr,Ur,$r,Mr,Fr,Ii,Ni,Oi,Di,Pi,ji,Li,Ui,$i,Mi,Fi,Vi,Bi,Hi,zi,Wi,Gi,Vr,jn=G(()=>{Pr();K();K();jr=(t=>typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>e[n]}):t)(function(t){throw Error('Dynamic require of "'+t+'" is not supported')}),Ur=class{validate(t){let e=[];return t.snapshot_version||e.push("Missing snapshot_version"),t.engine_target_version||e.push("Missing engine_target_version"),(!t.files||!Array.isArray(t.files))&&e.push("Invalid or missing files array"),(!t.dependencies||!Array.isArray(t.dependencies))&&e.push("Invalid or missing dependencies array"),t.files&&t.files.length>2e3&&e.push("File count exceeds maximum limit of 2000"),{valid:e.length===0,error:e.length>0?e.join(", "):void 0}}},$r=class{rules=[];register(t){this.rules.push(t);}executeAllRules(t){let e=[],n=[...this.rules].sort((r,s)=>r.id.localeCompare(s.id));for(let r of n)try{let s=r.evaluator(t);s&&e.push({rule_id:r.id,severity:s.severity,weight:r.weight,title:s.title,message:s.message,category:s.category,evidence:s.evidence,explanation:s.explanation,impact:s.impact,effort:s.effort,recommendations:s.recommendations});}catch{}return e}},Mr=class{calculateScore(t){let e=on.BASE_SCORE;for(let n of t)e-=n.weight;return Math.max(on.MIN_SCORE,Math.min(on.MAX_SCORE,e))}getSeverityBand(t){return t>=an.HEALTHY.min?"HEALTHY":t>=an.STABLE.min?"STABLE":t>=an.STRUCTURAL_CONCERN.min?"STRUCTURAL_CONCERN":"HIGH_RISK"}},Fr=class{generateReport(t,e,n,r){let s=e.map(i=>({rule_id:i.rule_id,title:i.title,message:i.message,severity:i.severity,category:i.category,evidence:i.evidence,explanation:i.explanation,impact:i.impact,effort:i.effort,recommendations:i.recommendations})),o=this.generateSummary(e),a={engine_name:"VeeStack Core Engine",score_impact:100-n,risk_level:r,metrics:{total_files:t.metadata.total_files,total_dependencies:t.metadata.total_dependencies,total_size_bytes:t.metadata.total_size_bytes,max_directory_depth:t.metadata.max_directory_depth},findings:s};return {analysis_version:ae,snapshot_schema_version:t.snapshot_version,total_score:n,severity_band:r,engines:[a],summary:o,generated_at:new Date().toISOString()}}generateSummary(t){let e={};for(let n of t){let r=this.getCategoryFromRuleId(n.rule_id);e[r]=(e[r]||0)+1;}return {total_findings:t.length,critical_count:t.filter(n=>n.severity==="CRITICAL").length,high_count:t.filter(n=>n.severity==="HIGH").length,medium_count:t.filter(n=>n.severity==="MEDIUM").length,low_count:t.filter(n=>n.severity==="LOW").length,categories:e}}getCategoryFromRuleId(t){let e=t.split("_")[0];return {SEC:"SECURITY",STR:"STRUCTURE",COM:"COMPLEXITY",DEP:"DEPENDENCY",HYG:"REPOSITORY_HYGIENE",DOC:"DOCUMENTATION",QUA:"QUALITY"}[e]||"OTHER"}},Ii=class{validator;ruleRegistry;scoringEngine;reportGenerator;constructor(){this.validator=new Ur,this.ruleRegistry=new $r,this.scoringEngine=new Mr,this.reportGenerator=new Fr;}registerRule(t){this.ruleRegistry.register(t);}async analyze(t){let e=this.validator.validate(t);if(!e.valid)return {success:false,error:{error:e.error,code:400}};let n=this.ruleRegistry.executeAllRules(t),r=this.scoringEngine.calculateScore(n),s=this.scoringEngine.getSeverityBand(r);return {success:true,report:this.reportGenerator.generateReport(t,n,r,s)}}},Ni={id:"RULE_001",name:"Environment File Committed",category:"SECURITY",description:"Sensitive environment configuration file detected in repository",severity:"CRITICAL",weight:25,evaluator:t=>{let e=t.files.filter(n=>n.path_hash.endsWith(".env")||n.path_hash.endsWith(".env.local")||n.path_hash.endsWith(".env.development")||n.path_hash.endsWith(".env.production")||n.path_hash.endsWith(".pem")||n.path_hash.endsWith(".key"));return e.length>0?{rule_id:"RULE_001",title:"Sensitive Environment File Detected",message:`Found ${e.length} environment configuration files in source`,severity:"CRITICAL",category:"SECURITY",evidence:e.map(n=>n.path),explanation:"Environment files often contain passwords, API keys, and secrets. Committing them exposes credentials in version history.",impact:"Security breach risk. Credentials may be exposed to anyone with repository access.",effort:"Low",recommendations:["Add .env files to .gitignore immediately","Rotate any exposed credentials","Use environment variable managers like doppler or 1password","Document proper environment setup in README"]}:null}},Oi={id:"RULE_002",name:"Node Modules in Snapshot",category:"REPOSITORY_HYGIENE",description:"node_modules directory detected in snapshot",severity:"HIGH",weight:15,evaluator:t=>{let e=t.files.filter(n=>n.path_hash.includes("node_modules"));return e.length>0?{rule_id:"RULE_002",title:"Node Modules in Repository",message:`Found ${e.length} files in node_modules directory`,severity:"HIGH",category:"REPOSITORY_HYGIENE",evidence:["node_modules detected"],explanation:"node_modules should never be committed. It bloats the repo and causes merge conflicts.",impact:"Repository size increases by 100MB+. CI/CD slows down. Merge conflicts multiply.",effort:"Low",recommendations:["Add node_modules to .gitignore","Remove node_modules from git history","Ensure package.json and lock files are committed","Document npm install step in README"]}:null}},Di={id:"RULE_003",name:"Excessive File Count",category:"STRUCTURE",description:"Project contains unusually high number of files",severity:"HIGH",weight:15,evaluator:t=>t.metadata.total_files>5e3?{rule_id:"RULE_003",title:"Excessive File Count",message:`Project contains ${t.metadata.total_files} files (threshold: 5000)`,severity:"HIGH",category:"STRUCTURE",explanation:"High file count increases cognitive load and slows down development.",impact:"Onboarding takes 2-3x longer. CI/CD more complex. Tooling inconsistent.",effort:"High",recommendations:["Split large projects into smaller sub-projects","Remove unused or redundant files","Consider a monorepo structure"]}:null},Pi={id:"RULE_004",name:"Deep Directory Nesting",category:"STRUCTURE",description:"Directory depth exceeds maintainable structure",severity:"MEDIUM",weight:8,evaluator:t=>t.metadata.max_directory_depth>10?{rule_id:"RULE_004",title:"Deeply Nested Directory Structure",message:`Maximum directory depth is ${t.metadata.max_directory_depth} levels (threshold: 10)`,severity:"MEDIUM",category:"STRUCTURE",explanation:"Deep nesting makes imports verbose and navigation difficult.",impact:"Developer productivity decreases. File paths become unmanageable.",effort:"Medium",recommendations:["Flatten directory structure where possible","Use barrel exports (index.ts) to simplify imports","Consolidate related modules"]}:null},ji={id:"RULE_005",name:"Large Single Files",category:"COMPLEXITY",description:"Detects files exceeding size thresholds with language-aware limits",severity:"MEDIUM",weight:15,evaluator:t=>{let e=[/\.(generated|auto|min|bundle|spec)\.\w+$/i,/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/\d{14}_/i,/migration/i,/\.config\./i,/\.d\.ts$/i,/lock\.json$/i,/\.lock$/i,/\.lockb$/i,/pnpm-lock\.yaml$/i,/\.tsbuildinfo$/i,/\.sql$/i,/\.csv$/i,/\.json$/i,/node_modules/i,/dist\//i,/build\//i,/out\//i],n={tsx:{warning:400,critical:800},jsx:{warning:400,critical:800},ts:{warning:600,critical:1200},js:{warning:500,critical:1e3},py:{warning:800,critical:1600},java:{warning:800,critical:1500},cs:{warning:800,critical:1500},go:{warning:400,critical:800},rb:{warning:500,critical:1e3},php:{warning:600,critical:1200},c:{warning:800,critical:1500},cpp:{warning:800,critical:1500},default:{warning:600,critical:1200}},r=[];for(let c of t.files){if(c.is_binary||e.some(x=>x.test(c.path)))continue;let _=c.extension.toLowerCase(),b=n[_]||n.default;c.estimated_lines>b.critical?r.push({path:c.path,lines:c.estimated_lines,threshold:b.critical,level:"critical"}):c.estimated_lines>b.warning&&r.push({path:c.path,lines:c.estimated_lines,threshold:b.warning,level:"warning"});}if(r.length===0)return null;let s=r.filter(c=>c.level==="critical"),o=r.filter(c=>c.level==="warning"),a,i,l;if(s.length>0){i="HIGH";let c=s.slice(0,3).map(f=>`${f.path} (${f.lines} lines)`);a=s.length===1?`Found 1 very large file (${s[0].lines} lines). Consider splitting into smaller modules with single responsibilities.`:`Found ${s.length} very large files (>${s[0].threshold} lines each). Splitting into smaller modules will improve maintainability and testability.`,l=c;}else {i="MEDIUM";let c=o.slice(0,3).map(f=>`${f.path} (${f.lines} lines)`);a=o.length===1?`Found 1 large file (${o[0].lines} lines). Consider if it can be decomposed into smaller units.`:`Found ${o.length} large files. Review for potential decomposition into smaller, focused modules.`,l=c;}return {rule_id:"RULE_005",title:"Large File Detected",message:a,severity:i,category:"COMPLEXITY",evidence:l.length>0?l:void 0,explanation:"Large files slow down code reviews, increase cognitive load, and make refactoring risky. They often indicate multiple responsibilities mixed together.",impact:"Onboarding takes 2-3x longer. Bugs are harder to locate. Testing becomes difficult.",effort:i==="HIGH"?"Medium":"Low",recommendations:["Extract business logic into service modules","Move data access into repository layer","Split route handlers by resource/entity","Create dedicated validation utilities"]}}},Li={id:"RULE_006",name:"High Dependency Footprint",category:"DEPENDENCY",description:"Detects projects with excessive dependencies",severity:"MEDIUM",weight:8,evaluator:t=>t.metadata.total_dependencies>500?{rule_id:"RULE_006",title:"High Dependency Count",message:`Project has ${t.metadata.total_dependencies} dependencies (threshold: 500)`,severity:"MEDIUM",category:"DEPENDENCY",explanation:"Excessive dependencies increase attack surface, build time, and complexity.",impact:"Security vulnerabilities multiply. Updates become painful. Bundle size grows.",effort:"High",recommendations:["Audit dependencies with npm audit","Remove unused dependencies","Consolidate similar packages","Consider smaller alternatives"]}:null},Ui={id:"RULE_007",name:"Missing README",category:"DOCUMENTATION",description:"README.md not found in root directory",severity:"LOW",weight:3,evaluator:t=>t.files.some(n=>n.path.toLowerCase()==="readme.md"||n.path.toLowerCase().endsWith("/readme.md"))?null:{rule_id:"RULE_007",title:"Missing README Documentation",message:"No README.md file found in project root",severity:"LOW",category:"DOCUMENTATION",explanation:"README is the first thing developers see. It should explain what the project does and how to use it.",impact:"Onboarding slows down. External contributions decrease.",effort:"Low",recommendations:["Create README.md with project overview","Include installation and setup instructions","Add usage examples and API documentation"]}},$i={id:"RULE_008",name:"No Test Directory",category:"QUALITY",description:"Detects projects without test directories",severity:"MEDIUM",weight:8,evaluator:t=>t.files.some(n=>n.path.toLowerCase().includes("/test/")||n.path.toLowerCase().includes("/tests/")||n.path.toLowerCase().includes("/__tests__/")||n.path.toLowerCase().includes("/spec/")||n.path.toLowerCase().includes("/specs/")||n.path.toLowerCase().endsWith(".test.ts")||n.path.toLowerCase().endsWith(".test.tsx")||n.path.toLowerCase().endsWith(".spec.ts")||n.path.toLowerCase().endsWith(".spec.tsx")||n.path.toLowerCase().endsWith(".test.js")||n.path.toLowerCase().endsWith(".spec.js"))?null:{rule_id:"RULE_008",title:"No Test Suite Detected",message:"No test directory or test files found in project",severity:"MEDIUM",category:"QUALITY",explanation:"Tests catch bugs early, enable refactoring, and document expected behavior.",impact:"Bugs reach production. Refactoring is risky. Code quality degrades over time.",effort:"Medium",recommendations:["Set up testing framework (Jest, Vitest, etc.)","Start with critical path tests","Add tests for new features going forward","Aim for 70%+ coverage gradually"]}},Mi={id:"RULE_009",name:"Binary Files in Source",category:"REPOSITORY_HYGIENE",description:"Binary files detected in source tree",severity:"MEDIUM",weight:8,evaluator:t=>{let e=[".png",".jpg",".jpeg",".zip",".exe",".dll",".mp4"],n=t.files.filter(s=>{let o="."+s.extension.toLowerCase();return e.includes(o)}),r=n.length/t.metadata.total_files;return r>.05?{rule_id:"RULE_009",title:"Binary Files in Source",message:`Found ${n.length} binary files in source (${(r*100).toFixed(1)}% of total)`,severity:"MEDIUM",category:"REPOSITORY_HYGIENE",explanation:"Binary files bloat the repository and cannot be diffed effectively.",impact:"Clone times increase. Git operations slow down.",effort:"Low",recommendations:["Move binaries to external storage/CDN","Use Git LFS for large files if necessary","Keep images in separate assets repo"]}:null}},Fi={id:"RULE_010",name:"Build Artifacts Committed",category:"REPOSITORY_HYGIENE",description:"Compiled artifacts detected",severity:"HIGH",weight:15,evaluator:t=>{let e=t.files.filter(n=>n.path.includes("/dist/")||n.path.includes("/build/")||n.path.includes("/out/")||n.path.includes("/target/"));return e.length>0?{rule_id:"RULE_010",title:"Build Artifacts Committed",message:`Found ${e.length} build artifact files in source`,severity:"HIGH",category:"REPOSITORY_HYGIENE",explanation:"Build outputs should be generated during CI/CD, not committed. They cause merge conflicts.",impact:"Merge conflicts multiply. Repository size balloons unnecessarily.",effort:"Low",recommendations:["Remove dist/build folders from git","Add dist/ and build/ to .gitignore","Configure CI/CD to generate artifacts"]}:null}},Vi={id:"RULE_011",name:"Large Snapshot Size",category:"STRUCTURE",description:"Detects snapshots exceeding size limits",severity:"HIGH",weight:15,evaluator:t=>{let e=t.metadata.total_size_bytes/1048576;return e>5?{rule_id:"RULE_011",title:"Large Snapshot Size",message:`Snapshot size is ${e.toFixed(2)}MB (threshold: 5MB)`,severity:"HIGH",category:"STRUCTURE",explanation:"Very large repositories slow down all git operations and CI/CD.",impact:"Clone takes minutes. CI/CD pipelines slow. Developer productivity drops.",effort:"High",recommendations:["Split into microservices or monorepo packages","Remove large files from history","Use shallow clones in CI/CD"]}:null}},Bi={id:"RULE_012",name:"Configuration Files Missing",category:"QUALITY",description:"No package.json, requirements.txt, or equivalent found",severity:"LOW",weight:3,evaluator:t=>t.files.some(n=>{let r=n.path.split("/").pop()?.toLowerCase()||"";return r==="package.json"||r==="requirements.txt"||r==="cargo.toml"||r==="go.mod"||r==="pom.xml"})?null:{rule_id:"RULE_012",title:"Missing Dependency Configuration",message:"No recognized dependency configuration file found",severity:"LOW",category:"QUALITY",explanation:"A proper dependency file enables reproducible builds and version management.",impact:"New developers cannot install dependencies. Build is not reproducible.",effort:"Low",recommendations:["Add package.json for Node.js projects","Use appropriate config for your language (requirements.txt, Cargo.toml, etc.)","Commit lock files for reproducibility"]}},Hi={id:"RULE_013",name:"High Average File Size",category:"COMPLEXITY",description:"Average file size exceeds threshold",severity:"MEDIUM",weight:8,evaluator:t=>{let e=t.metadata.total_lines/t.metadata.total_files;return e>400?{rule_id:"RULE_013",title:"High Average File Size",message:`Average file size is ${e.toFixed(0)} lines (threshold: 400)`,severity:"MEDIUM",category:"COMPLEXITY",explanation:"When average file size is high, the codebase is likely to have structural issues.",impact:"Overall maintainability suffers. Code reviews take longer.",effort:"Medium",recommendations:["Review largest files for decomposition","Establish file size guidelines for team","Use lint rules to enforce limits"]}:null}},zi={id:"RULE_014",name:"Multiple Lock Files",category:"DEPENDENCY",description:"Multiple dependency lock files detected",severity:"LOW",weight:3,evaluator:t=>{let e=t.files.filter(n=>{let r=n.path.split("/").pop()?.toLowerCase()||"";return r==="package-lock.json"||r==="yarn.lock"||r==="pnpm-lock.yaml"||r==="bun.lockb"});return e.length>1?{rule_id:"RULE_014",title:"Multiple Lock Files Detected",message:`Found ${e.length} lock files (expected: 1)`,severity:"LOW",category:"DEPENDENCY",explanation:"Multiple lock files indicate different package managers being used, causing inconsistency.",impact:"Dependency versions may differ between environments. Confusion for developers.",effort:"Low",recommendations:["Choose one package manager (npm, yarn, or pnpm)","Delete lock files from other managers","Document chosen package manager in README"]}:null}},Wi={id:"RULE_015",name:"Hardcoded Secrets Detection",category:"SECURITY",description:"Detects hardcoded secrets in source files",severity:"CRITICAL",weight:25,evaluator:t=>{let e=["ts","tsx","js","jsx","json","yaml","yml","env","config","conf"],n=[{name:"Stripe API Key",pattern:/sk_(live|test)_[0-9a-zA-Z]{20,}/g,severity:"CRITICAL"},{name:"JWT Secret",pattern:/JWT_SECRET\s*=\s*["']([^"']{8,})["']/g,severity:"CRITICAL"},{name:"Database Password",pattern:/(DB_PASSWORD|DATABASE_URL)\s*=\s*["']([^"']+)["']/g,severity:"CRITICAL"},{name:"Private Key",pattern:/-----BEGIN (RSA )?PRIVATE KEY-----/g,severity:"CRITICAL"},{name:"Generic Secret Assignment",pattern:/(password|secret|token|api_key|apikey)\s*[:=]\s*["']([^"']{8,})["']/gi,severity:"HIGH"}],r=[];for(let s of t.files){if(s.is_binary||s.size_bytes>1024*1024)continue;let o=s.extension.toLowerCase();if(e.includes(o))try{let a=jr("fs"),i=jr("path"),l=t.project_root?i.join(t.project_root,s.path):s.path,c=a.readFileSync(l,"utf-8");for(let f of n){let _=c.matchAll(f.pattern);for(let b of _){let x=b[0].replace(/["']([^"']{4,})["']/g,'"****"');r.push({file:s.path,type:f.name,severity:f.severity,masked:x});}}}catch{continue}}if(r.length>0){let s=r.filter(i=>i.severity==="CRITICAL");r.filter(i=>i.severity==="HIGH");let a=r.slice(0,10).map(i=>`${i.file}: ${i.type} (${i.masked})`);return {rule_id:"RULE_015",title:"Hardcoded Secrets Detected",message:`Found ${r.length} hardcoded secret(s) in source code`,severity:s.length>0?"CRITICAL":"HIGH",category:"SECURITY",evidence:a,explanation:"Hardcoded secrets in source code are a critical security risk. They can be extracted from version history and used to compromise your systems.",impact:"Attackers can access your databases, APIs, and services. Credentials remain exposed forever in git history.",effort:"Medium",recommendations:["Move all secrets to environment variables","Use secret management services (AWS Secrets Manager, Doppler, etc.)","Rotate all exposed credentials immediately","Add pre-commit hooks to prevent future commits","Remove secrets from git history using git-filter-repo"]}}return null}},Gi=[Ni,Oi,Di,Pi,ji,Li,Ui,$i,Mi,Fi,Vi,Bi,Hi,zi,Wi],Vr=class{options;constructor(t){this.options={maxFiles:100,includeRawContent:false,...t};}async scan(t){let e=await this.discoverFiles(),n=await this.extractDependencies(),r=this.options.framework||this.detectFramework(),s=this.detectLanguage(e),a=e.slice(0,this.options.maxFiles).map(l=>{let c=this.extractASTTokens(l.content,l.extension);return {path_hash:this.hash(l.path),content_hash:this.hash(l.content),extension:l.extension,size_bytes:l.size,ast_tokens:c.slice(0,500),raw_content:this.options.includeRawContent?l.content:void 0}}),i={framework:r,language:s,total_files:e.length,total_dependencies:n.length,file_types:this.calculateFileTypes(e)};return {version:ae,project_id:de__default.randomUUID(),session_id:t,generated_at:new Date().toISOString(),metadata:i,files:a,dependencies:n}}async discoverFiles(){let t=[],e=await glob(["**/*.{ts,tsx,js,jsx,json}"],{cwd:this.options.projectPath,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/.veestack/**"],absolute:false});for(let n of e){let r=join(this.options.projectPath,n);try{let s=statSync(r);if(!s.isFile()||s.size>1024*1024)continue;let o=readFileSync(r,"utf-8"),a=n.split(".").pop()||"";t.push({path:n,content:o,extension:a,size:s.size});}catch{continue}}return t}extractASTTokens(t,e){let n=[],r=t.split(`
6
- `),s=new Set(["function","const","let","var","class","import","export","return","if","else","for","while","try","catch","eval","dangerouslySetInnerHTML","document","window"]),o=new Set(["eval","setTimeout","setInterval","Function","exec","innerHTML","document.write","dangerouslySetInnerHTML"]);return r.forEach((a,i)=>{let l=i+1;if(s.forEach(_=>{let b=new RegExp(`\\b${_}\\b`,"g"),x;for(;(x=b.exec(a))!==null;)n.push({type:"keyword",value:_,line:l,column:x.index+1});}),o.forEach(_=>{let b=new RegExp(`${_.replace(".","\\.")}\\s*\\(`,"g"),x;for(;(x=b.exec(a))!==null;)n.push({type:"call_expression",value:_,line:l,column:x.index+1});}),e==="tsx"||e==="jsx"){let _=/<[A-Z][a-zA-Z0-9]*/g,b;for(;(b=_.exec(a))!==null;)n.push({type:"jsx_element",value:b[0].substring(1),line:l,column:b.index+1});a.includes("dangerouslySetInnerHTML")&&n.push({type:"property_access",value:"dangerouslySetInnerHTML",line:l,column:a.indexOf("dangerouslySetInnerHTML")+1});}let c=/['"]([^'"]*)['"]/g,f;for(;(f=c.exec(a))!==null;){let _=f[1];(_.includes(".env")||_.includes(".pem")||_.includes(".key"))&&n.push({type:"string",value:_,line:l,column:f.index+1});}}),n}async extractDependencies(){let t=[];try{let e=join(this.options.projectPath,"package.json");if(!existsSync(e))return t;let n=JSON.parse(readFileSync(e,"utf-8")),r=(s,o)=>{for(let[a,i]of Object.entries(s)){let l=i.match(/^(\d+)\.(\d+)/),c=l?parseInt(l[1]):0;t.push({name_hash:this.hash(a),version:i.replace(/[^\d.]/g,""),major_version:c,category:o});}};n.dependencies&&r(n.dependencies,"production"),n.devDependencies&&r(n.devDependencies,"development"),n.peerDependencies&&r(n.peerDependencies,"peer");}catch{}return t}detectFramework(){let t=this.options.projectPath;if(existsSync(join(t,"next.config.js"))||existsSync(join(t,"next.config.mjs"))||existsSync(join(t,"next.config.ts")))return "nextjs";try{let e=JSON.parse(readFileSync(join(t,"package.json"),"utf-8"));if(e.dependencies?.next)return "nextjs";if(e.dependencies?.react)return "react";if(e.dependencies?.vue)return "vue";if(e.dependencies?.["@angular/core"])return "angular";if(e.dependencies?.svelte)return "svelte"}catch{}return "node"}detectLanguage(t){let e=0,n=0;return t.forEach(r=>{r.extension==="ts"||r.extension==="tsx"?e++:(r.extension==="js"||r.extension==="jsx")&&n++;}),e>0&&n>0?"mixed":e>0?"typescript":"javascript"}calculateFileTypes(t){let e={};return t.forEach(n=>{let r=n.extension||"unknown";e[r]=(e[r]||0)+1;}),e}hash(t){return de__default.createHash("sha256").update(t).digest("hex")}};});var cs=[/^--token[=\s]/i,/^-t[=\s]/i,/^--api-key[=\s]/i,/^--apikey[=\s]/i,/^--key[=\s]/i,/^--auth[=\s]/i,/^--bearer[=\s]/i,/token[=:]\s*[a-zA-Z0-9_-]{10,}/i,/api[_-]?key[=:]\s*[a-zA-Z0-9_-]{10,}/i],qe=/vs_[a-zA-Z0-9_-]{20,}/i;function Wn(){let t=process.argv.slice(2);for(let e of t){for(let n of cs)n.test(e)&&(console.error(h.red(`
5
+ Please check your .env file and ensure all required variables are set.`)}throw t}}function $o(){return An||(An=Uo()),An}function Mo(t=jo.api.rateLimit){let{windowMs:e,maxRequests:n,message:r}=t;return {check(s){let o=Date.now(),a=He.get(s);a&&o>a.resetTime&&He.delete(s);let i=He.get(s)||{count:0,resetTime:o+e};return i.count>=n?{success:false,remaining:0,resetTime:i.resetTime,error:r||"Too many requests"}:(i.count++,He.set(s,i),{success:true,remaining:n-i.count,resetTime:i.resetTime})},reset(s){He.delete(s);},cleanup(){let s=Date.now();for(let[o,a]of He.entries())s>a.resetTime&&He.delete(o);}}}var jo,Lo,An,k,fr,Wt,E,He,K=G(()=>{_n();_n();pr();jo={versions:{cli:V,engine:V,frontend:V,api:vn,snapshot:ce,engine_target:Qe},analysis:{maxFileSize:2*1024*1024,maxFileCount:2e3,maxDependencyCount:2e3,maxDirectoryDepth:10,timeout:5e3},scoring:{baseScore:100,CRITICAL:25,HIGH:15,MEDIUM:8,LOW:3,severityBands:{HEALTHY:{min:90,max:100},STABLE:{min:75,max:89},STRUCTURAL_CONCERN:{min:60,max:74},HIGH_RISK:{min:0,max:59}}},api:{rateLimit:{windowMs:900*1e3,maxRequests:100},timeout:1e4},snapshot:{schemaVersion:ce,engineTargetVersion:Qe},usage:{free:{scansPerMonth:3,retentionDays:7},pro:{scansPerMonth:100,retentionDays:90}},security:{bcryptRounds:10,jwtExpiration:"7d",maxLoginAttempts:5,lockoutDuration:900*1e3},storage:{bucketName:"snapshots",maxRetries:3,chunkSize:1024*1024},ui:{maxFindingsPerPage:50,maxReportHistory:100}},d.object({snapshot_version:d.string(),engine_target_version:d.string(),project_id:d.string(),generated_at:d.string(),root_path_hash:d.string(),metadata:d.object({total_files:d.number().int().nonnegative(),total_dependencies:d.number().int().nonnegative(),total_size_bytes:d.number().int().nonnegative(),total_lines:d.number().int().nonnegative(),max_directory_depth:d.number().int().nonnegative(),language_breakdown:d.record(d.string(),d.number().int().nonnegative())}),files:d.array(d.object({id:d.string(),path_hash:d.string(),depth:d.number().int().nonnegative(),size_bytes:d.number().int().nonnegative(),estimated_lines:d.number().int().nonnegative(),extension:d.string(),is_binary:d.boolean(),import_count:d.number().int().nonnegative().optional(),function_count:d.number().int().nonnegative().optional(),class_count:d.number().int().nonnegative().optional()})),dependencies:d.array(d.object({id:d.string(),name_hash:d.string(),major_version:d.number().int().nonnegative(),minor_version:d.number().int().nonnegative(),category:d.enum(["dev","prod","peer"])}))}),d.object({name:d.string().min(1).max(100)}),d.object({analysis_version:d.string(),snapshot_schema_version:d.string(),total_score:d.number().min(0).max(100),severity_band:d.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),engines:d.array(d.object({engine_name:d.string(),score_impact:d.number(),risk_level:d.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),metrics:d.record(d.number()),findings:d.array(d.object({rule_id:d.string(),title:d.string(),message:d.string(),severity:d.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:d.enum(["SECURITY","STRUCTURE","COMPLEXITY","DEPENDENCY","REPOSITORY_HYGIENE","DOCUMENTATION","QUALITY"]),evidence:d.array(d.string()).optional(),explanation:d.string().optional(),impact:d.string().optional(),effort:d.enum(["Low","Medium","High"]).optional(),recommendations:d.array(d.string()).optional()}))})),summary:d.object({total_findings:d.number().int().nonnegative(),critical_count:d.number().int().nonnegative(),high_count:d.number().int().nonnegative(),medium_count:d.number().int().nonnegative(),low_count:d.number().int().nonnegative(),categories:d.record(d.string(),d.number().int().nonnegative())}),generated_at:d.string()}),Lo=d.object({NEXT_PUBLIC_SUPABASE_URL:d.string().url("Invalid SUPABASE_URL"),NEXT_PUBLIC_SUPABASE_ANON_KEY:d.string().min(1,"SUPABASE_ANON_KEY is required"),SUPABASE_SERVICE_ROLE_KEY:d.string().min(1,"SERVICE_ROLE_KEY is required"),NODE_ENV:d.enum(["development","production","test"],{errorMap:()=>({message:"NODE_ENV must be development, production, or test"})}),JWT_SECRET:d.string().min(32,"JWT_SECRET must be at least 32 characters").optional()});An=null;new Proxy({},{get(t,e){return $o()[e]}}),k={plans:{FREE:{name:"free",scansPerMonth:10,projects:3,snapshots:10,reports:10,maxFileSizeMB:5,maxFilesPerSnapshot:100,storageMB:100,teamMembers:1,support:"community",features:["basic-analysis","security-scan"]},PRO:{name:"pro",scansPerMonth:-1,projects:-1,snapshots:-1,reports:-1,maxFileSizeMB:50,maxFilesPerSnapshot:1e3,storageMB:1e4,teamMembers:10,support:"priority",features:["basic-analysis","security-scan","advanced-analytics","api-access","team-collaboration","priority-support"]}},roles:{MEMBER:"member",SUPPORT:"support",ADMIN:"admin",OWNER:"owner"},permissions:{PROJECT_READ:"project:read",PROJECT_CREATE:"project:create",PROJECT_UPDATE:"project:update",PROJECT_DELETE:"project:delete",SNAPSHOT_READ:"snapshot:read",SNAPSHOT_CREATE:"snapshot:create",SNAPSHOT_DELETE:"snapshot:delete",REPORT_READ:"report:read",REPORT_DOWNLOAD:"report:download",TEAM_READ:"team:read",TEAM_INVITE:"team:invite",TEAM_REMOVE:"team:remove",USER_READ:"user:read",USER_UPDATE:"user:update",USER_DELETE:"user:delete",SYSTEM_MANAGE:"system:manage",ALL:"*",READ_OWN:"read:own",CREATE_OWN:"create:own",UPDATE_OWN:"update:own",DELETE_OWN:"delete:own",READ_ALL:"read:all",CREATE_ALL:"create:all",UPDATE_ALL:"update:all",DELETE_ALL:"delete:all",SCAN_OWN:"scan:own",REPORT_OWN:"report:own",ANALYTICS_VIEW:"analytics:view",SUPPORT_ACCESS:"support:access",SUPPORT_VIEW_TICKETS:"support:view-tickets"},features:{BASIC_ANALYSIS:"basic-analysis",SECURITY_SCAN:"security-scan",ADVANCED_ANALYTICS:"advanced-analytics",API_ACCESS:"api-access",TEAM_COLLAB:"team-collaboration",PRIORITY_SUPPORT:"priority-support"}},fr={FREE:k.plans.FREE.name,PRO:k.plans.PRO.name},{BASIC_ANALYSIS:k.features.BASIC_ANALYSIS,SECURITY_SCAN:k.features.SECURITY_SCAN,ADVANCED_ANALYTICS:k.features.ADVANCED_ANALYTICS,API_ACCESS:k.features.API_ACCESS,TEAM_COLLAB:k.features.TEAM_COLLAB,PRIORITY_SUPPORT:k.features.PRIORITY_SUPPORT},{[fr.FREE]:k.plans.FREE,[fr.PRO]:k.plans.PRO},Wt={MEMBER:k.roles.MEMBER,SUPPORT:k.roles.SUPPORT,ADMIN:k.roles.ADMIN,OWNER:k.roles.OWNER},E={PROJECT_READ:k.permissions.PROJECT_READ,PROJECT_CREATE:k.permissions.PROJECT_CREATE,PROJECT_UPDATE:k.permissions.PROJECT_UPDATE,PROJECT_DELETE:k.permissions.PROJECT_DELETE,SNAPSHOT_READ:k.permissions.SNAPSHOT_READ,SNAPSHOT_CREATE:k.permissions.SNAPSHOT_CREATE,SNAPSHOT_DELETE:k.permissions.SNAPSHOT_DELETE,REPORT_READ:k.permissions.REPORT_READ,REPORT_DOWNLOAD:k.permissions.REPORT_DOWNLOAD,TEAM_READ:k.permissions.TEAM_READ,TEAM_INVITE:k.permissions.TEAM_INVITE,TEAM_REMOVE:k.permissions.TEAM_REMOVE,USER_READ:k.permissions.USER_READ,USER_UPDATE:k.permissions.USER_UPDATE,USER_DELETE:k.permissions.USER_DELETE,SYSTEM_MANAGE:k.permissions.SYSTEM_MANAGE,ALL:k.permissions.ALL,READ_OWN:k.permissions.READ_OWN,CREATE_OWN:k.permissions.CREATE_OWN,UPDATE_OWN:k.permissions.UPDATE_OWN,DELETE_OWN:k.permissions.DELETE_OWN,READ_ALL:k.permissions.READ_ALL,CREATE_ALL:k.permissions.CREATE_ALL,UPDATE_ALL:k.permissions.UPDATE_ALL,DELETE_ALL:k.permissions.DELETE_ALL,SCAN_OWN:k.permissions.SCAN_OWN,REPORT_OWN:k.permissions.REPORT_OWN,ANALYTICS_VIEW:k.permissions.ANALYTICS_VIEW,SUPPORT_ACCESS:k.permissions.SUPPORT_ACCESS,SUPPORT_VIEW_TICKETS:k.permissions.SUPPORT_VIEW_TICKETS},{[Wt.MEMBER]:[E.READ_OWN,E.CREATE_OWN,E.UPDATE_OWN,E.DELETE_OWN,E.SCAN_OWN,E.REPORT_OWN,E.PROJECT_READ,E.PROJECT_CREATE,E.PROJECT_UPDATE,E.PROJECT_DELETE,E.SNAPSHOT_READ,E.SNAPSHOT_CREATE,E.SNAPSHOT_DELETE,E.REPORT_READ,E.REPORT_DOWNLOAD],[Wt.SUPPORT]:[E.READ_ALL,E.PROJECT_READ,E.SNAPSHOT_READ,E.REPORT_READ,E.USER_READ,E.SUPPORT_ACCESS,E.SUPPORT_VIEW_TICKETS],[Wt.ADMIN]:[E.READ_ALL,E.CREATE_ALL,E.UPDATE_ALL,E.DELETE_ALL,E.USER_READ,E.USER_UPDATE,E.USER_DELETE,E.SYSTEM_MANAGE,E.REPORT_READ,E.ANALYTICS_VIEW],[Wt.OWNER]:[E.ALL]},{projects:{read:E.PROJECT_READ,create:E.PROJECT_CREATE,update:E.PROJECT_UPDATE,delete:E.PROJECT_DELETE},snapshots:{read:E.SNAPSHOT_READ,create:E.SNAPSHOT_CREATE,delete:E.SNAPSHOT_DELETE},reports:{read:E.REPORT_READ},users:{read:E.USER_READ,update:E.USER_UPDATE}},He=new Map;Mo();});var on,an,Pr=G(()=>{on={BASE_SCORE:100,MIN_SCORE:0,MAX_SCORE:100},an={HEALTHY:{min:90,max:100},STABLE:{min:75,max:89},STRUCTURAL_CONCERN:{min:60,max:74},HIGH_RISK:{min:0,max:59}};});var Pn={};zn(Pn,{CoreEngine:()=>Ii,ProjectScanner:()=>Vr,RULES:()=>Gi,ReportGenerator:()=>Fr,RuleRegistry:()=>$r,ScoringEngine:()=>Mr,SnapshotValidator:()=>Ur,scanProject:()=>Ji});async function Ji(t,e,n){return new Vr({projectPath:t,...n}).scan(e)}var jr,Ur,$r,Mr,Fr,Ii,Ni,Oi,Di,Pi,ji,Li,Ui,$i,Mi,Fi,Vi,Bi,Hi,zi,Wi,Gi,Vr,jn=G(()=>{Pr();K();K();jr=(t=>typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>e[n]}):t)(function(t){throw Error('Dynamic require of "'+t+'" is not supported')}),Ur=class{validate(t){let e=[];return t.snapshot_version||e.push("Missing snapshot_version"),t.engine_target_version||e.push("Missing engine_target_version"),(!t.files||!Array.isArray(t.files))&&e.push("Invalid or missing files array"),(!t.dependencies||!Array.isArray(t.dependencies))&&e.push("Invalid or missing dependencies array"),t.files&&t.files.length>2e3&&e.push("File count exceeds maximum limit of 2000"),{valid:e.length===0,error:e.length>0?e.join(", "):void 0}}},$r=class{rules=[];register(t){this.rules.push(t);}executeAllRules(t){let e=[],n=[...this.rules].sort((r,s)=>r.id.localeCompare(s.id));for(let r of n)try{let s=r.evaluator(t);s&&e.push({rule_id:r.id,severity:s.severity,weight:r.weight,title:s.title,message:s.message,category:s.category,evidence:s.evidence,explanation:s.explanation,impact:s.impact,effort:s.effort,recommendations:s.recommendations});}catch{}return e}},Mr=class{calculateScore(t){let e=on.BASE_SCORE;for(let n of t)e-=n.weight;return Math.max(on.MIN_SCORE,Math.min(on.MAX_SCORE,e))}getSeverityBand(t){return t>=an.HEALTHY.min?"HEALTHY":t>=an.STABLE.min?"STABLE":t>=an.STRUCTURAL_CONCERN.min?"STRUCTURAL_CONCERN":"HIGH_RISK"}},Fr=class{generateReport(t,e,n,r){let s=e.map(i=>({rule_id:i.rule_id,title:i.title,message:i.message,severity:i.severity,category:i.category,evidence:i.evidence,explanation:i.explanation,impact:i.impact,effort:i.effort,recommendations:i.recommendations})),o=this.generateSummary(e),a={engine_name:"VeeStack Core Engine",score_impact:100-n,risk_level:r,metrics:{total_files:t.metadata.total_files,total_dependencies:t.metadata.total_dependencies,total_size_bytes:t.metadata.total_size_bytes,max_directory_depth:t.metadata.max_directory_depth},findings:s};return {analysis_version:ce,snapshot_schema_version:t.snapshot_version,total_score:n,severity_band:r,engines:[a],summary:o,generated_at:new Date().toISOString()}}generateSummary(t){let e={};for(let n of t){let r=this.getCategoryFromRuleId(n.rule_id);e[r]=(e[r]||0)+1;}return {total_findings:t.length,critical_count:t.filter(n=>n.severity==="CRITICAL").length,high_count:t.filter(n=>n.severity==="HIGH").length,medium_count:t.filter(n=>n.severity==="MEDIUM").length,low_count:t.filter(n=>n.severity==="LOW").length,categories:e}}getCategoryFromRuleId(t){let e=t.split("_")[0];return {SEC:"SECURITY",STR:"STRUCTURE",COM:"COMPLEXITY",DEP:"DEPENDENCY",HYG:"REPOSITORY_HYGIENE",DOC:"DOCUMENTATION",QUA:"QUALITY"}[e]||"OTHER"}},Ii=class{validator;ruleRegistry;scoringEngine;reportGenerator;constructor(){this.validator=new Ur,this.ruleRegistry=new $r,this.scoringEngine=new Mr,this.reportGenerator=new Fr;}registerRule(t){this.ruleRegistry.register(t);}async analyze(t){let e=this.validator.validate(t);if(!e.valid)return {success:false,error:{error:e.error,code:400}};let n=this.ruleRegistry.executeAllRules(t),r=this.scoringEngine.calculateScore(n),s=this.scoringEngine.getSeverityBand(r);return {success:true,report:this.reportGenerator.generateReport(t,n,r,s)}}},Ni={id:"RULE_001",name:"Environment File Committed",category:"SECURITY",description:"Sensitive environment configuration file detected in repository",severity:"CRITICAL",weight:25,evaluator:t=>{let e=t.files.filter(n=>n.path_hash.endsWith(".env")||n.path_hash.endsWith(".env.local")||n.path_hash.endsWith(".env.development")||n.path_hash.endsWith(".env.production")||n.path_hash.endsWith(".pem")||n.path_hash.endsWith(".key"));return e.length>0?{rule_id:"RULE_001",title:"Sensitive Environment File Detected",message:`Found ${e.length} environment configuration files in source`,severity:"CRITICAL",category:"SECURITY",evidence:e.map(n=>n.path),explanation:"Environment files often contain passwords, API keys, and secrets. Committing them exposes credentials in version history.",impact:"Security breach risk. Credentials may be exposed to anyone with repository access.",effort:"Low",recommendations:["Add .env files to .gitignore immediately","Rotate any exposed credentials","Use environment variable managers like doppler or 1password","Document proper environment setup in README"]}:null}},Oi={id:"RULE_002",name:"Node Modules in Snapshot",category:"REPOSITORY_HYGIENE",description:"node_modules directory detected in snapshot",severity:"HIGH",weight:15,evaluator:t=>{let e=t.files.filter(n=>n.path_hash.includes("node_modules"));return e.length>0?{rule_id:"RULE_002",title:"Node Modules in Repository",message:`Found ${e.length} files in node_modules directory`,severity:"HIGH",category:"REPOSITORY_HYGIENE",evidence:["node_modules detected"],explanation:"node_modules should never be committed. It bloats the repo and causes merge conflicts.",impact:"Repository size increases by 100MB+. CI/CD slows down. Merge conflicts multiply.",effort:"Low",recommendations:["Add node_modules to .gitignore","Remove node_modules from git history","Ensure package.json and lock files are committed","Document npm install step in README"]}:null}},Di={id:"RULE_003",name:"Excessive File Count",category:"STRUCTURE",description:"Project contains unusually high number of files",severity:"HIGH",weight:15,evaluator:t=>t.metadata.total_files>5e3?{rule_id:"RULE_003",title:"Excessive File Count",message:`Project contains ${t.metadata.total_files} files (threshold: 5000)`,severity:"HIGH",category:"STRUCTURE",explanation:"High file count increases cognitive load and slows down development.",impact:"Onboarding takes 2-3x longer. CI/CD more complex. Tooling inconsistent.",effort:"High",recommendations:["Split large projects into smaller sub-projects","Remove unused or redundant files","Consider a monorepo structure"]}:null},Pi={id:"RULE_004",name:"Deep Directory Nesting",category:"STRUCTURE",description:"Directory depth exceeds maintainable structure",severity:"MEDIUM",weight:8,evaluator:t=>t.metadata.max_directory_depth>10?{rule_id:"RULE_004",title:"Deeply Nested Directory Structure",message:`Maximum directory depth is ${t.metadata.max_directory_depth} levels (threshold: 10)`,severity:"MEDIUM",category:"STRUCTURE",explanation:"Deep nesting makes imports verbose and navigation difficult.",impact:"Developer productivity decreases. File paths become unmanageable.",effort:"Medium",recommendations:["Flatten directory structure where possible","Use barrel exports (index.ts) to simplify imports","Consolidate related modules"]}:null},ji={id:"RULE_005",name:"Large Single Files",category:"COMPLEXITY",description:"Detects files exceeding size thresholds with language-aware limits",severity:"MEDIUM",weight:15,evaluator:t=>{let e=[/\.(generated|auto|min|bundle|spec)\.\w+$/i,/\.(test|spec)\.(ts|tsx|js|jsx)$/i,/\d{14}_/i,/migration/i,/\.config\./i,/\.d\.ts$/i,/lock\.json$/i,/\.lock$/i,/\.lockb$/i,/pnpm-lock\.yaml$/i,/\.tsbuildinfo$/i,/\.sql$/i,/\.csv$/i,/\.json$/i,/node_modules/i,/dist\//i,/build\//i,/out\//i],n={tsx:{warning:400,critical:800},jsx:{warning:400,critical:800},ts:{warning:600,critical:1200},js:{warning:500,critical:1e3},py:{warning:800,critical:1600},java:{warning:800,critical:1500},cs:{warning:800,critical:1500},go:{warning:400,critical:800},rb:{warning:500,critical:1e3},php:{warning:600,critical:1200},c:{warning:800,critical:1500},cpp:{warning:800,critical:1500},default:{warning:600,critical:1200}},r=[];for(let c of t.files){if(c.is_binary||e.some(x=>x.test(c.path)))continue;let _=c.extension.toLowerCase(),b=n[_]||n.default;c.estimated_lines>b.critical?r.push({path:c.path,lines:c.estimated_lines,threshold:b.critical,level:"critical"}):c.estimated_lines>b.warning&&r.push({path:c.path,lines:c.estimated_lines,threshold:b.warning,level:"warning"});}if(r.length===0)return null;let s=r.filter(c=>c.level==="critical"),o=r.filter(c=>c.level==="warning"),a,i,l;if(s.length>0){i="HIGH";let c=s.slice(0,3).map(f=>`${f.path} (${f.lines} lines)`);a=s.length===1?`Found 1 very large file (${s[0].lines} lines). Consider splitting into smaller modules with single responsibilities.`:`Found ${s.length} very large files (>${s[0].threshold} lines each). Splitting into smaller modules will improve maintainability and testability.`,l=c;}else {i="MEDIUM";let c=o.slice(0,3).map(f=>`${f.path} (${f.lines} lines)`);a=o.length===1?`Found 1 large file (${o[0].lines} lines). Consider if it can be decomposed into smaller units.`:`Found ${o.length} large files. Review for potential decomposition into smaller, focused modules.`,l=c;}return {rule_id:"RULE_005",title:"Large File Detected",message:a,severity:i,category:"COMPLEXITY",evidence:l.length>0?l:void 0,explanation:"Large files slow down code reviews, increase cognitive load, and make refactoring risky. They often indicate multiple responsibilities mixed together.",impact:"Onboarding takes 2-3x longer. Bugs are harder to locate. Testing becomes difficult.",effort:i==="HIGH"?"Medium":"Low",recommendations:["Extract business logic into service modules","Move data access into repository layer","Split route handlers by resource/entity","Create dedicated validation utilities"]}}},Li={id:"RULE_006",name:"High Dependency Footprint",category:"DEPENDENCY",description:"Detects projects with excessive dependencies",severity:"MEDIUM",weight:8,evaluator:t=>t.metadata.total_dependencies>500?{rule_id:"RULE_006",title:"High Dependency Count",message:`Project has ${t.metadata.total_dependencies} dependencies (threshold: 500)`,severity:"MEDIUM",category:"DEPENDENCY",explanation:"Excessive dependencies increase attack surface, build time, and complexity.",impact:"Security vulnerabilities multiply. Updates become painful. Bundle size grows.",effort:"High",recommendations:["Audit dependencies with npm audit","Remove unused dependencies","Consolidate similar packages","Consider smaller alternatives"]}:null},Ui={id:"RULE_007",name:"Missing README",category:"DOCUMENTATION",description:"README.md not found in root directory",severity:"LOW",weight:3,evaluator:t=>t.files.some(n=>n.path.toLowerCase()==="readme.md"||n.path.toLowerCase().endsWith("/readme.md"))?null:{rule_id:"RULE_007",title:"Missing README Documentation",message:"No README.md file found in project root",severity:"LOW",category:"DOCUMENTATION",explanation:"README is the first thing developers see. It should explain what the project does and how to use it.",impact:"Onboarding slows down. External contributions decrease.",effort:"Low",recommendations:["Create README.md with project overview","Include installation and setup instructions","Add usage examples and API documentation"]}},$i={id:"RULE_008",name:"No Test Directory",category:"QUALITY",description:"Detects projects without test directories",severity:"MEDIUM",weight:8,evaluator:t=>t.files.some(n=>n.path.toLowerCase().includes("/test/")||n.path.toLowerCase().includes("/tests/")||n.path.toLowerCase().includes("/__tests__/")||n.path.toLowerCase().includes("/spec/")||n.path.toLowerCase().includes("/specs/")||n.path.toLowerCase().endsWith(".test.ts")||n.path.toLowerCase().endsWith(".test.tsx")||n.path.toLowerCase().endsWith(".spec.ts")||n.path.toLowerCase().endsWith(".spec.tsx")||n.path.toLowerCase().endsWith(".test.js")||n.path.toLowerCase().endsWith(".spec.js"))?null:{rule_id:"RULE_008",title:"No Test Suite Detected",message:"No test directory or test files found in project",severity:"MEDIUM",category:"QUALITY",explanation:"Tests catch bugs early, enable refactoring, and document expected behavior.",impact:"Bugs reach production. Refactoring is risky. Code quality degrades over time.",effort:"Medium",recommendations:["Set up testing framework (Jest, Vitest, etc.)","Start with critical path tests","Add tests for new features going forward","Aim for 70%+ coverage gradually"]}},Mi={id:"RULE_009",name:"Binary Files in Source",category:"REPOSITORY_HYGIENE",description:"Binary files detected in source tree",severity:"MEDIUM",weight:8,evaluator:t=>{let e=[".png",".jpg",".jpeg",".zip",".exe",".dll",".mp4"],n=t.files.filter(s=>{let o="."+s.extension.toLowerCase();return e.includes(o)}),r=n.length/t.metadata.total_files;return r>.05?{rule_id:"RULE_009",title:"Binary Files in Source",message:`Found ${n.length} binary files in source (${(r*100).toFixed(1)}% of total)`,severity:"MEDIUM",category:"REPOSITORY_HYGIENE",explanation:"Binary files bloat the repository and cannot be diffed effectively.",impact:"Clone times increase. Git operations slow down.",effort:"Low",recommendations:["Move binaries to external storage/CDN","Use Git LFS for large files if necessary","Keep images in separate assets repo"]}:null}},Fi={id:"RULE_010",name:"Build Artifacts Committed",category:"REPOSITORY_HYGIENE",description:"Compiled artifacts detected",severity:"HIGH",weight:15,evaluator:t=>{let e=t.files.filter(n=>n.path.includes("/dist/")||n.path.includes("/build/")||n.path.includes("/out/")||n.path.includes("/target/"));return e.length>0?{rule_id:"RULE_010",title:"Build Artifacts Committed",message:`Found ${e.length} build artifact files in source`,severity:"HIGH",category:"REPOSITORY_HYGIENE",explanation:"Build outputs should be generated during CI/CD, not committed. They cause merge conflicts.",impact:"Merge conflicts multiply. Repository size balloons unnecessarily.",effort:"Low",recommendations:["Remove dist/build folders from git","Add dist/ and build/ to .gitignore","Configure CI/CD to generate artifacts"]}:null}},Vi={id:"RULE_011",name:"Large Snapshot Size",category:"STRUCTURE",description:"Detects snapshots exceeding size limits",severity:"HIGH",weight:15,evaluator:t=>{let e=t.metadata.total_size_bytes/1048576;return e>5?{rule_id:"RULE_011",title:"Large Snapshot Size",message:`Snapshot size is ${e.toFixed(2)}MB (threshold: 5MB)`,severity:"HIGH",category:"STRUCTURE",explanation:"Very large repositories slow down all git operations and CI/CD.",impact:"Clone takes minutes. CI/CD pipelines slow. Developer productivity drops.",effort:"High",recommendations:["Split into microservices or monorepo packages","Remove large files from history","Use shallow clones in CI/CD"]}:null}},Bi={id:"RULE_012",name:"Configuration Files Missing",category:"QUALITY",description:"No package.json, requirements.txt, or equivalent found",severity:"LOW",weight:3,evaluator:t=>t.files.some(n=>{let r=n.path.split("/").pop()?.toLowerCase()||"";return r==="package.json"||r==="requirements.txt"||r==="cargo.toml"||r==="go.mod"||r==="pom.xml"})?null:{rule_id:"RULE_012",title:"Missing Dependency Configuration",message:"No recognized dependency configuration file found",severity:"LOW",category:"QUALITY",explanation:"A proper dependency file enables reproducible builds and version management.",impact:"New developers cannot install dependencies. Build is not reproducible.",effort:"Low",recommendations:["Add package.json for Node.js projects","Use appropriate config for your language (requirements.txt, Cargo.toml, etc.)","Commit lock files for reproducibility"]}},Hi={id:"RULE_013",name:"High Average File Size",category:"COMPLEXITY",description:"Average file size exceeds threshold",severity:"MEDIUM",weight:8,evaluator:t=>{let e=t.metadata.total_lines/t.metadata.total_files;return e>400?{rule_id:"RULE_013",title:"High Average File Size",message:`Average file size is ${e.toFixed(0)} lines (threshold: 400)`,severity:"MEDIUM",category:"COMPLEXITY",explanation:"When average file size is high, the codebase is likely to have structural issues.",impact:"Overall maintainability suffers. Code reviews take longer.",effort:"Medium",recommendations:["Review largest files for decomposition","Establish file size guidelines for team","Use lint rules to enforce limits"]}:null}},zi={id:"RULE_014",name:"Multiple Lock Files",category:"DEPENDENCY",description:"Multiple dependency lock files detected",severity:"LOW",weight:3,evaluator:t=>{let e=t.files.filter(n=>{let r=n.path.split("/").pop()?.toLowerCase()||"";return r==="package-lock.json"||r==="yarn.lock"||r==="pnpm-lock.yaml"||r==="bun.lockb"});return e.length>1?{rule_id:"RULE_014",title:"Multiple Lock Files Detected",message:`Found ${e.length} lock files (expected: 1)`,severity:"LOW",category:"DEPENDENCY",explanation:"Multiple lock files indicate different package managers being used, causing inconsistency.",impact:"Dependency versions may differ between environments. Confusion for developers.",effort:"Low",recommendations:["Choose one package manager (npm, yarn, or pnpm)","Delete lock files from other managers","Document chosen package manager in README"]}:null}},Wi={id:"RULE_015",name:"Hardcoded Secrets Detection",category:"SECURITY",description:"Detects hardcoded secrets in source files",severity:"CRITICAL",weight:25,evaluator:t=>{let e=["ts","tsx","js","jsx","json","yaml","yml","env","config","conf"],n=[{name:"Stripe API Key",pattern:/sk_(live|test)_[0-9a-zA-Z]{20,}/g,severity:"CRITICAL"},{name:"JWT Secret",pattern:/JWT_SECRET\s*=\s*["']([^"']{8,})["']/g,severity:"CRITICAL"},{name:"Database Password",pattern:/(DB_PASSWORD|DATABASE_URL)\s*=\s*["']([^"']+)["']/g,severity:"CRITICAL"},{name:"Private Key",pattern:/-----BEGIN (RSA )?PRIVATE KEY-----/g,severity:"CRITICAL"},{name:"Generic Secret Assignment",pattern:/(password|secret|token|api_key|apikey)\s*[:=]\s*["']([^"']{8,})["']/gi,severity:"HIGH"}],r=[];for(let s of t.files){if(s.is_binary||s.size_bytes>1024*1024)continue;let o=s.extension.toLowerCase();if(e.includes(o))try{let a=jr("fs"),i=jr("path"),l=t.project_root?i.join(t.project_root,s.path):s.path,c=a.readFileSync(l,"utf-8");for(let f of n){let _=c.matchAll(f.pattern);for(let b of _){let x=b[0].replace(/["']([^"']{4,})["']/g,'"****"');r.push({file:s.path,type:f.name,severity:f.severity,masked:x});}}}catch{continue}}if(r.length>0){let s=r.filter(i=>i.severity==="CRITICAL");r.filter(i=>i.severity==="HIGH");let a=r.slice(0,10).map(i=>`${i.file}: ${i.type} (${i.masked})`);return {rule_id:"RULE_015",title:"Hardcoded Secrets Detected",message:`Found ${r.length} hardcoded secret(s) in source code`,severity:s.length>0?"CRITICAL":"HIGH",category:"SECURITY",evidence:a,explanation:"Hardcoded secrets in source code are a critical security risk. They can be extracted from version history and used to compromise your systems.",impact:"Attackers can access your databases, APIs, and services. Credentials remain exposed forever in git history.",effort:"Medium",recommendations:["Move all secrets to environment variables","Use secret management services (AWS Secrets Manager, Doppler, etc.)","Rotate all exposed credentials immediately","Add pre-commit hooks to prevent future commits","Remove secrets from git history using git-filter-repo"]}}return null}},Gi=[Ni,Oi,Di,Pi,ji,Li,Ui,$i,Mi,Fi,Vi,Bi,Hi,zi,Wi],Vr=class{options;constructor(t){this.options={maxFiles:100,includeRawContent:false,...t};}async scan(t){let e=await this.discoverFiles(),n=await this.extractDependencies(),r=this.options.framework||this.detectFramework(),s=this.detectLanguage(e),a=e.slice(0,this.options.maxFiles).map(l=>{let c=this.extractASTTokens(l.content,l.extension);return {path_hash:this.hash(l.path),content_hash:this.hash(l.content),extension:l.extension,size_bytes:l.size,ast_tokens:c.slice(0,500),raw_content:this.options.includeRawContent?l.content:void 0}}),i={framework:r,language:s,total_files:e.length,total_dependencies:n.length,file_types:this.calculateFileTypes(e)};return {version:ce,project_id:pe__default.randomUUID(),session_id:t,generated_at:new Date().toISOString(),metadata:i,files:a,dependencies:n}}async discoverFiles(){let t=[],e=await glob(["**/*.{ts,tsx,js,jsx,json}"],{cwd:this.options.projectPath,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/.veestack/**"],absolute:false});for(let n of e){let r=join(this.options.projectPath,n);try{let s=statSync(r);if(!s.isFile()||s.size>1024*1024)continue;let o=readFileSync(r,"utf-8"),a=n.split(".").pop()||"";t.push({path:n,content:o,extension:a,size:s.size});}catch{continue}}return t}extractASTTokens(t,e){let n=[],r=t.split(`
6
+ `),s=new Set(["function","const","let","var","class","import","export","return","if","else","for","while","try","catch","eval","dangerouslySetInnerHTML","document","window"]),o=new Set(["eval","setTimeout","setInterval","Function","exec","innerHTML","document.write","dangerouslySetInnerHTML"]);return r.forEach((a,i)=>{let l=i+1;if(s.forEach(_=>{let b=new RegExp(`\\b${_}\\b`,"g"),x;for(;(x=b.exec(a))!==null;)n.push({type:"keyword",value:_,line:l,column:x.index+1});}),o.forEach(_=>{let b=new RegExp(`${_.replace(".","\\.")}\\s*\\(`,"g"),x;for(;(x=b.exec(a))!==null;)n.push({type:"call_expression",value:_,line:l,column:x.index+1});}),e==="tsx"||e==="jsx"){let _=/<[A-Z][a-zA-Z0-9]*/g,b;for(;(b=_.exec(a))!==null;)n.push({type:"jsx_element",value:b[0].substring(1),line:l,column:b.index+1});a.includes("dangerouslySetInnerHTML")&&n.push({type:"property_access",value:"dangerouslySetInnerHTML",line:l,column:a.indexOf("dangerouslySetInnerHTML")+1});}let c=/['"]([^'"]*)['"]/g,f;for(;(f=c.exec(a))!==null;){let _=f[1];(_.includes(".env")||_.includes(".pem")||_.includes(".key"))&&n.push({type:"string",value:_,line:l,column:f.index+1});}}),n}async extractDependencies(){let t=[];try{let e=join(this.options.projectPath,"package.json");if(!existsSync(e))return t;let n=JSON.parse(readFileSync(e,"utf-8")),r=(s,o)=>{for(let[a,i]of Object.entries(s)){let l=i.match(/^(\d+)\.(\d+)/),c=l?parseInt(l[1]):0;t.push({name_hash:this.hash(a),version:i.replace(/[^\d.]/g,""),major_version:c,category:o});}};n.dependencies&&r(n.dependencies,"production"),n.devDependencies&&r(n.devDependencies,"development"),n.peerDependencies&&r(n.peerDependencies,"peer");}catch{}return t}detectFramework(){let t=this.options.projectPath;if(existsSync(join(t,"next.config.js"))||existsSync(join(t,"next.config.mjs"))||existsSync(join(t,"next.config.ts")))return "nextjs";try{let e=JSON.parse(readFileSync(join(t,"package.json"),"utf-8"));if(e.dependencies?.next)return "nextjs";if(e.dependencies?.react)return "react";if(e.dependencies?.vue)return "vue";if(e.dependencies?.["@angular/core"])return "angular";if(e.dependencies?.svelte)return "svelte"}catch{}return "node"}detectLanguage(t){let e=0,n=0;return t.forEach(r=>{r.extension==="ts"||r.extension==="tsx"?e++:(r.extension==="js"||r.extension==="jsx")&&n++;}),e>0&&n>0?"mixed":e>0?"typescript":"javascript"}calculateFileTypes(t){let e={};return t.forEach(n=>{let r=n.extension||"unknown";e[r]=(e[r]||0)+1;}),e}hash(t){return pe__default.createHash("sha256").update(t).digest("hex")}};});var cs=[/^--token[=\s]/i,/^-t[=\s]/i,/^--api-key[=\s]/i,/^--apikey[=\s]/i,/^--key[=\s]/i,/^--auth[=\s]/i,/^--bearer[=\s]/i,/token[=:]\s*[a-zA-Z0-9_-]{10,}/i,/api[_-]?key[=:]\s*[a-zA-Z0-9_-]{10,}/i],qe=/vs_[a-zA-Z0-9_-]{20,}/i;function Wn(){let t=process.argv.slice(2);for(let e of t){for(let n of cs)n.test(e)&&(console.error(h.red(`
7
7
  \u274C Security Error: Token detected in command line arguments`)),console.error(h.yellow(`
8
8
  Passing tokens via CLI arguments is not allowed.`)),console.error(h.yellow("This prevents tokens from being saved in shell history (~/.bash_history, ~/.zsh_history)")),console.error(h.gray(`
9
9
  Instead, use:`)),console.error(h.cyan(" veestack login")),console.error(h.gray(`
@@ -23,25 +23,25 @@ Run with DEBUG=veestack for full stack trace (sanitized)`);}process.exit(1);}),p
23
23
  `));for(let n of e)console.log(h.yellow(n));console.log(h.gray(`
24
24
  To install the official CLI:`)),console.log(h.cyan(" npm install -g veestack-tools")),console.log(h.red("\u2550".repeat(60)+`
25
25
  `)),process.exit(1);}process.env.VEESTACK_DEBUG==="true"&&console.log(h.gray(`\u2713 Official package verified: ${Xe.join(" or ")}`));}function Lt(){let t=Jn(),e=Xe.includes(t);return {packageName:t,isOfficial:e,homepage:"https://veestack.tools",repository:"https://github.com/Mohmed-ElZehiry/VeeStack"}}K();var Fo=[".env",".env.local",".env.development",".env.production",".env.test",".env.example",".envrc",".env.*","id_rsa","id_rsa.pub","id_dsa","id_dsa.pub","id_ecdsa","id_ecdsa.pub","id_ed25519","id_ed25519.pub","*.pem","*.key","*.p12","*.pfx","*.crt","*.cer","*.der","credentials",".aws/credentials",".aws/config",".docker/config.json","kubeconfig","*.kubeconfig",".npmrc",".yarnrc",".pnpmrc",".git-credentials","*.sqlite","*.sqlite3","*.db","secrets/","secret/",".secrets/","config.json","settings.json","local.settings.json"],Vo=["veestack.config.json","package.json","tsconfig.json","jsconfig.json",".eslintrc.json",".prettierrc.json","README.md"],Bo=[{name:"AWS Access Key ID",pattern:/AKIA[0-9A-Z]{16}/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/['"\s][A-Za-z0-9/+=]{40}['"\s]/g,severity:"critical",description:"Potential AWS Secret Key detected"},{name:"Private Key",pattern:/-----BEGIN (RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g,severity:"critical",description:"Private key detected"},{name:"JWT Token",pattern:/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Bearer Token",pattern:/Bearer\s+[a-zA-Z0-9_-]{20,}/gi,severity:"high",description:"Bearer token detected"},{name:"API Key",pattern:/(?:api[_-]?key|apikey|api_token|apiToken)['"\s]*[:=]\s*['"][a-zA-Z0-9_-]{16,}['"]/gi,severity:"high",description:"API key detected"},{name:"Password in URL",pattern:/[a-zA-Z]+:\/\/[^\s:@]+:[^\s:@]+@[^\s]+/g,severity:"high",description:"Password in URL detected"},{name:"Password Assignment",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"][^'"]{8,}['"]/gi,severity:"medium",description:"Password assignment detected"},{name:"GitHub Token",pattern:/gh[pousr]_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}(-[a-zA-Z0-9]{24})?/g,severity:"critical",description:"Slack token detected"},{name:"Generic Secret",pattern:/(?:secret|token|key)\s*[=:]\s*['"][a-zA-Z0-9_-]{20,}['"]/gi,severity:"medium",description:"Potential secret detected"},{name:"Connection String",pattern:/(?:mongodb|postgres|mysql|redis|amqp):\/\/[^\s]+/gi,severity:"high",description:"Database connection string detected"},{name:"VeeStack Token",pattern:/vs_[a-zA-Z0-9_-]{20,}/g,severity:"critical",description:"VeeStack token detected"}];function gr(t){let e=t.replace(/\\/g,"/").toLowerCase(),n=Je.basename(e);for(let r of Vo)if(n===r.toLowerCase())return false;for(let r of Fo){if(n===r.toLowerCase())return true;if(r.includes("*")){let s=r.toLowerCase().replace(/\./g,"\\.").replace(/\*/g,".*"),o=new RegExp(s);if(o.test(n)||o.test(e))return true}if(e.includes(r.toLowerCase().replace("*","")))return true}return false}function Ho(t,e){let n=[],r=e.split(`
26
- `);for(let s of Bo){s.pattern.lastIndex=0;for(let o=0;o<r.length;o++){let a=r[o],i;for(;(i=s.pattern.exec(a))!==null;)n.push({filePath:t,type:"secret_content",secretName:s.name,severity:s.severity,description:s.description,lineNumber:o+1,match:i[0].substring(0,20)+"..."});s.pattern.lastIndex=0;}}return n}async function zo(t){let e=[];if(gr(t))return e.push({filePath:t,type:"sensitive_file",secretName:"Sensitive File",severity:"critical",description:`Sensitive file type detected: ${Je.basename(t)}`}),e;try{if(re.statSync(t).size>1024*1024)return e;let r=re.readFileSync(t,"utf-8"),s=Ho(t,r);e.push(...s);}catch{}return e}async function mr(t,e){let n=[];for(let i of e){let l=Je.join(t,i),c=await zo(l);for(let f of c)f.filePath=i,n.push(f);}let r=n.filter(i=>i.severity==="critical").length,s=n.filter(i=>i.severity==="high").length,o=n.filter(i=>i.severity==="medium").length,a=n.filter(i=>i.severity==="low").length;return {totalFiles:e.length,secretsFound:n.length,criticalCount:r,highCount:s,mediumCount:o,lowCount:a,results:n}}function hr(t){let e=[],n=[];for(let r of t)gr(r)?n.push(r):e.push(r);return {safe:e,blocked:n}}K();K();var Wo={TOKEN_BINDING_SALT:hn};function yr(t,e){let n=`${t}:${e}:${Wo.TOKEN_BINDING_SALT}`;return de.createHash("sha256").update(n).digest("hex")}function vr(t,e,n,r,s="cli"){let o=new Date().toISOString(),a=Jo(),i=Go(t,e,n,o,a),l=Yo(o,s,i),c=Zo(r,o,s,l);return {signature:c,timestamp:o,nonce:a,headers:{"X-Signature":c,"X-Timestamp":o,"X-Nonce":a,"X-Signed-Headers":"host;x-timestamp;x-nonce"}}}function Go(t,e,n,r,s){let o=de.createHash("sha256").update(n).digest("hex");return [t.toUpperCase(),e,"",`host:api.veestack.tools
26
+ `);for(let s of Bo){s.pattern.lastIndex=0;for(let o=0;o<r.length;o++){let a=r[o],i;for(;(i=s.pattern.exec(a))!==null;)n.push({filePath:t,type:"secret_content",secretName:s.name,severity:s.severity,description:s.description,lineNumber:o+1,match:i[0].substring(0,20)+"..."});s.pattern.lastIndex=0;}}return n}async function zo(t){let e=[];if(gr(t))return e.push({filePath:t,type:"sensitive_file",secretName:"Sensitive File",severity:"critical",description:`Sensitive file type detected: ${Je.basename(t)}`}),e;try{if(re.statSync(t).size>1024*1024)return e;let r=re.readFileSync(t,"utf-8"),s=Ho(t,r);e.push(...s);}catch{}return e}async function mr(t,e){let n=[];for(let i of e){let l=Je.join(t,i),c=await zo(l);for(let f of c)f.filePath=i,n.push(f);}let r=n.filter(i=>i.severity==="critical").length,s=n.filter(i=>i.severity==="high").length,o=n.filter(i=>i.severity==="medium").length,a=n.filter(i=>i.severity==="low").length;return {totalFiles:e.length,secretsFound:n.length,criticalCount:r,highCount:s,mediumCount:o,lowCount:a,results:n}}function hr(t){let e=[],n=[];for(let r of t)gr(r)?n.push(r):e.push(r);return {safe:e,blocked:n}}K();K();var Wo={TOKEN_BINDING_SALT:hn};function yr(t,e){let n=`${t}:${e}:${Wo.TOKEN_BINDING_SALT}`;return pe.createHash("sha256").update(n).digest("hex")}function vr(t,e,n,r,s="cli"){let o=new Date().toISOString(),a=Jo(),i=Go(t,e,n,o,a),l=Yo(o,s,i),c=Zo(r,o,s,l);return {signature:c,timestamp:o,nonce:a,headers:{"X-Signature":c,"X-Timestamp":o,"X-Nonce":a,"X-Signed-Headers":"host;x-timestamp;x-nonce"}}}function Go(t,e,n,r,s){let o=pe.createHash("sha256").update(n).digest("hex");return [t.toUpperCase(),e,"",`host:api.veestack.tools
27
27
  `,`x-timestamp:${r}
28
28
  `,`x-nonce:${s}
29
29
  `,"host;x-timestamp;x-nonce",o].join(`
30
- `)}function Yo(t,e,n){let r=t.substring(0,10).replace(/-/g,""),s=de.createHash("sha256").update(n).digest("hex");return ["VEESTACK-HMAC-SHA256",t,`${r}/veestack/${e}/veestack_request`,s].join(`
31
- `)}function Zo(t,e,n,r){let s=e.substring(0,10).replace(/-/g,""),o=Et("VEESTACK"+t,s),a=Et(o,"veestack"),i=Et(a,n),l=Et(i,"veestack_request");return Et(l,r,"hex")}function Et(t,e,n){return de.createHmac("sha256",t).update(e).digest(n||"hex")}function Jo(){return de.randomBytes(16).toString("hex")}var Yt=null;async function Jt(){if(Yt)return Yt;try{return Yt=await import('keytar'),Yt}catch{return null}}var Tt=Je.join(ct.homedir(),".veestack"),he=Je.join(Tt,"tokens.enc"),_r=Je.join(Tt,"salt"),kr=Je.join(Tt,".key"),Kt="VeeStack CLI",qt="auth_tokens",Ko=1e5,qo=32,Xo=16;function Zt(){return process.env.DEBUG?.includes("veestack")||process.env.DEBUG?.includes("*")||process.env.NODE_ENV==="development"||process.env.VEESTACK_DEBUG==="true"}async function Qo(){try{let e=await L.readFile(_r).catch(()=>null);if(e)return e}catch{}let t=de.randomBytes(32);return await L.mkdir(Tt,{recursive:true,mode:448}),await L.writeFile(_r,t,{mode:384}),t}async function Er(){try{let r=await L.readFile(kr,"utf-8").catch(()=>null);if(r){let s=Buffer.from(r,"hex");return await L.unlink(kr).catch(()=>{}),s}}catch{}let t=`${ct.userInfo().username}@${ct.hostname()}`,e=await Qo();return de.pbkdf2Sync(t,e,Ko,qo,"sha256")}function St(t){Buffer.isBuffer(t)&&t.fill(0);}async function xt(t){let e=await Jt();if(e)try{let c=JSON.stringify(t);await e.setPassword(Kt,qt,c),Zt()&&console.log(" Tokens saved to OS Keychain");return}catch(c){Zt()&&console.log(" Keychain failed, falling back to encrypted file:",c);}let n=await Er(),r=de.randomBytes(Xo),s=de.createCipheriv("aes-256-gcm",n,r),o=JSON.stringify(t),a=Buffer.concat([s.update(o,"utf8"),s.final()]),i=s.getAuthTag(),l={iv:r.toString("hex"),data:a.toString("hex"),authTag:i.toString("hex"),timestamp:Date.now(),version:2};await L.mkdir(Tt,{recursive:true,mode:448}),await L.writeFile(he,JSON.stringify(l),{mode:384}),St(n),Zt()&&console.log(" Tokens saved to encrypted file (AES-256-GCM)");}async function Sr(){let t=await Jt();if(t)try{let e=await t.getPassword(Kt,qt);if(e)return JSON.parse(e)}catch(e){Zt()&&console.log("\u26A0\uFE0F Keychain read failed, trying encrypted file:",e);}try{let e=await L.readFile(he,"utf-8"),n=JSON.parse(e);if(n.version===1)return await ei(n);let r=await Er(),s=null;try{let o=Buffer.from(n.iv,"hex"),a=Buffer.from(n.data,"hex"),i=Buffer.from(n.authTag,"hex"),l=de.createDecipheriv("aes-256-gcm",r,o);l.setAuthTag(i),s=Buffer.concat([l.update(a),l.final()]);let c=JSON.parse(s.toString("utf8"));return St(s),St(r),c}catch(o){throw s&&St(s),St(r),o}}catch{return null}}async function ei(t){try{return console.log("\u{1F510} Migrating from legacy encryption format..."),await L.unlink(he).catch(()=>{}),null}catch{return null}}async function Xt(){try{return await L.access(he),!0}catch{return false}}async function ze(){try{let t=await L.stat(he).catch(()=>null);if(!t)return;let e=t.size,n=3;for(let s=0;s<n;s++){let o=de.randomBytes(e);await L.writeFile(he,o);}await L.unlink(he);let r=await Jt();r&&await r.deletePassword(Kt,qt).catch(()=>{});}catch{}}async function wr(){let t=await Jt(),e=!!t,n=false;if(t)try{n=!!await t.getPassword(Kt,qt);}catch{}let r=false,s,o,a=0;try{let i=await L.stat(he);r=!0,s=i.mode.toString(8),o=i.size;let l=await L.readFile(he,"utf-8");a=JSON.parse(l).version||1;}catch{}return {keychainAvailable:e,keychainHasTokens:n,fileExists:r,filePermissions:s,fileSize:o,encryptionVersion:a}}var ti=[{name:"bearer_token",regex:/Bearer\s+[a-zA-Z0-9_-]{20,}/gi,replacement:"Bearer [REDACTED]"},{name:"api_key",regex:/api[_-]?key['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"api_key: [REDACTED]"},{name:"access_token",regex:/access[_-]?token['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"access_token: [REDACTED]"},{name:"refresh_token",regex:/refresh[_-]?token['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"refresh_token: [REDACTED]"},{name:"auth_token",regex:/auth[_-]?token['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"auth_token: [REDACTED]"},{name:"password",regex:/password['"\s]*[:=]\s*['"]?([^'"\s]{8,})/gi,replacement:"password: [REDACTED]"},{name:"secret",regex:/secret['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"secret: [REDACTED]"},{name:"private_key",regex:/private[_-]?key['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"private_key: [REDACTED]"},{name:"jwt_token",regex:/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,replacement:"[REDACTED_JWT]"},{name:"supabase_key",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g,replacement:"[REDACTED_SUPABASE_KEY]"}];function We(t){if(!t||typeof t!="string")return t;let e=t;for(let n of ti)e=e.replace(n.regex,n.replacement);return e}function Rn(t){return t instanceof Error?We(t.message).slice(0,500):typeof t=="string"?We(t).slice(0,500):We(String(t)).slice(0,500)}function Qt(t){if(!t||typeof t!="object")return t;let e=["token","accessToken","refreshToken","apiKey","api_key","secret","password","privateKey","private_key","authToken","auth_token","jwt","credential","credentials"];if(Array.isArray(t))return t.map(r=>Qt(r));let n={};for(let[r,s]of Object.entries(t)){let o=r.toLowerCase();e.some(a=>o.includes(a))?n[r]="[REDACTED]":typeof s=="object"&&s!==null?n[r]=Qt(s):typeof s=="string"?n[r]=We(s):n[r]=s;}return n}function At(t,e,...n){let r=We(e),s=n.map(o=>typeof o=="string"?We(o):typeof o=="object"&&o!==null?Qt(o):o);console[t](r,...s);}var ye={log:(t,...e)=>At("log",t,...e),error:(t,...e)=>At("error",t,...e),warn:(t,...e)=>At("warn",t,...e),info:(t,...e)=>At("info",t,...e),debug:(t,...e)=>At("debug",t,...e)};var bn=Je.join(ct.homedir(),".veestack");Je.join(bn,"config.json");var en=Je.join(bn,"config.json"),ni=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function si(){try{if(!re.existsSync(en))return;let t=re.readFileSync(en,"utf-8"),e=JSON.parse(t);if(await Xt()){try{re.unlinkSync(en);}catch{}return}let n={token:e.token,refreshToken:e.refreshToken,tokenType:e.tokenType,tokenExpiresAt:e.tokenExpiresAt,device:e.device,user:e.user,subscription:e.subscription,lastLoginAt:e.lastLoginAt,apiKey:e.apiKey};await xt(n);try{re.unlinkSync(en);}catch{}ye.info("\u{1F510} Authentication migrated to encrypted storage");}catch{}}async function q(){await si();let t=await Sr();return t?{token:t.token,tokenType:t.tokenType,refreshToken:t.refreshToken,tokenExpiresAt:t.tokenExpiresAt,device:t.device,user:t.user,subscription:t.subscription,lastLoginAt:t.lastLoginAt,apiKey:t.apiKey}:null}async function Ye(){let t=await q();if(!t)return false;let e=t.token!==void 0&&t.token.length>0,n=t.apiKey!==void 0&&t.apiKey.length>0;return e||n}async function oi(){let t=await q();return t&&(t.token||t.apiKey)||null}async function ii(){let t=await q();return {id:t?.device?.id,fingerprint:t?.device?.fingerprint}}async function nn(t="GET",e="",n="",r=["project:read"]){let s=await oi();if(!s)return {};let o=await q(),a=await ii();if(!a.id||!a.fingerprint||!o?.refreshToken)return {};let i=yr(o.refreshToken,a.fingerprint),l=vr(t,e,n,o.refreshToken,"cli");return {Authorization:`Bearer ${s}`,"Content-Type":"application/json","X-Device-ID":a.id,"X-CLI-Version":B,"X-Device-Fingerprint":a.fingerprint,"X-Token-Binding":i,"X-Signature":l.signature,"X-Timestamp":l.timestamp,"X-Nonce":l.nonce,"X-Scope":r.join(","),"X-Security-Version":B}}function Cn(t){if(!t.tokenExpiresAt)return true;let e=new Date(t.tokenExpiresAt),n=300*1e3;return Date.now()>=e.getTime()-n}async function ai(t){if(!t.refreshToken)return null;try{let e=await fetch(`${ni}/api/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t.refreshToken,device_id:t.device?.id,device_fingerprint:t.device?.fingerprint})});if(e.status===401){let s=await e.json().catch(()=>({}));throw s.code==="device_mismatch"&&(await ze(),console.log(h.red(`
30
+ `)}function Yo(t,e,n){let r=t.substring(0,10).replace(/-/g,""),s=pe.createHash("sha256").update(n).digest("hex");return ["VEESTACK-HMAC-SHA256",t,`${r}/veestack/${e}/veestack_request`,s].join(`
31
+ `)}function Zo(t,e,n,r){let s=e.substring(0,10).replace(/-/g,""),o=Et("VEESTACK"+t,s),a=Et(o,"veestack"),i=Et(a,n),l=Et(i,"veestack_request");return Et(l,r,"hex")}function Et(t,e,n){return pe.createHmac("sha256",t).update(e).digest(n||"hex")}function Jo(){return pe.randomBytes(16).toString("hex")}var Yt=null;async function Jt(){if(Yt)return Yt;try{return Yt=await import('keytar'),Yt}catch{return null}}var Tt=Je.join(ct.homedir(),".veestack"),ye=Je.join(Tt,"tokens.enc"),_r=Je.join(Tt,"salt"),kr=Je.join(Tt,".key"),Kt="VeeStack CLI",qt="auth_tokens",Ko=1e5,qo=32,Xo=16;function Zt(){return process.env.DEBUG?.includes("veestack")||process.env.DEBUG?.includes("*")||process.env.NODE_ENV==="development"||process.env.VEESTACK_DEBUG==="true"}async function Qo(){try{let e=await L.readFile(_r).catch(()=>null);if(e)return e}catch{}let t=pe.randomBytes(32);return await L.mkdir(Tt,{recursive:true,mode:448}),await L.writeFile(_r,t,{mode:384}),t}async function Er(){try{let r=await L.readFile(kr,"utf-8").catch(()=>null);if(r){let s=Buffer.from(r,"hex");return await L.unlink(kr).catch(()=>{}),s}}catch{}let t=`${ct.userInfo().username}@${ct.hostname()}`,e=await Qo();return pe.pbkdf2Sync(t,e,Ko,qo,"sha256")}function St(t){Buffer.isBuffer(t)&&t.fill(0);}async function xt(t){let e=await Jt();if(e)try{let c=JSON.stringify(t);await e.setPassword(Kt,qt,c),Zt()&&console.log(" Tokens saved to OS Keychain");return}catch(c){Zt()&&console.log(" Keychain failed, falling back to encrypted file:",c);}let n=await Er(),r=pe.randomBytes(Xo),s=pe.createCipheriv("aes-256-gcm",n,r),o=JSON.stringify(t),a=Buffer.concat([s.update(o,"utf8"),s.final()]),i=s.getAuthTag(),l={iv:r.toString("hex"),data:a.toString("hex"),authTag:i.toString("hex"),timestamp:Date.now(),version:2};await L.mkdir(Tt,{recursive:true,mode:448}),await L.writeFile(ye,JSON.stringify(l),{mode:384}),St(n),Zt()&&console.log(" Tokens saved to encrypted file (AES-256-GCM)");}async function Sr(){let t=await Jt();if(t)try{let e=await t.getPassword(Kt,qt);if(e)return JSON.parse(e)}catch(e){Zt()&&console.log("\u26A0\uFE0F Keychain read failed, trying encrypted file:",e);}try{let e=await L.readFile(ye,"utf-8"),n=JSON.parse(e);if(n.version===1)return await ei(n);let r=await Er(),s=null;try{let o=Buffer.from(n.iv,"hex"),a=Buffer.from(n.data,"hex"),i=Buffer.from(n.authTag,"hex"),l=pe.createDecipheriv("aes-256-gcm",r,o);l.setAuthTag(i),s=Buffer.concat([l.update(a),l.final()]);let c=JSON.parse(s.toString("utf8"));return St(s),St(r),c}catch(o){throw s&&St(s),St(r),o}}catch{return null}}async function ei(t){try{return console.log("\u{1F510} Migrating from legacy encryption format..."),await L.unlink(ye).catch(()=>{}),null}catch{return null}}async function Xt(){try{return await L.access(ye),!0}catch{return false}}async function ze(){try{let t=await L.stat(ye).catch(()=>null);if(!t)return;let e=t.size,n=3;for(let s=0;s<n;s++){let o=pe.randomBytes(e);await L.writeFile(ye,o);}await L.unlink(ye);let r=await Jt();r&&await r.deletePassword(Kt,qt).catch(()=>{});}catch{}}async function wr(){let t=await Jt(),e=!!t,n=false;if(t)try{n=!!await t.getPassword(Kt,qt);}catch{}let r=false,s,o,a=0;try{let i=await L.stat(ye);r=!0,s=i.mode.toString(8),o=i.size;let l=await L.readFile(ye,"utf-8");a=JSON.parse(l).version||1;}catch{}return {keychainAvailable:e,keychainHasTokens:n,fileExists:r,filePermissions:s,fileSize:o,encryptionVersion:a}}var ti=[{name:"bearer_token",regex:/Bearer\s+[a-zA-Z0-9_-]{20,}/gi,replacement:"Bearer [REDACTED]"},{name:"api_key",regex:/api[_-]?key['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"api_key: [REDACTED]"},{name:"access_token",regex:/access[_-]?token['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"access_token: [REDACTED]"},{name:"refresh_token",regex:/refresh[_-]?token['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"refresh_token: [REDACTED]"},{name:"auth_token",regex:/auth[_-]?token['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"auth_token: [REDACTED]"},{name:"password",regex:/password['"\s]*[:=]\s*['"]?([^'"\s]{8,})/gi,replacement:"password: [REDACTED]"},{name:"secret",regex:/secret['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"secret: [REDACTED]"},{name:"private_key",regex:/private[_-]?key['"\s]*[:=]\s*['"]?([a-zA-Z0-9_-]{16,})/gi,replacement:"private_key: [REDACTED]"},{name:"jwt_token",regex:/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,replacement:"[REDACTED_JWT]"},{name:"supabase_key",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g,replacement:"[REDACTED_SUPABASE_KEY]"}];function We(t){if(!t||typeof t!="string")return t;let e=t;for(let n of ti)e=e.replace(n.regex,n.replacement);return e}function Rn(t){return t instanceof Error?We(t.message).slice(0,500):typeof t=="string"?We(t).slice(0,500):We(String(t)).slice(0,500)}function Qt(t){if(!t||typeof t!="object")return t;let e=["token","accessToken","refreshToken","apiKey","api_key","secret","password","privateKey","private_key","authToken","auth_token","jwt","credential","credentials"];if(Array.isArray(t))return t.map(r=>Qt(r));let n={};for(let[r,s]of Object.entries(t)){let o=r.toLowerCase();e.some(a=>o.includes(a))?n[r]="[REDACTED]":typeof s=="object"&&s!==null?n[r]=Qt(s):typeof s=="string"?n[r]=We(s):n[r]=s;}return n}function At(t,e,...n){let r=We(e),s=n.map(o=>typeof o=="string"?We(o):typeof o=="object"&&o!==null?Qt(o):o);console[t](r,...s);}var ve={log:(t,...e)=>At("log",t,...e),error:(t,...e)=>At("error",t,...e),warn:(t,...e)=>At("warn",t,...e),info:(t,...e)=>At("info",t,...e),debug:(t,...e)=>At("debug",t,...e)};var bn=Je.join(ct.homedir(),".veestack");Je.join(bn,"config.json");var en=Je.join(bn,"config.json"),ni=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function si(){try{if(!re.existsSync(en))return;let t=re.readFileSync(en,"utf-8"),e=JSON.parse(t);if(await Xt()){try{re.unlinkSync(en);}catch{}return}let n={token:e.token,refreshToken:e.refreshToken,tokenType:e.tokenType,tokenExpiresAt:e.tokenExpiresAt,device:e.device,user:e.user,subscription:e.subscription,lastLoginAt:e.lastLoginAt,apiKey:e.apiKey};await xt(n);try{re.unlinkSync(en);}catch{}ve.info("\u{1F510} Authentication migrated to encrypted storage");}catch{}}async function q(){await si();let t=await Sr();return t?{token:t.token,tokenType:t.tokenType,refreshToken:t.refreshToken,tokenExpiresAt:t.tokenExpiresAt,device:t.device,user:t.user,subscription:t.subscription,lastLoginAt:t.lastLoginAt,apiKey:t.apiKey}:null}async function Ye(){let t=await q();if(!t)return false;let e=t.token!==void 0&&t.token.length>0,n=t.apiKey!==void 0&&t.apiKey.length>0;return e||n}async function oi(){let t=await q();return t&&(t.token||t.apiKey)||null}async function ii(){let t=await q();return {id:t?.device?.id,fingerprint:t?.device?.fingerprint}}async function nn(t="GET",e="",n="",r=["project:read"]){let s=await oi();if(!s)return {};let o=await q(),a=await ii();if(!a.id||!a.fingerprint||!o?.refreshToken)return {};let i=yr(o.refreshToken,a.fingerprint),l=vr(t,e,n,o.refreshToken,"cli");return {Authorization:`Bearer ${s}`,"Content-Type":"application/json","X-Device-ID":a.id,"X-CLI-Version":B,"X-Device-Fingerprint":a.fingerprint,"X-Token-Binding":i,"X-Signature":l.signature,"X-Timestamp":l.timestamp,"X-Nonce":l.nonce,"X-Scope":r.join(","),"X-Security-Version":B}}function Cn(t){if(!t.tokenExpiresAt)return true;let e=new Date(t.tokenExpiresAt),n=300*1e3;return Date.now()>=e.getTime()-n}async function ai(t){if(!t.refreshToken)return null;try{let e=await fetch(`${ni}/api/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t.refreshToken,device_id:t.device?.id,device_fingerprint:t.device?.fingerprint})});if(e.status===401){let s=await e.json().catch(()=>({}));throw s.code==="device_mismatch"&&(await ze(),console.log(h.red(`
32
32
  \u274C Security Alert: Device mismatch`)),console.log(h.yellow(`
33
33
  Your token was used from a different device.`)),console.log(h.gray("This could indicate a token theft attempt.")),console.log(h.gray("Please login again:")),console.log(h.cyan(" veestack login")),process.exit(1)),s.code==="device_revoked"&&(await ze(),console.log(h.red(`
34
34
  \u274C Device authorization revoked`)),console.log(h.yellow(`
35
35
  Your device was removed from authorized devices.`)),console.log(h.gray("Please login again:")),console.log(h.cyan(" veestack login")),process.exit(1)),(s.code==="token_invalid"||s.code==="session_expired")&&(await ze(),console.log(h.red(`
36
36
  \u274C Session expired`)),console.log(h.yellow(`
37
- Your session has expired or your password was changed.`)),console.log(h.gray("Please login again:")),console.log(h.cyan(" veestack login")),process.exit(1)),new Error("Token refresh failed: Unauthorized")}if(!e.ok)throw new Error("Token refresh failed");let n=await e.json(),r={...t,token:n.access_token,tokenExpiresAt:new Date(Date.now()+n.expires_in*1e3).toISOString()};return n.refresh_token&&(r.refreshToken=n.refresh_token),await xt({token:r.token,refreshToken:r.refreshToken,tokenType:r.tokenType,tokenExpiresAt:r.tokenExpiresAt,device:r.device,user:r.user,subscription:r.subscription,lastLoginAt:r.lastLoginAt,apiKey:r.apiKey}),r}catch(e){return e instanceof Error&&e.message.includes("fetch")&&(ye.warn(`
38
- \u26A0\uFE0F Network error`),ye.info("Could not connect to authentication server."),ye.info("Please check your connection and try again.")),null}}async function xe(){let t=await q();if(!t)return console.log(h.yellow(`
37
+ Your session has expired or your password was changed.`)),console.log(h.gray("Please login again:")),console.log(h.cyan(" veestack login")),process.exit(1)),new Error("Token refresh failed: Unauthorized")}if(!e.ok)throw new Error("Token refresh failed");let n=await e.json(),r={...t,token:n.access_token,tokenExpiresAt:new Date(Date.now()+n.expires_in*1e3).toISOString()};return n.refresh_token&&(r.refreshToken=n.refresh_token),await xt({token:r.token,refreshToken:r.refreshToken,tokenType:r.tokenType,tokenExpiresAt:r.tokenExpiresAt,device:r.device,user:r.user,subscription:r.subscription,lastLoginAt:r.lastLoginAt,apiKey:r.apiKey}),r}catch(e){return e instanceof Error&&e.message.includes("fetch")&&(ve.warn(`
38
+ \u26A0\uFE0F Network error`),ve.info("Could not connect to authentication server."),ve.info("Please check your connection and try again.")),null}}async function xe(){let t=await q();if(!t)return console.log(h.yellow(`
39
39
  \u26A0\uFE0F You are not logged in`)),console.log(h.gray(`
40
40
  Login to enable:`)),console.log(h.gray(" \u2022 Cloud reports")),console.log(h.gray(" \u2022 Team dashboard")),console.log(h.gray(` \u2022 Historical scans
41
41
  `)),console.log(h.gray("Run:")),console.log(h.cyan(" veestack login")),null;if(t.refreshToken&&Cn(t)){console.log(h.yellow("Token expired, refreshing..."));let e=await ai(t);return e?(console.log(h.green("\u2713 Token refreshed")),e):(await ze(),console.log(h.red(`
42
42
  \u274C Session expired`)),console.log(h.yellow("Your refresh token has expired.")),console.log(h.gray("Run: veestack login")),null)}return t}async function rn(){let t=await q();return !t||!t.subscription?"free":t.subscription.tier}async function Ar(){let t=await q();return !t||!t.subscription||t.subscription.tier==="free"?true:t.subscription.expiresAt?new Date(t.subscription.expiresAt)>new Date&&t.subscription.isActive:t.subscription.isActive}function Rr(t){if(t.user)try{let e=join(bn,"accounts"),n=(void 0)("fs");n.mkdirSync(e,{recursive:!0});let r=join(e,`${t.user.id}.json`);n.writeFileSync(r,JSON.stringify(t,null,2),{mode:384});}catch{}}K();var Ir=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function Nr(){try{let t=await fetch(`${Ir}/v1/cli/version`,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){let n=(await t.json()).version;n&&n!==V&&(console.log(h.yellow(`
43
43
  \u2728 New version available: ${h.bold(n)} (current: ${V})`)),console.log(h.gray(` Run: ${h.cyan("veestack upgrade")} to update
44
- `)));}}catch{}}async function li(){let t=process.cwd(),e=join(t,"package.json"),n=[{name:"Next.js",files:["next.config.js","next.config.ts","next.config.mjs"]},{name:"Nuxt.js",files:["nuxt.config.js","nuxt.config.ts"]},{name:"Vue CLI",files:["vue.config.js"]},{name:"Angular",files:["angular.json"]},{name:"SvelteKit",files:["svelte.config.js","svelte.config.ts"]},{name:"Vite",files:["vite.config.js","vite.config.ts"]},{name:"Remix",files:["remix.config.js"]},{name:"Gatsby",files:["gatsby-config.js","gatsby-config.ts"]},{name:"Astro",files:["astro.config.mjs","astro.config.js"]}];for(let r of n)for(let s of r.files)if(existsSync(join(t,s)))return {name:r.name,confidence:95};if(!existsSync(e)){if(existsSync(join(t,"requirements.txt"))){let r=readFileSync(join(t,"requirements.txt"),"utf-8").toLowerCase();if(r.includes("django"))return {name:"Django",confidence:85};if(r.includes("flask"))return {name:"Flask",confidence:85}}return existsSync(join(t,"Gemfile"))&&readFileSync(join(t,"Gemfile"),"utf-8").toLowerCase().includes("rails")?{name:"Ruby on Rails",confidence:85}:existsSync(join(t,"pom.xml"))&&readFileSync(join(t,"pom.xml"),"utf-8").toLowerCase().includes("spring-boot")?{name:"Spring Boot",confidence:85}:{name:"unknown",confidence:0}}try{let r=JSON.parse(readFileSync(e,"utf-8")),s={...r.dependencies,...r.devDependencies},o=[{name:"Next.js",primary:["next"],secondary:["next/core-web-vitals","@next/bundle-analyzer"],indicators:["app","pages"]},{name:"React",primary:["react","react-dom"],secondary:["@types/react","react-scripts","create-react-app"],indicators:["src/components","src/App.js","src/App.tsx"]},{name:"Vue",primary:["vue"],secondary:["vue-router","vuex","pinia","@vue/cli-service"],indicators:["src/views","src/components"]},{name:"Angular",primary:["@angular/core"],secondary:["@angular/cli","@angular/common","@angular/router"],indicators:["src/app"]},{name:"Svelte",primary:["svelte"],secondary:["svelte-check","@sveltejs/kit"],indicators:["src/routes"]},{name:"Express",primary:["express"],secondary:["cors","helmet","morgan","body-parser"],indicators:["routes","controllers"]},{name:"NestJS",primary:["@nestjs/core"],secondary:["@nestjs/common","@nestjs/platform-express"],indicators:["src/modules"]},{name:"Fastify",primary:["fastify"],secondary:["@fastify/cors","@fastify/helmet"],indicators:["routes"]}];for(let a of o){let i=0;for(let c of a.primary)if(s[c]){i+=70;break}let l=0;for(let c of a.secondary)s[c]&&l<2&&(i+=10,l++);for(let c of a.indicators)existsSync(join(t,c))&&(i+=10);if(i>=60)return a.name==="Next.js"&&s.next?{name:a.name,confidence:100}:{name:a.name,confidence:Math.min(i,95)}}return s.astro?{name:"Astro",confidence:80}:s.remix?{name:"Remix",confidence:80}:s.gatsby?{name:"Gatsby",confidence:80}:s.nuxt?{name:"Nuxt.js",confidence:80}:s["@sveltejs/kit"]?{name:"SvelteKit",confidence:85}:{name:"unknown",confidence:0}}catch{return {name:"unknown",confidence:0}}}async function ui(t,e){try{let n=await nn(),r=await fetch(`${Ir}/v1/projects`,{method:"POST",headers:n,body:JSON.stringify({name:t,framework:e,source:"cli-init"})});if(!r.ok){let s=await r.json().catch(()=>({error:"Unknown error"}));throw new Error(s.error||`HTTP ${r.status}`)}return await r.json()}catch(n){return ye.error("Failed to create project:",n instanceof Error?n.message:String(n)),null}}function Cr(t){let e={"Next.js":["**/*.{js,jsx,ts,tsx,json,mjs,cjs}"],React:["**/*.{js,jsx,ts,tsx,json}"],Vue:["**/*.{js,jsx,ts,tsx,vue,json}"],Angular:["**/*.{ts,html,json}"],Svelte:["**/*.{js,ts,svelte,json}"],Express:["**/*.{js,ts,json}"],NestJS:["**/*.{ts,json}"],unknown:["**/*.{js,ts,jsx,tsx,json,py,go,rs,rb,php,cs,cpp,c,h}"]};return e[t]||e.unknown}function di(){return ["node_modules/**/*",".git/**/*","dist/**/*","build/**/*",".next/**/*","coverage/**/*","*.test.ts","*.spec.ts","*.min.js"]}function pi(t){let e=join(process.cwd(),"veestack.config.json");writeFileSync(e,JSON.stringify(t,null,2));}function fi(){let t=join(process.cwd(),"veestack.config.json");if(existsSync(t))try{return JSON.parse(readFileSync(t,"utf-8"))}catch{return null}return null}function gi(t){let e=process.cwd(),n=[],r=["src","app","lib","components","pages","routes","controllers","models","utils"];for(let s of r){let o=join(e,s);existsSync(o)&&n.push(`${s}/**/*`);}return n}function mi(){let t=process.cwd(),e=join(t,".git");return existsSync(e)}function hi(){let t=process.cwd();return existsSync(join(t,"pnpm-lock.yaml"))?"pnpm":existsSync(join(t,"yarn.lock"))?"yarn":existsSync(join(t,"package-lock.json"))?"npm":existsSync(join(t,"bun.lockb"))?"bun":"npm"}function yi(){return `Node ${process.version}`}async function Rt(t){t?.skipAuthCheck||console.log(h.bold.cyan(`
44
+ `)));}}catch{}}async function li(){let t=process.cwd(),e=join(t,"package.json"),n=[{name:"Next.js",files:["next.config.js","next.config.ts","next.config.mjs"]},{name:"Nuxt.js",files:["nuxt.config.js","nuxt.config.ts"]},{name:"Vue CLI",files:["vue.config.js"]},{name:"Angular",files:["angular.json"]},{name:"SvelteKit",files:["svelte.config.js","svelte.config.ts"]},{name:"Vite",files:["vite.config.js","vite.config.ts"]},{name:"Remix",files:["remix.config.js"]},{name:"Gatsby",files:["gatsby-config.js","gatsby-config.ts"]},{name:"Astro",files:["astro.config.mjs","astro.config.js"]}];for(let r of n)for(let s of r.files)if(existsSync(join(t,s)))return {name:r.name,confidence:95};if(!existsSync(e)){if(existsSync(join(t,"requirements.txt"))){let r=readFileSync(join(t,"requirements.txt"),"utf-8").toLowerCase();if(r.includes("django"))return {name:"Django",confidence:85};if(r.includes("flask"))return {name:"Flask",confidence:85}}return existsSync(join(t,"Gemfile"))&&readFileSync(join(t,"Gemfile"),"utf-8").toLowerCase().includes("rails")?{name:"Ruby on Rails",confidence:85}:existsSync(join(t,"pom.xml"))&&readFileSync(join(t,"pom.xml"),"utf-8").toLowerCase().includes("spring-boot")?{name:"Spring Boot",confidence:85}:{name:"unknown",confidence:0}}try{let r=JSON.parse(readFileSync(e,"utf-8")),s={...r.dependencies,...r.devDependencies},o=[{name:"Next.js",primary:["next"],secondary:["next/core-web-vitals","@next/bundle-analyzer"],indicators:["app","pages"]},{name:"React",primary:["react","react-dom"],secondary:["@types/react","react-scripts","create-react-app"],indicators:["src/components","src/App.js","src/App.tsx"]},{name:"Vue",primary:["vue"],secondary:["vue-router","vuex","pinia","@vue/cli-service"],indicators:["src/views","src/components"]},{name:"Angular",primary:["@angular/core"],secondary:["@angular/cli","@angular/common","@angular/router"],indicators:["src/app"]},{name:"Svelte",primary:["svelte"],secondary:["svelte-check","@sveltejs/kit"],indicators:["src/routes"]},{name:"Express",primary:["express"],secondary:["cors","helmet","morgan","body-parser"],indicators:["routes","controllers"]},{name:"NestJS",primary:["@nestjs/core"],secondary:["@nestjs/common","@nestjs/platform-express"],indicators:["src/modules"]},{name:"Fastify",primary:["fastify"],secondary:["@fastify/cors","@fastify/helmet"],indicators:["routes"]}];for(let a of o){let i=0;for(let c of a.primary)if(s[c]){i+=70;break}let l=0;for(let c of a.secondary)s[c]&&l<2&&(i+=10,l++);for(let c of a.indicators)existsSync(join(t,c))&&(i+=10);if(i>=60)return a.name==="Next.js"&&s.next?{name:a.name,confidence:100}:{name:a.name,confidence:Math.min(i,95)}}return s.astro?{name:"Astro",confidence:80}:s.remix?{name:"Remix",confidence:80}:s.gatsby?{name:"Gatsby",confidence:80}:s.nuxt?{name:"Nuxt.js",confidence:80}:s["@sveltejs/kit"]?{name:"SvelteKit",confidence:85}:{name:"unknown",confidence:0}}catch{return {name:"unknown",confidence:0}}}async function ui(t,e){try{let n=await nn(),r=await fetch(`${Ir}/v1/projects`,{method:"POST",headers:n,body:JSON.stringify({name:t,framework:e,source:"cli-init"})});if(!r.ok){let s=await r.json().catch(()=>({error:"Unknown error"}));throw new Error(s.error||`HTTP ${r.status}`)}return await r.json()}catch(n){return ve.error("Failed to create project:",n instanceof Error?n.message:String(n)),null}}function Cr(t){let e={"Next.js":["**/*.{js,jsx,ts,tsx,json,mjs,cjs}"],React:["**/*.{js,jsx,ts,tsx,json}"],Vue:["**/*.{js,jsx,ts,tsx,vue,json}"],Angular:["**/*.{ts,html,json}"],Svelte:["**/*.{js,ts,svelte,json}"],Express:["**/*.{js,ts,json}"],NestJS:["**/*.{ts,json}"],unknown:["**/*.{js,ts,jsx,tsx,json,py,go,rs,rb,php,cs,cpp,c,h}"]};return e[t]||e.unknown}function di(){return ["node_modules/**/*",".git/**/*","dist/**/*","build/**/*",".next/**/*","coverage/**/*","*.test.ts","*.spec.ts","*.min.js"]}function pi(t){let e=join(process.cwd(),"veestack.config.json");writeFileSync(e,JSON.stringify(t,null,2));}function fi(){let t=join(process.cwd(),"veestack.config.json");if(existsSync(t))try{return JSON.parse(readFileSync(t,"utf-8"))}catch{return null}return null}function gi(t){let e=process.cwd(),n=[],r=["src","app","lib","components","pages","routes","controllers","models","utils"];for(let s of r){let o=join(e,s);existsSync(o)&&n.push(`${s}/**/*`);}return n}function mi(){let t=process.cwd(),e=join(t,".git");return existsSync(e)}function hi(){let t=process.cwd();return existsSync(join(t,"pnpm-lock.yaml"))?"pnpm":existsSync(join(t,"yarn.lock"))?"yarn":existsSync(join(t,"package-lock.json"))?"npm":existsSync(join(t,"bun.lockb"))?"bun":"npm"}function yi(){return `Node ${process.version}`}async function Rt(t){t?.skipAuthCheck||console.log(h.bold.cyan(`
45
45
  \u{1F680} Initializing VeeStack...
46
46
  `));let e=false;t?.skipAuthCheck||(e=await xe()!==null);let n=fi();if(n?.projectId&&!t?.ci&&t?.interactive){let{overwrite:x}=await br({type:"confirm",name:"overwrite",message:`Project already linked to ${n.name||n.projectId}. Re-initialize?`,initial:false});if(!x){console.log(h.gray(`
47
47
  Cancelled. Existing configuration preserved.
@@ -65,28 +65,28 @@ VeeStack Security Scan`)),console.log(h.gray("\u2500".repeat(40))));await xe()!=
65
65
  Using smart defaults for this scan...`));}let a=_i({text:"Preparing scan...",spinner:"dots",stream:process.stdout});e||(console.log(`
66
66
  `+h.bold.cyan("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),console.log(h.bold.white(" Analyzing Project")),console.log(h.bold.cyan(`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
67
67
  `)),a.start());try{let i=Date.now(),l=existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{scanPatterns:["src/**/*","app/**/*","lib/**/*","components/**/*","pages/**/*"],excludePatterns:["node_modules/**/*",".git/**/*","dist/**/*","build/**/*",".next/**/*"]},c=l.scanPatterns||["**/*.{js,jsx,ts,tsx,json,py,go,rs,rb,php,cs,cpp,c,h,mjs,cjs,svelte,vue,html}"],f=l.excludePatterns||["**/node_modules/**","**/.next/**","**/dist/**","**/build/**","**/.git/**","**/.turbo/**","**/coverage/**","**/*.test.ts","**/*.spec.ts","**/*.min.js"],_=await xi(n,c,f),b=_.map(W=>W.path);if(e||(console.log(h.gray(`
68
- Found ${h.white(b.length)} source files`)),console.log(h.gray("Preparing scan..."))),b.length===0&&!t.json){e||(console.log(h.yellow(`
68
+ Found ${h.white(b.length)} source files`)),console.log(h.gray("Analyzing project files..."))),b.length===0&&!t.json){e||(console.log(h.yellow(`
69
69
  \u26A0\uFE0F No source files found to scan.`)),console.log(h.gray(`
70
70
  Checked patterns:`)),c.forEach(W=>console.log(h.gray(` \u2022 ${W}`))),console.log(h.gray(`
71
71
  Try running from the project root`)),console.log(h.gray(`or update scanPatterns in veestack.config.json
72
- `)));return}let x=new Si.SingleBar({format:"Scanning |"+h.cyan("{bar}")+"| {percentage}% ({value}/{total} files)",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});e||(console.log(h.gray("Analyzing project files...")),x.start(b.length,0)),e||(a.text="Analyzing security...");let I=await mr(n,b);e||x.update(Math.floor(b.length*.5));let _e=Or({metadata:{total_files:b.length}},I);if(t.json){let W={version:V,timestamp:new Date().toISOString(),score:_e.score,grade:_e.grade,files:b.length,issues:_e.breakdown,project:resolve(t.path).split(/[\\/]/).pop()};console.log(JSON.stringify(W,null,2)),process.exit(0);}I.criticalCount>0&&(e||(x.stop(),a.fail("Security validation failed"),console.log(h.red(`
72
+ `)));return}let x=new Si.SingleBar({format:"Scanning |"+h.cyan("{bar}")+"| {percentage}% ({value}/{total} files)",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});e||x.start(b.length,0),e||(a.text="Analyzing security...");let I=await mr(n,b);e||x.update(Math.floor(b.length*.5));let oe=Or({metadata:{total_files:b.length}},I);if(t.json){let W={version:V,timestamp:new Date().toISOString(),score:oe.score,grade:oe.grade,files:b.length,issues:oe.breakdown,project:resolve(t.path).split(/[\\/]/).pop()};console.log(JSON.stringify(W,null,2)),process.exit(0);}I.criticalCount>0&&(e||(x.stop(),a.fail("Security validation failed"),console.log(h.red(`
73
73
  \u274C Critical security risks detected.`)),console.log(h.yellow("For your protection, local snapshot generation is blocked.")),console.log(h.gray(`
74
74
  Please review your environment variables and configuration files.`)),console.log(h.gray(`Once resolved, run the scan again to prepare for cloud analysis.
75
- `))),process.exit(1));let{safe:Pt,blocked:pn}=hr(b),X=_.filter(W=>Pt.includes(W.path)),Ke=await Ti(n,X);e||(x.update(b.length),x.stop());let is=((Date.now()-i)/1e3).toFixed(1);if(e)console.log(h.green(`\u2714 Scan completed. Score: ${_e.grade}`));else {if(a.succeed(`Analysis prepared in ${is}s`),console.log(h.green(`
76
- \u{1F389} Snapshot ready for upload`)),console.log(`
75
+ `))),process.exit(1));let{safe:Pt,blocked:pn}=hr(b),X=_.filter(W=>Pt.includes(W.path)),Ke=await Ti(n,X);e||(x.update(b.length),x.stop());let is=((Date.now()-i)/1e3).toFixed(1);if(e)console.log(h.green(`\u2714 Scan completed. Score: ${oe.grade}`));else {if(a.succeed(`Analysis prepared in ${is}s`),console.log(`
77
76
  `+h.bold.cyan("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),console.log(h.bold.white(" VeeStack Security Summary")),console.log(h.bold.cyan(`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
78
77
  `)),console.log(h.bold("Status: ")+h.yellow("Analysis Pending Cloud Review")),console.log(h.gray(`Your project snapshot has been safely generated.
79
78
  `)),Object.keys(Ke.metadata.language_breakdown).length>0){let W=new ki({head:[h.cyan("Language"),h.cyan("Files")],style:{head:[],border:["gray"]}});Object.entries(Ke.metadata.language_breakdown).sort(([,pt],[,ft])=>ft-pt).slice(0,5).forEach(([pt,ft])=>W.push([pt,ft])),console.log(h.bold("Languages detected")),console.log(W.toString()+`
80
79
  `);}else console.log(h.bold("Languages detected")),console.log(h.gray(`No source languages detected.
81
- `));console.log(h.bold("Summary")),console.log(h.gray(` \u2022 Files: ${Ke.metadata.total_files}`)),console.log(h.gray(` \u2022 Dependencies: ${Ke.metadata.total_dependencies}`)),console.log(h.gray(` \u2022 Project: ${resolve(t.path).split(/[\\/]/).pop()}`)),console.log(`
82
- `+h.gray("\u2500".repeat(40)));}let fn=await import('fs/promises');await fn.writeFile(t.output,JSON.stringify(Ke,null,2));try{let W=Or(Ke,I),pt=join(process.env.HOME||process.env.USERPROFILE||"",".veestack","last-scan.json"),ft={timestamp:new Date().toISOString(),score:W.score,grade:W.grade,issues:I.secretsFound,project:resolve(t.path).split(/[\\/]/).pop()};await fn.mkdir(join(process.env.HOME||process.env.USERPROFILE||"",".veestack"),{recursive:!0}),await fn.writeFile(pt,JSON.stringify(ft,null,2));}catch{}console.log(`
80
+ `));console.log(h.bold("Summary")),console.log(h.gray(` \u2022 Files: ${Ke.metadata.total_files}`)),console.log(h.gray(` \u2022 Dependencies: ${Ke.metadata.total_dependencies}`)),console.log(h.gray(` \u2022 Project: ${resolve(t.path).split(/[\\/]/).pop()}`)),console.log(h.gray(` \u2022 Score: ${oe.score}`)),console.log(h.gray(` \u2022 Grade: ${oe.grade}`)),console.log(`
81
+ `+h.gray("\u2500".repeat(40))),console.log(h.green(`
82
+ \u{1F389} Snapshot ready for upload`));}let fn=await import('fs/promises');await fn.writeFile(t.output,JSON.stringify(Ke,null,2));try{let W=Or(Ke,I),pt=join(process.env.HOME||process.env.USERPROFILE||"",".veestack","last-scan.json"),ft={timestamp:new Date().toISOString(),score:W.score,grade:W.grade,issues:I.secretsFound,project:resolve(t.path).split(/[\\/]/).pop()};await fn.mkdir(join(process.env.HOME||process.env.USERPROFILE||"",".veestack"),{recursive:!0}),await fn.writeFile(pt,JSON.stringify(ft,null,2));}catch{}console.log(`
83
83
  \u2705 Snapshot saved to ${t.output}`),Ye?(console.log(h.bold(`
84
84
  Next step`)),console.log(h.gray(`
85
85
  Upload results to cloud:`)),console.log(h.cyan(" veestack upload"))):(console.log(h.bold(`
86
86
  Next step`)),console.log(h.gray(`
87
87
  Upload results to cloud:`)),console.log(h.cyan(" veestack upload snapshot.json")));}catch(i){a.fail("Scan failed"),console.error(h.red(`
88
88
  \u274C Error:`),i),console.log(h.gray(`
89
- Possible causes:`)),console.log(h.gray(" \u2022 Invalid project path")),console.log(h.gray(" \u2022 Permission denied")),console.log(h.gray(" \u2022 No package.json found")),process.exit(1);}}async function Ti(t,e){let n=await Ai(t),r={total_files:e.length,total_dependencies:n.length,total_size_bytes:e.reduce((s,o)=>s+o.size_bytes,0),total_lines:e.reduce((s,o)=>s+(o.estimated_lines||0),0),max_directory_depth:Math.max(...e.map(s=>s.depth),0),language_breakdown:Ri(e)};return {snapshot_version:ae,engine_target_version:Qe,project_id:de__default.randomUUID(),generated_at:new Date().toISOString(),root_path_hash:On(t),project_root:resolve(t),metadata:r,files:e,dependencies:n}}async function xi(t,e,n){let r=[],o=(await glob(e,{cwd:t,ignore:n,nodir:true,dot:true,absolute:false})).filter(a=>{let i=a.replace(/\\/g,"/");return !i.includes("node_modules/")&&!i.startsWith("node_modules/")&&!i.includes("/node_modules/")&&!i.includes(".next/")&&!i.startsWith(".next/")});for(let a of o){let i=join(t,a),l=statSync(i);if(l.isFile()){let c={id:de__default.randomUUID(),path:a,path_hash:On(a),depth:a.split(/[\\/]/).length,size_bytes:l.size,estimated_lines:Math.floor(l.size/50),extension:a.split(".").pop()||"",is_binary:Ci(a)};r.push(c);}}return r.sort((a,i)=>a.path_hash.localeCompare(i.path_hash))}async function Ai(t){let e=[];try{let n=join(t,"package.json"),r=JSON.parse(readFileSync(n,"utf-8")),s=(o,a)=>{for(let[i,l]of Object.entries(o)){let c=l.match(/^(\d+)\.(\d+)/),f=c?parseInt(c[1]):0,_=c?parseInt(c[2]):0;e.push({id:de__default.randomUUID(),name_hash:On(i),major_version:f,minor_version:_,category:a});}};r.dependencies&&s(r.dependencies,"prod"),r.devDependencies&&s(r.devDependencies,"dev"),r.peerDependencies&&s(r.peerDependencies,"peer");}catch{}return e.sort((n,r)=>n.name_hash.localeCompare(r.name_hash))}function Ri(t){let e={};for(let n of t){let r=n.extension.toLowerCase(),s=bi(r);e[s]=(e[s]||0)+1;}return e}function bi(t){return {ts:"TypeScript",js:"JavaScript",tsx:"TypeScript",jsx:"JavaScript",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",rb:"Ruby",php:"PHP",cs:"C#",cpp:"C++",c:"C",h:"C",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",html:"HTML",css:"CSS",scss:"SCSS",sql:"SQL",sh:"Shell"}[t]||"Other"}function Ci(t){let e=[".exe",".dll",".so",".dylib",".bin",".png",".jpg",".jpeg",".gif",".pdf",".zip",".tar",".gz",".7z",".woff",".woff2",".ttf",".eot"],n=t.split(".").pop()?.toLowerCase();return n?e.includes("."+n):false}function On(t){return de__default.createHash("sha256").update(t).digest("hex")}var un=process.env.SUPABASE_URL||"https://qhonrrojtqklvlkvfswb.supabase.co",Ae=process.env.SUPABASE_ANON_KEY||"";async function Xi(){try{let t=await fetch(`${un}/rest/v1/projects?select=id,name,created_at&order=created_at.desc`,{headers:{apikey:Ae,Authorization:`Bearer ${Ae}`}});return t.ok?await t.json():[]}catch{return []}}async function Br(t){try{let e=await fetch(`${un}/rest/v1/projects`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({name:t,user_id:"00000000-0000-0000-0000-000000000001"})});return e.ok&&(await e.json())[0]?.id||null}catch{return null}}function ln(t){let e=qi.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{e.question(t,r=>{e.close(),n(r);});})}async function Qi(){console.log(h.blue(`
89
+ Possible causes:`)),console.log(h.gray(" \u2022 Invalid project path")),console.log(h.gray(" \u2022 Permission denied")),console.log(h.gray(" \u2022 No package.json found")),process.exit(1);}}async function Ti(t,e){let n=await Ai(t),r={total_files:e.length,total_dependencies:n.length,total_size_bytes:e.reduce((s,o)=>s+o.size_bytes,0),total_lines:e.reduce((s,o)=>s+(o.estimated_lines||0),0),max_directory_depth:Math.max(...e.map(s=>s.depth),0),language_breakdown:Ri(e)};return {snapshot_version:ce,engine_target_version:Qe,project_id:pe__default.randomUUID(),generated_at:new Date().toISOString(),root_path_hash:On(t),project_root:resolve(t),metadata:r,files:e,dependencies:n}}async function xi(t,e,n){let r=[],o=(await glob(e,{cwd:t,ignore:n,nodir:true,dot:true,absolute:false})).filter(a=>{let i=a.replace(/\\/g,"/");return !i.includes("node_modules/")&&!i.startsWith("node_modules/")&&!i.includes("/node_modules/")&&!i.includes(".next/")&&!i.startsWith(".next/")});for(let a of o){let i=join(t,a),l=statSync(i);if(l.isFile()){let c={id:pe__default.randomUUID(),path:a,path_hash:On(a),depth:a.split(/[\\/]/).length,size_bytes:l.size,estimated_lines:Math.floor(l.size/50),extension:a.split(".").pop()||"",is_binary:Ci(a)};r.push(c);}}return r.sort((a,i)=>a.path_hash.localeCompare(i.path_hash))}async function Ai(t){let e=[];try{let n=join(t,"package.json"),r=JSON.parse(readFileSync(n,"utf-8")),s=(o,a)=>{for(let[i,l]of Object.entries(o)){let c=l.match(/^(\d+)\.(\d+)/),f=c?parseInt(c[1]):0,_=c?parseInt(c[2]):0;e.push({id:pe__default.randomUUID(),name_hash:On(i),major_version:f,minor_version:_,category:a});}};r.dependencies&&s(r.dependencies,"prod"),r.devDependencies&&s(r.devDependencies,"dev"),r.peerDependencies&&s(r.peerDependencies,"peer");}catch{}return e.sort((n,r)=>n.name_hash.localeCompare(r.name_hash))}function Ri(t){let e={};for(let n of t){let r=n.extension.toLowerCase(),s=bi(r);e[s]=(e[s]||0)+1;}return e}function bi(t){return {ts:"TypeScript",js:"JavaScript",tsx:"TypeScript",jsx:"JavaScript",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",rb:"Ruby",php:"PHP",cs:"C#",cpp:"C++",c:"C",h:"C",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",html:"HTML",css:"CSS",scss:"SCSS",sql:"SQL",sh:"Shell"}[t]||"Other"}function Ci(t){let e=[".exe",".dll",".so",".dylib",".bin",".png",".jpg",".jpeg",".gif",".pdf",".zip",".tar",".gz",".7z",".woff",".woff2",".ttf",".eot"],n=t.split(".").pop()?.toLowerCase();return n?e.includes("."+n):false}function On(t){return pe__default.createHash("sha256").update(t).digest("hex")}var un=process.env.SUPABASE_URL||"https://qhonrrojtqklvlkvfswb.supabase.co",Ae=process.env.SUPABASE_ANON_KEY||"";async function Xi(){try{let t=await fetch(`${un}/rest/v1/projects?select=id,name,created_at&order=created_at.desc`,{headers:{apikey:Ae,Authorization:`Bearer ${Ae}`}});return t.ok?await t.json():[]}catch{return []}}async function Br(t){try{let e=await fetch(`${un}/rest/v1/projects`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({name:t,user_id:"00000000-0000-0000-0000-000000000001"})});return e.ok&&(await e.json())[0]?.id||null}catch{return null}}function ln(t){let e=qi.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{e.question(t,r=>{e.close(),n(r);});})}async function Qi(){console.log(h.blue(`
90
90
  \u{1F4C1} Loading projects...
91
91
  `));let t=await Xi();if(t.length===0){if(console.log(h.yellow(`No projects found.
92
92
  `)),(await ln("Do you want to create a new project? (y/n): ")).toLowerCase()==="y"){let s=await ln("Enter project name: ");if(s.trim()){let o=await Br(s.trim());if(o)return console.log(h.green(`
@@ -101,10 +101,10 @@ Enter project name: `);if(r.trim()){let s=await Br(r.trim());if(s)return console
101
101
  Please login first:`)),console.log(h.cyan(" veestack login")),process.exit(1));let n=rn();console.log(h.blue(`
102
102
  \u{1F510} Authentication verified`)),e.user&&console.log(h.gray(`User: ${e.user.name}`)),console.log(h.gray(`Subscription tier: ${n==="pro"?"Pro":"Free"}`)),console.log(h.gray("\u2500".repeat(40)+`
103
103
  `));let r=_i("Preparing upload...").start();try{let o=await(await import('fs/promises')).readFile(t.file,"utf-8"),a=JSON.parse(o),i=t.projectId;if(!i){r.stop();let X=await Qi();X||(console.log(h.red(`
104
- \u274C No project selected. Exiting.`)),process.exit(1)),i=X,r.start("Uploading snapshot...");}r.text="Creating snapshot...";let l=await fetch(`${un}/rest/v1/snapshots`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({project_id:i,file_count:a.metadata.total_files,size_mb:a.metadata.total_size_bytes/(1024*1024),storage_path:"local://"+i})});if(!l.ok){let X=await l.json();r.fail("Failed to create snapshot"),console.error(h.red(`Error: ${X.message||X.details||"Unknown error"}`)),process.exit(1);}let c=await l.json(),f=c[0]?.id||c[0]?.id;r.text="Analyzing snapshot...";let{CoreEngine:_}=await Promise.resolve().then(()=>(jn(),Pn)),{RULES:b}=await Promise.resolve().then(()=>(jn(),Pn)),x=new _;b.forEach(X=>x.registerRule(X));let I=await x.analyze(a);I.success||(r.fail("Analysis failed"),console.error(h.red("Error:",I.error)),process.exit(1)),r.text="Creating report...";let _e=await fetch(`${un}/rest/v1/reports`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({snapshot_id:f,score:I.report.total_score,issues_count:I.report.summary.total_findings,critical_count:I.report.summary.critical_count,high_count:I.report.summary.high_count,medium_count:I.report.summary.medium_count,low_count:I.report.summary.low_count,execution_time_ms:0,report_json:I.report})});if(!_e.ok){let X=await _e.json();r.fail("Failed to create report"),console.error(h.red(`Error: ${X.message||X.details||"Unknown error"}`)),process.exit(1);}let Pt=await _e.json(),pn=Pt[0]?.id||Pt[0]?.id;r.succeed("Analysis complete"),console.log(h.green(`
104
+ \u274C No project selected. Exiting.`)),process.exit(1)),i=X,r.start("Uploading snapshot...");}r.text="Creating snapshot...";let l=await fetch(`${un}/rest/v1/snapshots`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({project_id:i,file_count:a.metadata.total_files,size_mb:a.metadata.total_size_bytes/(1024*1024),storage_path:"local://"+i})});if(!l.ok){let X=await l.json();r.fail("Failed to create snapshot"),console.error(h.red(`Error: ${X.message||X.details||"Unknown error"}`)),process.exit(1);}let c=await l.json(),f=c[0]?.id||c[0]?.id;r.text="Analyzing snapshot...";let{CoreEngine:_}=await Promise.resolve().then(()=>(jn(),Pn)),{RULES:b}=await Promise.resolve().then(()=>(jn(),Pn)),x=new _;b.forEach(X=>x.registerRule(X));let I=await x.analyze(a);I.success||(r.fail("Analysis failed"),console.error(h.red("Error:",I.error)),process.exit(1)),r.text="Creating report...";let oe=await fetch(`${un}/rest/v1/reports`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({snapshot_id:f,score:I.report.total_score,issues_count:I.report.summary.total_findings,critical_count:I.report.summary.critical_count,high_count:I.report.summary.high_count,medium_count:I.report.summary.medium_count,low_count:I.report.summary.low_count,execution_time_ms:0,report_json:I.report})});if(!oe.ok){let X=await oe.json();r.fail("Failed to create report"),console.error(h.red(`Error: ${X.message||X.details||"Unknown error"}`)),process.exit(1);}let Pt=await oe.json(),pn=Pt[0]?.id||Pt[0]?.id;r.succeed("Analysis complete"),console.log(h.green(`
105
105
  \u2705 Report generated and saved to VeeStack`)),console.log(h.gray("Project ID:"),i),console.log(h.gray("Snapshot ID:"),f),console.log(h.gray("Report ID:"),pn),console.log(h.bold(`
106
106
  \u{1F4CA} Score:`),I.report.total_score),console.log(h.gray("Severity:"),I.report.severity_band),console.log(h.gray("Findings:"),I.report.summary.total_findings),console.log(h.blue(`
107
- \u{1F517} View your report at:`)),console.log(h.underline(`http://localhost:3001/reports/${pn}?project=${i}`));}catch(s){r.fail("Upload failed"),console.error(s),process.exit(1);}}K();var zr=process.env.VEESTACK_API_URL||"https://api.veestack.tools",na=process.env.VEESTACK_WEB_URL||"https://veestack.tools",ra=2e3,Wr=300;function sa(){return de__default.randomBytes(16).toString("hex")}function oa(){let t=de__default.randomBytes(32).toString("base64url"),e=de__default.createHash("sha256").update(t).digest("base64url");return {code_verifier:t,code_challenge:e}}function ia(){let t=process.platform,e=ct.hostname(),n=B,r=e||de__default.randomBytes(8).toString("hex"),s=de__default.createHash("sha256").update(`${r}:${t}:${n}`).digest("hex"),o=de__default.randomBytes(12).toString("hex"),a=`${e||"Unknown"} (${t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"})`;return {id:o,name:a,fingerprint:s,os:t,version:n}}async function aa(t,e){let n=sa(),r=await fetch(`${zr}/api/cli/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:n,client_id:"veestack-cli",code_challenge:t.code_challenge,code_challenge_method:"S256",device_info:{id:e.id,name:e.name,fingerprint:e.fingerprint,os:e.os,version:e.version}})});if(!r.ok)throw new Error(`Failed to request device code: ${r.statusText}`);return await r.json()}async function ca(t,e,n){try{let r=await fetch(`${zr}/api/cli/token?device_code=${t}&code_verifier=${e}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(r.status===202)return null;if(!r.ok)throw new Error(`Failed to poll for token: ${r.statusText}`);return r.json()}catch{if(n>=Wr)throw new Error("Authentication timeout. Please try again.");return null}}async function It(){console.log(h.bold.cyan(`
107
+ \u{1F517} View your report at:`)),console.log(h.underline(`http://localhost:3001/reports/${pn}?project=${i}`));}catch(s){r.fail("Upload failed"),console.error(s),process.exit(1);}}K();var zr=process.env.VEESTACK_API_URL||"https://api.veestack.tools",na=process.env.VEESTACK_WEB_URL||"https://veestack.tools",ra=2e3,Wr=300;function sa(){return pe__default.randomBytes(16).toString("hex")}function oa(){let t=pe__default.randomBytes(32).toString("base64url"),e=pe__default.createHash("sha256").update(t).digest("base64url");return {code_verifier:t,code_challenge:e}}function ia(){let t=process.platform,e=ct.hostname(),n=B,r=e||pe__default.randomBytes(8).toString("hex"),s=pe__default.createHash("sha256").update(`${r}:${t}:${n}`).digest("hex"),o=pe__default.randomBytes(12).toString("hex"),a=`${e||"Unknown"} (${t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"})`;return {id:o,name:a,fingerprint:s,os:t,version:n}}async function aa(t,e){let n=sa(),r=await fetch(`${zr}/api/cli/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:n,client_id:"veestack-cli",code_challenge:t.code_challenge,code_challenge_method:"S256",device_info:{id:e.id,name:e.name,fingerprint:e.fingerprint,os:e.os,version:e.version}})});if(!r.ok)throw new Error(`Failed to request device code: ${r.statusText}`);return await r.json()}async function ca(t,e,n){try{let r=await fetch(`${zr}/api/cli/token?device_code=${t}&code_verifier=${e}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(r.status===202)return null;if(!r.ok)throw new Error(`Failed to poll for token: ${r.statusText}`);return r.json()}catch{if(n>=Wr)throw new Error("Authentication timeout. Please try again.");return null}}async function It(){console.log(h.bold.cyan(`
108
108
  \u{1F510} Login to VeeStack
109
109
  `)),console.log(h.gray(`Opening browser to authenticate...
110
110
  `));let t=_i({text:"Requesting device code...",spinner:"dots",stream:process.stdout});try{let e=oa(),n=ia();t.start();let r=await aa(e,n);t.stop();let s=`${na}/cli-auth?device=${r.device_code}&code=${r.user_code}&challenge=${e.code_challenge}`;console.log(h.white(`Please authenticate using your browser:
@@ -120,7 +120,7 @@ Token saved securely to OS Keychain`)),Rr({token:i.token,tokenType:i.tokenType,r
120
120
  \u{1F6AA} Logout from VeeStack
121
121
  `)),t.token||t.apiKey)try{let e=t.token||t.apiKey;await fetch(`${la}/api/cli/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({device_id:t.device?.id})});}catch{}await Xt()&&await ze();try{let{existsSync:e,unlinkSync:n}=await import('fs'),{join:r}=await import('path'),{homedir:s}=await import('os'),o=r(s(),".veestack"),a=r(o,"config.json");e(a)&&n(a);}catch{}t.user?console.log(h.green(`\u2714 Logged out ${t.user.name}`)):console.log(h.green("\u2714 Logged out")),console.log(h.gray(`
122
122
  \u{1F510} All local tokens securely deleted`)),console.log(h.gray("See you soon! \u{1F44B}")),console.log(h.gray(`Run "veestack login" to authenticate again.
123
- `));}catch(t){ye.error("\u274C Error during logout:",Rn(t)),process.exit(1);}}async function Yr(){try{let t=await xe();t||(console.log(h.yellow("\u26A0\uFE0F Not authenticated")),console.log(h.gray(`
123
+ `));}catch(t){ve.error("\u274C Error during logout:",Rn(t)),process.exit(1);}}async function Yr(){try{let t=await xe();t||(console.log(h.yellow("\u26A0\uFE0F Not authenticated")),console.log(h.gray(`
124
124
  Please login first:`)),console.log(h.cyan(" veestack login")),process.exit(1)),console.log(h.bold.cyan(`
125
125
  \u{1F464} VeeStack Account
126
126
  `)),t.user&&(console.log(h.gray("User: ")+h.white(t.user.name)),console.log(h.gray("Email: ")+h.white(t.user.email)),console.log(h.gray("Provider: ")+h.cyan(t.user.provider))),t.device&&(console.log(h.gray("Device: ")+h.white(t.device.name)),console.log(h.gray("Device ID: ")+h.gray(t.device.id.substring(0,8)+"...")));let e=t.subscription?.tier||"free";if(console.log(h.gray("Subscription: ")+(e==="pro"?h.cyan("Pro"):h.blue("Free"))),t.tokenExpiresAt){let r=Cn(t)?h.red("Expired (will refresh)"):h.green("Valid");console.log(h.gray("Token Status: ")+r),console.log(h.gray("Expires: ")+h.yellow(new Date(t.tokenExpiresAt).toLocaleString()));}t.lastLoginAt&&console.log(h.gray("Last Login: ")+h.gray(new Date(t.lastLoginAt).toLocaleString())),console.log();}catch(t){console.error(h.red("\u274C Error:"),t instanceof Error?t.message:t),process.exit(1);}}function Jr(){return join(homedir(),".veestack","accounts")}function ua(){try{let t=Jr();if(!re.existsSync(t))return [];let e=[],n=re.readdirSync(t);for(let r of n)if(r.endsWith(".json")){let s=re.readFileSync(join(t,r),"utf-8"),o=JSON.parse(s);o.user&&e.push({id:o.user.id,name:o.user.name,email:o.user.email,provider:o.user.provider,config:o});}return e}catch{return []}}function da(t){try{let e=Jr();if(re.mkdirSync(e,{recursive:!0}),t.user){let n=join(e,`${t.user.id}.json`);re.writeFileSync(n,JSON.stringify(t,null,2),{mode:384});}}catch{}}async function Kr(){let t=await q(),e=ua();console.log(h.bold.cyan(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vee_stack/cli",
3
- "version": "6.2.3",
3
+ "version": "6.2.4",
4
4
  "description": "VeeStack CLI - Technical Stack Visibility Tool",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",