@vee_stack/cli 6.1.2 → 6.1.3

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 +79 -79
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,45 +1,45 @@
1
1
  #!/usr/bin/env node
2
- import {createRequire}from'module';import {glob}from'glob';import*as te from'fs';import {existsSync,readFileSync,writeFileSync,statSync}from'fs';import*as Ge from'path';import {join,resolve}from'path';import*as le from'crypto';import le__default from'crypto';import y from'chalk';import {fileURLToPath}from'url';import {Command}from'commander';import Bo from'ora';import Ho from'cli-progress';import zo from'cli-table3';import*as ot from'os';import {homedir}from'os';import*as U from'fs/promises';import _i from'readline';import wi from'open';import {execSync}from'child_process';import Gr from'prompts';import va from'omelette';createRequire(import.meta.url);
3
- var Jr=Object.defineProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var $n=(t,e)=>{for(var n in e)Jr(t,n,{get:e[n],enumerable:true});};var ye,H,cn,oe,Ke,Dt,un,dn=G(()=>{ye="6.1.1",H=ye,cn=`vs_cli_v${ye}`,oe="2.0.0",Ke="2.0.0",Dt="3.0",un="v2";});var A,pn,g,ie,gt=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;})(A||(A={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n});})(pn||(pn={}));g=A.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=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,Pt=G(()=>{gt();u=A.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,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(n(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++;}}};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,A.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 ns,ue,fn=G(()=>{Pt();gt();ns=(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,A.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:n=`Unrecognized key(s) in object: ${A.joinValues(t.keys,", ")}`;break;case u.invalid_union:n="Invalid input";break;case u.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${A.joinValues(t.options)}`;break;case u.invalid_enum_value:n=`Invalid enum value. Expected ${A.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}"`:A.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,A.assertNever(t);}return {message:n}},ue=ns;});function rs(t){Wn=t;}function qe(){return Wn}var Wn,Lt=G(()=>{fn();Wn=ue;});function f(t,e){let n=qe(),r=mt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ue?void 0:ue].filter(s=>!!s)});t.common.issues.push(r);}var mt,ss,M,h,Ae,V,jt,Ut,ve,Xe,gn=G(()=>{Lt();fn();mt=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="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)i=l(a,{data:e,defaultError:i}).message;return {...s,path:o,message:i}},ss=[];M=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 h;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 h;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}}},h=Object.freeze({status:"aborted"}),Ae=t=>({status:"dirty",value:t}),V=t=>({status:"valid",value:t}),jt=t=>t.status==="aborted",Ut=t=>t.status==="dirty",ve=t=>t.status==="valid",Xe=t=>typeof Promise<"u"&&t instanceof Promise;});var Gn=G(()=>{});var m,Yn=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:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??n??i.defaultError}},description:s}}function qn(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 Es(t){return new RegExp(`^${qn(t)}$`)}function Xn(t){let e=`${Kn}T${qn(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 Ss(t,e){return !!((e==="v4"||!e)&&gs.test(t)||(e==="v6"||!e)&&hs.test(t))}function ws(t,e){if(!us.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 Ts(t,e){return !!((e==="v4"||!e)&&ms.test(t)||(e==="v6"||!e)&&ys.test(t))}function As(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 Qe(t){if(t instanceof Z){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=X.create(Qe(r));}return new Z({...t._def,shape:()=>e})}else return t instanceof fe?new fe({...t._def,type:Qe(t.element)}):t instanceof X?X.create(Qe(t.unwrap())):t instanceof ce?ce.create(Qe(t.unwrap())):t instanceof ae?ae.create(t.items.map(e=>Qe(e))):t}function hn(t,e){let n=ie(t),r=ie(e);if(t===e)return {valid:true,data:t};if(n===g.object&&r===g.object){let s=A.objectKeys(e),o=A.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(let i of o){let c=hn(t[i],e[i]);if(!c.valid)return {valid:false};a[i]=c.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],c=hn(a,i);if(!c.valid)return {valid:false};s.push(c.data);}return {valid:true,data:s}}else return n===g.date&&r===g.date&&+t==+e?{valid:true,data:t}:{valid:false}}function Qn(t,e){return new je({values:t,typeName:v.ZodEnum,...S(e)})}function Jn(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function er(t,e={},n){return t?ke.create().superRefine((r,s)=>{let o=t(r);if(o instanceof Promise)return o.then(a=>{if(!a){let i=Jn(e,r),c=i.fatal??n??true;s.addIssue({code:"custom",...i,fatal:c});}});if(!o){let a=Jn(e,r),i=a.fatal??n??true;s.addIssue({code:"custom",...a,fatal:i});}}):ke.create()}var Q,Zn,w,os,is,as,cs,ls,us,ds,ps,fs,mn,gs,ms,hs,ys,vs,_s,Kn,ks,_e,xe,Re,be,Ce,et,Ie,Ne,ke,pe,ne,tt,fe,Z,Oe,de,$t,De,ae,Mt,nt,rt,Ft,Pe,Le,je,Ue,Ee,ee,X,ce,$e,Me,st,xs,ht,yt,Fe,Rs,v,bs,tr,nr,Cs,Is,rr,Ns,Os,Ds,Ps,Ls,js,Us,$s,Ms,Fs,Vs,Bs,Hs,zs,Ws,Gs,Ys,Zs,Js,Ks,qs,Xs,Qs,eo,to,no,ro,so,oo,io,ao,co,lo,uo,sr=G(()=>{Pt();Lt();Yn();gn();gt();Q=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}},Zn=(t,e)=>{if(ve(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 ie(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Xe(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:ie(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Zn(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ve(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=>ve(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:ie(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(Xe(s)?s:Promise.resolve(s));return Zn(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(c=>c?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 ee({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 X.create(this,this._def)}nullable(){return ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fe.create(this)}promise(){return Ee.create(this,this._def)}or(e){return Oe.create([this,e],this._def)}and(e){return De.create(this,e,this._def)}transform(e){return new ee({...S(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $e({...S(this._def),innerType:this,defaultValue:n,typeName:v.ZodDefault})}brand(){return new ht({typeName:v.ZodBranded,type:this,...S(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Me({...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 yt.create(this,e)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},os=/^c[^\s-]{8,}$/i,is=/^[0-9a-z]+$/,as=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cs=/^[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,ls=/^[a-z0-9_-]{21}$/i,us=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ds=/^[-+]?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)?)??$/,ps=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gs=/^(?:(?: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])$/,ms=/^(?:(?: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])$/,hs=/^(([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]))$/,ys=/^(([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}=))?$/,_s=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kn="((\\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])))",ks=new RegExp(`^${Kn}$`);_e=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 f(o,{code:u.invalid_type,expected:g.string,received:o.parsedType}),h}let r=new M,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),f(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),f(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?f(s,{code:u.too_big,maximum:o.value,type:"string",inclusive:true,exact:true,message:o.message}):i&&f(s,{code:u.too_small,minimum:o.value,type:"string",inclusive:true,exact:true,message:o.message}),r.dirty());}else if(o.kind==="email")ps.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"email",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")mn||(mn=new RegExp(fs,"u")),mn.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"emoji",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")cs.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"uuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")ls.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"nanoid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")os.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")is.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid2",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")as.test(e.data)||(s=this._getOrReturnCtx(e,s),f(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),f(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),f(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),f(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),f(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),f(s,{code:u.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Xn(o).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:u.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?ks.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:u.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Es(o).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:u.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?ds.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"duration",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ss(e.data,o.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ip",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?ws(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"jwt",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Ts(e.data,o.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cidr",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?vs.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?_s.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64url",code:u.invalid_string,message:o.message}),r.dirty()):A.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}};_e.create=t=>new _e({checks:[],typeName:v.ZodString,coerce:t?.coerce??false,...S(t)});xe=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 f(o,{code:u.invalid_type,expected:g.number,received:o.parsedType}),h}let r,s=new M;for(let o of this._def.checks)o.kind==="int"?A.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),f(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),f(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),f(r,{code:u.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),s.dirty()):o.kind==="multipleOf"?As(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),f(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),f(r,{code:u.not_finite,message:o.message}),s.dirty()):A.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"&&A.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)}};xe.create=t=>new xe({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||false,...S(t)});Re=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 M;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),f(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),f(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),f(r,{code:u.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):A.assertNever(o);return {status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:g.bigint,received:n.parsedType}),h}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}};Re.create=t=>new Re({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??false,...S(t)});be=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.boolean,received:r.parsedType}),h}return V(e.data)}};be.create=t=>new be({typeName:v.ZodBoolean,coerce:t?.coerce||false,...S(t)});Ce=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 f(o,{code:u.invalid_type,expected:g.date,received:o.parsedType}),h}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return f(o,{code:u.invalid_date}),h}let r=new M,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),f(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),f(s,{code:u.too_big,message:o.message,inclusive:true,exact:false,maximum:o.value,type:"date"}),r.dirty()):A.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}};Ce.create=t=>new Ce({checks:[],coerce:t?.coerce||false,typeName:v.ZodDate,...S(t)});et=class extends w{_parse(e){if(this._getType(e)!==g.symbol){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.symbol,received:r.parsedType}),h}return V(e.data)}};et.create=t=>new et({typeName:v.ZodSymbol,...S(t)});Ie=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.undefined,received:r.parsedType}),h}return V(e.data)}};Ie.create=t=>new Ie({typeName:v.ZodUndefined,...S(t)});Ne=class extends w{_parse(e){if(this._getType(e)!==g.null){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.null,received:r.parsedType}),h}return V(e.data)}};Ne.create=t=>new Ne({typeName:v.ZodNull,...S(t)});ke=class extends w{constructor(){super(...arguments),this._any=true;}_parse(e){return V(e.data)}};ke.create=t=>new ke({typeName:v.ZodAny,...S(t)});pe=class extends w{constructor(){super(...arguments),this._unknown=true;}_parse(e){return V(e.data)}};pe.create=t=>new pe({typeName:v.ZodUnknown,...S(t)});ne=class extends w{_parse(e){let n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:g.never,received:n.parsedType}),h}};ne.create=t=>new ne({typeName:v.ZodNever,...S(t)});tt=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.void,received:r.parsedType}),h}return V(e.data)}};tt.create=t=>new tt({typeName:v.ZodVoid,...S(t)});fe=class t extends w{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==g.array)return f(n,{code:u.invalid_type,expected:g.array,received:n.parsedType}),h;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,i=n.data.length<s.exactLength.value;(a||i)&&(f(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&&(f(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&&(f(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 Q(n,a,n.path,i)))).then(a=>M.mergeArray(r,a));let o=[...n.data].map((a,i)=>s.type._parseSync(new Q(n,a,n.path,i)));return M.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)}};fe.create=(t,e)=>new fe({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=A.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==g.object){let l=this._getOrReturnCtx(e);return f(l,{code:u.invalid_type,expected:g.object,received:l.parsedType}),h}let{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof ne&&this._def.unknownKeys==="strip"))for(let l in s.data)a.includes(l)||i.push(l);let c=[];for(let l of a){let d=o[l],T=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Q(s,T,s.path,l)),alwaysSet:l in s.data});}if(this._def.catchall instanceof ne){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of i)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")i.length>0&&(f(s,{code:u.unrecognized_keys,keys:i}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let l=this._def.catchall;for(let d of i){let T=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Q(s,T,s.path,d)),alwaysSet:d in s.data});}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let T=await d.key,b=await d.value;l.push({key:T,value:b,alwaysSet:d.alwaysSet});}return l}).then(l=>M.mergeObjectSync(r,l)):M.mergeObjectSync(r,c)}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 A.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 A.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Qe(this)}partial(e){let n={};for(let r of A.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 A.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else {let o=this.shape[r];for(;o instanceof X;)o=o._def.innerType;n[r]=o;}return new t({...this._def,shape:()=>n})}keyof(){return Qn(A.objectKeys(this.shape))}};Z.create=(t,e)=>new Z({shape:()=>t,unknownKeys:"strip",catchall:ne.create(),typeName:v.ZodObject,...S(e)});Z.strictCreate=(t,e)=>new Z({shape:()=>t,unknownKeys:"strict",catchall:ne.create(),typeName:v.ZodObject,...S(e)});Z.lazycreate=(t,e)=>new Z({shape:t,unknownKeys:"strip",catchall:ne.create(),typeName:v.ZodObject,...S(e)});Oe=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 f(n,{code:u.invalid_union,unionErrors:a}),h}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 c of r){let l={...n,common:{...n.common,issues:[]},parent:null},d=c._parseSync({data:n.data,path:n.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues);}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(c=>new Y(c));return f(n,{code:u.invalid_union,unionErrors:i}),h}}get options(){return this._def.options}};Oe.create=(t,e)=>new Oe({options:t,typeName:v.ZodUnion,...S(e)});de=t=>t instanceof Pe?de(t.schema):t instanceof ee?de(t.innerType()):t instanceof Le?[t.value]:t instanceof je?t.options:t instanceof Ue?A.objectValues(t.enum):t instanceof $e?de(t._def.innerType):t instanceof Ie?[void 0]:t instanceof Ne?[null]:t instanceof X?[void 0,...de(t.unwrap())]:t instanceof ce?[null,...de(t.unwrap())]:t instanceof ht||t instanceof Fe?de(t.unwrap()):t instanceof Me?de(t._def.innerType):[],$t=class t extends w{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.object)return f(n,{code:u.invalid_type,expected:g.object,received:n.parsedType}),h;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}):(f(n,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),h)}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=de(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)})}};De=class extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(o,a)=>{if(jt(o)||jt(a))return h;let i=hn(o.value,a.value);return i.valid?((Ut(o)||Ut(a))&&n.dirty(),{status:n.value,value:i.data}):(f(r,{code:u.invalid_intersection_types}),h)};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}))}};De.create=(t,e,n)=>new De({left:t,right:e,typeName:v.ZodIntersection,...S(n)});ae=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.array)return f(r,{code:u.invalid_type,expected:g.array,received:r.parsedType}),h;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),h;!this._def.rest&&r.data.length>this._def.items.length&&(f(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 c=this._def.items[i]||this._def.rest;return c?c._parse(new Q(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>M.mergeArray(n,a)):M.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ae.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ae({items:t,typeName:v.ZodTuple,rest:null,...S(e)})};Mt=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 f(r,{code:u.invalid_type,expected:g.object,received:r.parsedType}),h;let s=[],o=this._def.keyType,a=this._def.valueType;for(let i in r.data)s.push({key:o._parse(new Q(r,i,r.path,i)),value:a._parse(new Q(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?M.mergeObjectAsync(n,s):M.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:_e.create(),valueType:e,typeName:v.ZodRecord,...S(n)})}},nt=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 f(r,{code:u.invalid_type,expected:g.map,received:r.parsedType}),h;let s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([i,c],l)=>({key:s._parse(new Q(r,i,r.path,[l,"key"])),value:o._parse(new Q(r,c,r.path,[l,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return h;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),i.set(l.value,d.value);}return {status:n.value,value:i}})}else {let i=new Map;for(let c of a){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return h;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),i.set(l.value,d.value);}return {status:n.value,value:i}}}};nt.create=(t,e,n)=>new nt({valueType:e,keyType:t,typeName:v.ZodMap,...S(n)});rt=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.set)return f(r,{code:u.invalid_type,expected:g.set,received:r.parsedType}),h;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(f(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&&(f(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(c){let l=new Set;for(let d of c){if(d.status==="aborted")return h;d.status==="dirty"&&n.dirty(),l.add(d.value);}return {status:n.value,value:l}}let i=[...r.data.values()].map((c,l)=>o._parse(new Q(r,c,r.path,l)));return r.common.async?Promise.all(i).then(c=>a(c)):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)}};rt.create=(t,e)=>new rt({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...S(e)});Ft=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 f(n,{code:u.invalid_type,expected:g.function,received:n.parsedType}),h;function r(i,c){return mt({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qe(),ue].filter(l=>!!l),issueData:{code:u.invalid_arguments,argumentsError:c}})}function s(i,c){return mt({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qe(),ue].filter(l=>!!l),issueData:{code:u.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Ee){let i=this;return V(async function(...c){let l=new Y([]),d=await i._def.args.parseAsync(c,o).catch(j=>{throw l.addIssue(r(c,j)),l}),T=await Reflect.apply(a,this,d);return await i._def.returns._def.type.parseAsync(T,o).catch(j=>{throw l.addIssue(s(T,j)),l})})}else {let i=this;return V(function(...c){let l=i._def.args.safeParse(c,o);if(!l.success)throw new Y([r(c,l.error)]);let d=Reflect.apply(a,this,l.data),T=i._def.returns.safeParse(d,o);if(!T.success)throw new Y([s(d,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ae.create(e).rest(pe.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||ae.create([]).rest(pe.create()),returns:n||pe.create(),typeName:v.ZodFunction,...S(r)})}},Pe=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})}};Pe.create=(t,e)=>new Pe({getter:t,typeName:v.ZodLazy,...S(e)});Le=class extends w{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return f(n,{received:n.data,code:u.invalid_literal,expected:this._def.value}),h}return {status:"valid",value:e.data}}get value(){return this._def.value}};Le.create=(t,e)=>new Le({value:t,typeName:v.ZodLiteral,...S(e)});je=class t extends w{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return f(n,{expected:A.joinValues(r),received:n.parsedType,code:u.invalid_type}),h}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 f(n,{received:n.data,code:u.invalid_enum_value,options:r}),h}return V(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})}};je.create=Qn;Ue=class extends w{_parse(e){let n=A.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==g.string&&r.parsedType!==g.number){let s=A.objectValues(n);return f(r,{expected:A.joinValues(s),received:r.parsedType,code:u.invalid_type}),h}if(this._cache||(this._cache=new Set(A.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=A.objectValues(n);return f(r,{received:r.data,code:u.invalid_enum_value,options:s}),h}return V(e.data)}get enum(){return this._def.values}};Ue.create=(t,e)=>new Ue({values:t,typeName:v.ZodNativeEnum,...S(e)});Ee=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 f(n,{code:u.invalid_type,expected:g.promise,received:n.parsedType}),h;let r=n.parsedType===g.promise?n.data:Promise.resolve(n.data);return V(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Ee.create=(t,e)=>new Ee({type:t,typeName:v.ZodPromise,...S(e)});ee=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=>{f(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 h;let c=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return c.status==="aborted"?h:c.status==="dirty"?Ae(c.value):n.value==="dirty"?Ae(c.value):c});{if(n.value==="aborted")return h;let i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?h:i.status==="dirty"?Ae(i.value):n.value==="dirty"?Ae(i.value):i}}if(s.type==="refinement"){let a=i=>{let c=s.refinement(i,o);if(r.common.async)return Promise.resolve(c);if(c 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"?h:(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"?h:(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(!ve(a))return h;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=>ve(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:n.value,value:i})):h);A.assertNever(s);}};ee.create=(t,e,n)=>new ee({schema:t,typeName:v.ZodEffects,effect:e,...S(n)});ee.createWithPreprocess=(t,e,n)=>new ee({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...S(n)});X=class extends w{_parse(e){return this._getType(e)===g.undefined?V(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};X.create=(t,e)=>new X({innerType:t,typeName:v.ZodOptional,...S(e)});ce=class extends w{_parse(e){return this._getType(e)===g.null?V(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ce.create=(t,e)=>new ce({innerType:t,typeName:v.ZodNullable,...S(e)});$e=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}};$e.create=(t,e)=>new $e({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});Me=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 Xe(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}};Me.create=(t,e)=>new Me({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});st=class extends w{_parse(e){if(this._getType(e)!==g.nan){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.nan,received:r.parsedType}),h}return {status:"valid",value:e.data}}};st.create=t=>new st({typeName:v.ZodNaN,...S(t)});xs=Symbol("zod_brand"),ht=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}},yt=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"?h:o.status==="dirty"?(n.dirty(),Ae(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"?h: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})}},Fe=class extends w{_parse(e){let n=this._def.innerType._parse(e),r=s=>(ve(s)&&(s.value=Object.freeze(s.value)),s);return Xe(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Fe.create=(t,e)=>new Fe({innerType:t,typeName:v.ZodReadonly,...S(e)});Rs={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={}));bs=(t,e={message:`Input not instance of ${t.name}`})=>er(n=>n instanceof t,e),tr=_e.create,nr=xe.create,Cs=st.create,Is=Re.create,rr=be.create,Ns=Ce.create,Os=et.create,Ds=Ie.create,Ps=Ne.create,Ls=ke.create,js=pe.create,Us=ne.create,$s=tt.create,Ms=fe.create,Fs=Z.create,Vs=Z.strictCreate,Bs=Oe.create,Hs=$t.create,zs=De.create,Ws=ae.create,Gs=Mt.create,Ys=nt.create,Zs=rt.create,Js=Ft.create,Ks=Pe.create,qs=Le.create,Xs=je.create,Qs=Ue.create,eo=Ee.create,to=ee.create,no=X.create,ro=ce.create,so=ee.createWithPreprocess,oo=yt.create,io=()=>tr().optional(),ao=()=>nr().optional(),co=()=>rr().optional(),lo={string:(t=>_e.create({...t,coerce:true})),number:(t=>xe.create({...t,coerce:true})),boolean:(t=>be.create({...t,coerce:true})),bigint:(t=>Re.create({...t,coerce:true})),date:(t=>Ce.create({...t,coerce:true}))},uo=h;});var p={};$n(p,{BRAND:()=>xs,DIRTY:()=>Ae,EMPTY_PATH:()=>ss,INVALID:()=>h,NEVER:()=>uo,OK:()=>V,ParseStatus:()=>M,Schema:()=>w,ZodAny:()=>ke,ZodArray:()=>fe,ZodBigInt:()=>Re,ZodBoolean:()=>be,ZodBranded:()=>ht,ZodCatch:()=>Me,ZodDate:()=>Ce,ZodDefault:()=>$e,ZodDiscriminatedUnion:()=>$t,ZodEffects:()=>ee,ZodEnum:()=>je,ZodError:()=>Y,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Ft,ZodIntersection:()=>De,ZodIssueCode:()=>u,ZodLazy:()=>Pe,ZodLiteral:()=>Le,ZodMap:()=>nt,ZodNaN:()=>st,ZodNativeEnum:()=>Ue,ZodNever:()=>ne,ZodNull:()=>Ne,ZodNullable:()=>ce,ZodNumber:()=>xe,ZodObject:()=>Z,ZodOptional:()=>X,ZodParsedType:()=>g,ZodPipeline:()=>yt,ZodPromise:()=>Ee,ZodReadonly:()=>Fe,ZodRecord:()=>Mt,ZodSchema:()=>w,ZodSet:()=>rt,ZodString:()=>_e,ZodSymbol:()=>et,ZodTransformer:()=>ee,ZodTuple:()=>ae,ZodType:()=>w,ZodUndefined:()=>Ie,ZodUnion:()=>Oe,ZodUnknown:()=>pe,ZodVoid:()=>tt,addIssueToContext:()=>f,any:()=>Ls,array:()=>Ms,bigint:()=>Is,boolean:()=>rr,coerce:()=>lo,custom:()=>er,date:()=>Ns,datetimeRegex:()=>Xn,defaultErrorMap:()=>ue,discriminatedUnion:()=>Hs,effect:()=>to,enum:()=>Xs,function:()=>Js,getErrorMap:()=>qe,getParsedType:()=>ie,instanceof:()=>bs,intersection:()=>zs,isAborted:()=>jt,isAsync:()=>Xe,isDirty:()=>Ut,isValid:()=>ve,late:()=>Rs,lazy:()=>Ks,literal:()=>qs,makeIssue:()=>mt,map:()=>Ys,nan:()=>Cs,nativeEnum:()=>Qs,never:()=>Us,null:()=>Ps,nullable:()=>ro,number:()=>nr,object:()=>Fs,objectUtil:()=>pn,oboolean:()=>co,onumber:()=>ao,optional:()=>no,ostring:()=>io,pipeline:()=>oo,preprocess:()=>so,promise:()=>eo,quotelessJson:()=>ts,record:()=>Gs,set:()=>Zs,setErrorMap:()=>rs,strictObject:()=>Vs,string:()=>tr,symbol:()=>Os,transformer:()=>to,tuple:()=>Ws,undefined:()=>Ds,union:()=>Bs,unknown:()=>js,util:()=>A,void:()=>$s});var yn=G(()=>{Lt();gn();Gn();gt();sr();Pt();});var or=G(()=>{yn();yn();});function go(){try{return fo.parse(process.env)}catch(t){if(t instanceof p.ZodError){let e=t.errors.map(n=>n.path.join(".")).join(", ");throw new Error(`Environment validation failed:
2
+ import {createRequire}from'module';import*as ne from'fs';import {existsSync,readFileSync,writeFileSync,statSync}from'fs';import*as Ye from'path';import {join,resolve,dirname}from'path';import {fileURLToPath}from'url';import {glob}from'glob';import*as ue from'crypto';import ue__default from'crypto';import y from'chalk';import {Command}from'commander';import ti from'ora';import ni from'cli-progress';import ri from'cli-table3';import*as it from'os';import {homedir}from'os';import*as U from'fs/promises';import Oi from'readline';import ji from'open';import {execSync}from'child_process';import Jr from'prompts';import Na from'omelette';createRequire(import.meta.url);
3
+ var Xr=Object.defineProperty;var G=(t,e)=>()=>(t&&(e=t(t=0)),e);var Vn=(t,e)=>{for(var n in e)Xr(t,n,{get:e[n],enumerable:true});};function ls(){let t=cs;for(;t!==dirname(t);){let e=join(t,"package.json");try{let n=JSON.parse(readFileSync(e,"utf-8"));if(n.name==="vee_stack")return n}catch{}t=dirname(t);}return null}var as,cs,un,ve,oe,H,dn,ie,qe,Pt,fn,gn=G(()=>{as=fileURLToPath(import.meta.url),cs=dirname(as);un=ls();if(!un)throw new Error("VeeStack Error: Root package.json not found. Ensure you are running from within the VeeStack monorepo.");ve=un.versions||{},oe=un.version,H=oe,dn=`vs_cli_v${oe}`,ie=ve.snapshot,qe=ve.engine_target,Pt=ve.audit,ve.session_payload,ve.rules,ve.analysis,fn=ve.api,ve.min_node;});var A,mn,g,ae,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;})(A||(A={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n});})(mn||(mn={}));g=A.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=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,gs,Y,Lt=G(()=>{mt();u=A.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"]),gs=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,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(n(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++;}}};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,A.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 ms,de,hn=G(()=>{Lt();mt();ms=(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,A.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:n=`Unrecognized key(s) in object: ${A.joinValues(t.keys,", ")}`;break;case u.invalid_union:n="Invalid input";break;case u.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${A.joinValues(t.options)}`;break;case u.invalid_enum_value:n=`Invalid enum value. Expected ${A.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}"`:A.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,A.assertNever(t);}return {message:n}},de=ms;});function hs(t){Zn=t;}function Xe(){return Zn}var Zn,jt=G(()=>{hn();Zn=de;});function f(t,e){let n=Xe(),r=ht({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===de?void 0:de].filter(s=>!!s)});t.common.issues.push(r);}var ht,ys,M,h,xe,V,Ut,$t,_e,Qe,yn=G(()=>{jt();hn();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="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)i=l(a,{data:e,defaultError:i}).message;return {...s,path:o,message:i}},ys=[];M=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 h;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 h;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}}},h=Object.freeze({status:"aborted"}),xe=t=>({status:"dirty",value:t}),V=t=>({status:"valid",value:t}),Ut=t=>t.status==="aborted",$t=t=>t.status==="dirty",_e=t=>t.status==="valid",Qe=t=>typeof Promise<"u"&&t instanceof Promise;});var Jn=G(()=>{});var m,Kn=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:c}=t;return a.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:c??n??i.defaultError}},description:s}}function er(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 Ps(t){return new RegExp(`^${er(t)}$`)}function tr(t){let e=`${Qn}T${er(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 Ls(t,e){return !!((e==="v4"||!e)&&Rs.test(t)||(e==="v6"||!e)&&Cs.test(t))}function js(t,e){if(!ws.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 Us(t,e){return !!((e==="v4"||!e)&&bs.test(t)||(e==="v6"||!e)&&Is.test(t))}function $s(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 et(t){if(t instanceof Z){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=X.create(et(r));}return new Z({...t._def,shape:()=>e})}else return t instanceof ge?new ge({...t._def,type:et(t.element)}):t instanceof X?X.create(et(t.unwrap())):t instanceof le?le.create(et(t.unwrap())):t instanceof ce?ce.create(t.items.map(e=>et(e))):t}function _n(t,e){let n=ae(t),r=ae(e);if(t===e)return {valid:true,data:t};if(n===g.object&&r===g.object){let s=A.objectKeys(e),o=A.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(let i of o){let c=_n(t[i],e[i]);if(!c.valid)return {valid:false};a[i]=c.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],c=_n(a,i);if(!c.valid)return {valid:false};s.push(c.data);}return {valid:true,data:s}}else return n===g.date&&r===g.date&&+t==+e?{valid:true,data:t}:{valid:false}}function nr(t,e){return new Ue({values:t,typeName:v.ZodEnum,...S(e)})}function Xn(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function rr(t,e={},n){return t?Ee.create().superRefine((r,s)=>{let o=t(r);if(o instanceof Promise)return o.then(a=>{if(!a){let i=Xn(e,r),c=i.fatal??n??true;s.addIssue({code:"custom",...i,fatal:c});}});if(!o){let a=Xn(e,r),i=a.fatal??n??true;s.addIssue({code:"custom",...a,fatal:i});}}):Ee.create()}var Q,qn,w,vs,_s,ks,Es,Ss,ws,Ts,As,xs,vn,Rs,bs,Cs,Is,Ns,Os,Qn,Ds,ke,Re,be,Ce,Ie,tt,Ne,Oe,Ee,fe,re,nt,ge,Z,De,pe,Mt,Pe,ce,Ft,rt,st,Vt,Le,je,Ue,$e,Se,ee,X,le,Me,Fe,ot,Ms,yt,vt,Ve,Fs,v,Vs,sr,or,Bs,Hs,ir,zs,Ws,Gs,Ys,Zs,Js,Ks,qs,Xs,Qs,eo,to,no,ro,so,oo,io,ao,co,lo,uo,po,fo,go,mo,ho,yo,vo,_o,ko,Eo,So,wo,To,ar=G(()=>{Lt();jt();Kn();yn();mt();Q=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}},qn=(t,e)=>{if(_e(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 ae(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Qe(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:ae(e)},s=this._parseSync({data:e,path:r.path,parent:r});return qn(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return _e(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=>_e(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:ae(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(Qe(s)?s:Promise.resolve(s));return qn(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(c=>c?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 ee({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 X.create(this,this._def)}nullable(){return le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ge.create(this)}promise(){return Se.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Pe.create(this,e,this._def)}transform(e){return new ee({...S(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Me({...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 Fe({...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 Ve.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vs=/^c[^\s-]{8,}$/i,_s=/^[0-9a-z]+$/,ks=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Es=/^[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,Ss=/^[a-z0-9_-]{21}$/i,ws=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ts=/^[-+]?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)?)??$/,As=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Rs=/^(?:(?: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])$/,bs=/^(?:(?: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])$/,Cs=/^(([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]))$/,Is=/^(([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])$/,Ns=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Os=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qn="((\\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])))",Ds=new RegExp(`^${Qn}$`);ke=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 f(o,{code:u.invalid_type,expected:g.string,received:o.parsedType}),h}let r=new M,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),f(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),f(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?f(s,{code:u.too_big,maximum:o.value,type:"string",inclusive:true,exact:true,message:o.message}):i&&f(s,{code:u.too_small,minimum:o.value,type:"string",inclusive:true,exact:true,message:o.message}),r.dirty());}else if(o.kind==="email")As.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"email",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")vn||(vn=new RegExp(xs,"u")),vn.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"emoji",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Es.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"uuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Ss.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"nanoid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")vs.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")_s.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid2",code:u.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")ks.test(e.data)||(s=this._getOrReturnCtx(e,s),f(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),f(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),f(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),f(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),f(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),f(s,{code:u.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?tr(o).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:u.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Ds.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:u.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Ps(o).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:u.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Ts.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"duration",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ls(e.data,o.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ip",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?js(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"jwt",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Us(e.data,o.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cidr",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Ns.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64",code:u.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Os.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64url",code:u.invalid_string,message:o.message}),r.dirty()):A.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}};ke.create=t=>new ke({checks:[],typeName:v.ZodString,coerce:t?.coerce??false,...S(t)});Re=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 f(o,{code:u.invalid_type,expected:g.number,received:o.parsedType}),h}let r,s=new M;for(let o of this._def.checks)o.kind==="int"?A.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),f(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),f(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),f(r,{code:u.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),s.dirty()):o.kind==="multipleOf"?$s(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),f(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),f(r,{code:u.not_finite,message:o.message}),s.dirty()):A.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"&&A.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)}};Re.create=t=>new Re({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||false,...S(t)});be=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 M;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),f(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),f(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),f(r,{code:u.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):A.assertNever(o);return {status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:g.bigint,received:n.parsedType}),h}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}};be.create=t=>new be({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??false,...S(t)});Ce=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.boolean,received:r.parsedType}),h}return V(e.data)}};Ce.create=t=>new Ce({typeName:v.ZodBoolean,coerce:t?.coerce||false,...S(t)});Ie=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 f(o,{code:u.invalid_type,expected:g.date,received:o.parsedType}),h}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return f(o,{code:u.invalid_date}),h}let r=new M,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),f(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),f(s,{code:u.too_big,message:o.message,inclusive:true,exact:false,maximum:o.value,type:"date"}),r.dirty()):A.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}};Ie.create=t=>new Ie({checks:[],coerce:t?.coerce||false,typeName:v.ZodDate,...S(t)});tt=class extends w{_parse(e){if(this._getType(e)!==g.symbol){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.symbol,received:r.parsedType}),h}return V(e.data)}};tt.create=t=>new tt({typeName:v.ZodSymbol,...S(t)});Ne=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.undefined,received:r.parsedType}),h}return V(e.data)}};Ne.create=t=>new Ne({typeName:v.ZodUndefined,...S(t)});Oe=class extends w{_parse(e){if(this._getType(e)!==g.null){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.null,received:r.parsedType}),h}return V(e.data)}};Oe.create=t=>new Oe({typeName:v.ZodNull,...S(t)});Ee=class extends w{constructor(){super(...arguments),this._any=true;}_parse(e){return V(e.data)}};Ee.create=t=>new Ee({typeName:v.ZodAny,...S(t)});fe=class extends w{constructor(){super(...arguments),this._unknown=true;}_parse(e){return V(e.data)}};fe.create=t=>new fe({typeName:v.ZodUnknown,...S(t)});re=class extends w{_parse(e){let n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:g.never,received:n.parsedType}),h}};re.create=t=>new re({typeName:v.ZodNever,...S(t)});nt=class extends w{_parse(e){if(this._getType(e)!==g.undefined){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.void,received:r.parsedType}),h}return V(e.data)}};nt.create=t=>new nt({typeName:v.ZodVoid,...S(t)});ge=class t extends w{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==g.array)return f(n,{code:u.invalid_type,expected:g.array,received:n.parsedType}),h;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,i=n.data.length<s.exactLength.value;(a||i)&&(f(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&&(f(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&&(f(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 Q(n,a,n.path,i)))).then(a=>M.mergeArray(r,a));let o=[...n.data].map((a,i)=>s.type._parseSync(new Q(n,a,n.path,i)));return M.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)}};ge.create=(t,e)=>new ge({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=A.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==g.object){let l=this._getOrReturnCtx(e);return f(l,{code:u.invalid_type,expected:g.object,received:l.parsedType}),h}let{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof re&&this._def.unknownKeys==="strip"))for(let l in s.data)a.includes(l)||i.push(l);let c=[];for(let l of a){let d=o[l],T=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Q(s,T,s.path,l)),alwaysSet:l in s.data});}if(this._def.catchall instanceof re){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of i)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")i.length>0&&(f(s,{code:u.unrecognized_keys,keys:i}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let l=this._def.catchall;for(let d of i){let T=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Q(s,T,s.path,d)),alwaysSet:d in s.data});}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let T=await d.key,b=await d.value;l.push({key:T,value:b,alwaysSet:d.alwaysSet});}return l}).then(l=>M.mergeObjectSync(r,l)):M.mergeObjectSync(r,c)}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 A.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 A.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return et(this)}partial(e){let n={};for(let r of A.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 A.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else {let o=this.shape[r];for(;o instanceof X;)o=o._def.innerType;n[r]=o;}return new t({...this._def,shape:()=>n})}keyof(){return nr(A.objectKeys(this.shape))}};Z.create=(t,e)=>new Z({shape:()=>t,unknownKeys:"strip",catchall:re.create(),typeName:v.ZodObject,...S(e)});Z.strictCreate=(t,e)=>new Z({shape:()=>t,unknownKeys:"strict",catchall:re.create(),typeName:v.ZodObject,...S(e)});Z.lazycreate=(t,e)=>new Z({shape:t,unknownKeys:"strip",catchall:re.create(),typeName:v.ZodObject,...S(e)});De=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 f(n,{code:u.invalid_union,unionErrors:a}),h}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 c of r){let l={...n,common:{...n.common,issues:[]},parent:null},d=c._parseSync({data:n.data,path:n.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues);}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(c=>new Y(c));return f(n,{code:u.invalid_union,unionErrors:i}),h}}get options(){return this._def.options}};De.create=(t,e)=>new De({options:t,typeName:v.ZodUnion,...S(e)});pe=t=>t instanceof Le?pe(t.schema):t instanceof ee?pe(t.innerType()):t instanceof je?[t.value]:t instanceof Ue?t.options:t instanceof $e?A.objectValues(t.enum):t instanceof Me?pe(t._def.innerType):t instanceof Ne?[void 0]:t instanceof Oe?[null]:t instanceof X?[void 0,...pe(t.unwrap())]:t instanceof le?[null,...pe(t.unwrap())]:t instanceof yt||t instanceof Ve?pe(t.unwrap()):t instanceof Fe?pe(t._def.innerType):[],Mt=class t extends w{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==g.object)return f(n,{code:u.invalid_type,expected:g.object,received:n.parsedType}),h;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}):(f(n,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),h)}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=pe(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)})}};Pe=class extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(o,a)=>{if(Ut(o)||Ut(a))return h;let i=_n(o.value,a.value);return i.valid?(($t(o)||$t(a))&&n.dirty(),{status:n.value,value:i.data}):(f(r,{code:u.invalid_intersection_types}),h)};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}))}};Pe.create=(t,e,n)=>new Pe({left:t,right:e,typeName:v.ZodIntersection,...S(n)});ce=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.array)return f(r,{code:u.invalid_type,expected:g.array,received:r.parsedType}),h;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),h;!this._def.rest&&r.data.length>this._def.items.length&&(f(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 c=this._def.items[i]||this._def.rest;return c?c._parse(new Q(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>M.mergeArray(n,a)):M.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ce.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ce({items:t,typeName:v.ZodTuple,rest:null,...S(e)})};Ft=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 f(r,{code:u.invalid_type,expected:g.object,received:r.parsedType}),h;let s=[],o=this._def.keyType,a=this._def.valueType;for(let i in r.data)s.push({key:o._parse(new Q(r,i,r.path,i)),value:a._parse(new Q(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?M.mergeObjectAsync(n,s):M.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:ke.create(),valueType:e,typeName:v.ZodRecord,...S(n)})}},rt=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 f(r,{code:u.invalid_type,expected:g.map,received:r.parsedType}),h;let s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([i,c],l)=>({key:s._parse(new Q(r,i,r.path,[l,"key"])),value:o._parse(new Q(r,c,r.path,[l,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return h;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),i.set(l.value,d.value);}return {status:n.value,value:i}})}else {let i=new Map;for(let c of a){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return h;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),i.set(l.value,d.value);}return {status:n.value,value:i}}}};rt.create=(t,e,n)=>new rt({valueType:e,keyType:t,typeName:v.ZodMap,...S(n)});st=class t extends w{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.set)return f(r,{code:u.invalid_type,expected:g.set,received:r.parsedType}),h;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(f(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&&(f(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(c){let l=new Set;for(let d of c){if(d.status==="aborted")return h;d.status==="dirty"&&n.dirty(),l.add(d.value);}return {status:n.value,value:l}}let i=[...r.data.values()].map((c,l)=>o._parse(new Q(r,c,r.path,l)));return r.common.async?Promise.all(i).then(c=>a(c)):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)}};st.create=(t,e)=>new st({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...S(e)});Vt=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 f(n,{code:u.invalid_type,expected:g.function,received:n.parsedType}),h;function r(i,c){return ht({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xe(),de].filter(l=>!!l),issueData:{code:u.invalid_arguments,argumentsError:c}})}function s(i,c){return ht({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xe(),de].filter(l=>!!l),issueData:{code:u.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Se){let i=this;return V(async function(...c){let l=new Y([]),d=await i._def.args.parseAsync(c,o).catch(j=>{throw l.addIssue(r(c,j)),l}),T=await Reflect.apply(a,this,d);return await i._def.returns._def.type.parseAsync(T,o).catch(j=>{throw l.addIssue(s(T,j)),l})})}else {let i=this;return V(function(...c){let l=i._def.args.safeParse(c,o);if(!l.success)throw new Y([r(c,l.error)]);let d=Reflect.apply(a,this,l.data),T=i._def.returns.safeParse(d,o);if(!T.success)throw new Y([s(d,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ce.create(e).rest(fe.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||ce.create([]).rest(fe.create()),returns:n||fe.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)});je=class extends w{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return f(n,{received:n.data,code:u.invalid_literal,expected:this._def.value}),h}return {status:"valid",value:e.data}}get value(){return this._def.value}};je.create=(t,e)=>new je({value:t,typeName:v.ZodLiteral,...S(e)});Ue=class t extends w{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return f(n,{expected:A.joinValues(r),received:n.parsedType,code:u.invalid_type}),h}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 f(n,{received:n.data,code:u.invalid_enum_value,options:r}),h}return V(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})}};Ue.create=nr;$e=class extends w{_parse(e){let n=A.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==g.string&&r.parsedType!==g.number){let s=A.objectValues(n);return f(r,{expected:A.joinValues(s),received:r.parsedType,code:u.invalid_type}),h}if(this._cache||(this._cache=new Set(A.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=A.objectValues(n);return f(r,{received:r.data,code:u.invalid_enum_value,options:s}),h}return V(e.data)}get enum(){return this._def.values}};$e.create=(t,e)=>new $e({values:t,typeName:v.ZodNativeEnum,...S(e)});Se=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 f(n,{code:u.invalid_type,expected:g.promise,received:n.parsedType}),h;let r=n.parsedType===g.promise?n.data:Promise.resolve(n.data);return V(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Se.create=(t,e)=>new Se({type:t,typeName:v.ZodPromise,...S(e)});ee=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=>{f(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 h;let c=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return c.status==="aborted"?h:c.status==="dirty"?xe(c.value):n.value==="dirty"?xe(c.value):c});{if(n.value==="aborted")return h;let i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?h:i.status==="dirty"?xe(i.value):n.value==="dirty"?xe(i.value):i}}if(s.type==="refinement"){let a=i=>{let c=s.refinement(i,o);if(r.common.async)return Promise.resolve(c);if(c 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"?h:(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"?h:(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(!_e(a))return h;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=>_e(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:n.value,value:i})):h);A.assertNever(s);}};ee.create=(t,e,n)=>new ee({schema:t,typeName:v.ZodEffects,effect:e,...S(n)});ee.createWithPreprocess=(t,e,n)=>new ee({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...S(n)});X=class extends w{_parse(e){return this._getType(e)===g.undefined?V(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};X.create=(t,e)=>new X({innerType:t,typeName:v.ZodOptional,...S(e)});le=class extends w{_parse(e){return this._getType(e)===g.null?V(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};le.create=(t,e)=>new le({innerType:t,typeName:v.ZodNullable,...S(e)});Me=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}};Me.create=(t,e)=>new Me({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});Fe=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 Qe(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}};Fe.create=(t,e)=>new Fe({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});ot=class extends w{_parse(e){if(this._getType(e)!==g.nan){let r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:g.nan,received:r.parsedType}),h}return {status:"valid",value:e.data}}};ot.create=t=>new ot({typeName:v.ZodNaN,...S(t)});Ms=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"?h:o.status==="dirty"?(n.dirty(),xe(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"?h: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})}},Ve=class extends w{_parse(e){let n=this._def.innerType._parse(e),r=s=>(_e(s)&&(s.value=Object.freeze(s.value)),s);return Qe(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Ve.create=(t,e)=>new Ve({innerType:t,typeName:v.ZodReadonly,...S(e)});Fs={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={}));Vs=(t,e={message:`Input not instance of ${t.name}`})=>rr(n=>n instanceof t,e),sr=ke.create,or=Re.create,Bs=ot.create,Hs=be.create,ir=Ce.create,zs=Ie.create,Ws=tt.create,Gs=Ne.create,Ys=Oe.create,Zs=Ee.create,Js=fe.create,Ks=re.create,qs=nt.create,Xs=ge.create,Qs=Z.create,eo=Z.strictCreate,to=De.create,no=Mt.create,ro=Pe.create,so=ce.create,oo=Ft.create,io=rt.create,ao=st.create,co=Vt.create,lo=Le.create,uo=je.create,po=Ue.create,fo=$e.create,go=Se.create,mo=ee.create,ho=X.create,yo=le.create,vo=ee.createWithPreprocess,_o=vt.create,ko=()=>sr().optional(),Eo=()=>or().optional(),So=()=>ir().optional(),wo={string:(t=>ke.create({...t,coerce:true})),number:(t=>Re.create({...t,coerce:true})),boolean:(t=>Ce.create({...t,coerce:true})),bigint:(t=>be.create({...t,coerce:true})),date:(t=>Ie.create({...t,coerce:true}))},To=h;});var p={};Vn(p,{BRAND:()=>Ms,DIRTY:()=>xe,EMPTY_PATH:()=>ys,INVALID:()=>h,NEVER:()=>To,OK:()=>V,ParseStatus:()=>M,Schema:()=>w,ZodAny:()=>Ee,ZodArray:()=>ge,ZodBigInt:()=>be,ZodBoolean:()=>Ce,ZodBranded:()=>yt,ZodCatch:()=>Fe,ZodDate:()=>Ie,ZodDefault:()=>Me,ZodDiscriminatedUnion:()=>Mt,ZodEffects:()=>ee,ZodEnum:()=>Ue,ZodError:()=>Y,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Vt,ZodIntersection:()=>Pe,ZodIssueCode:()=>u,ZodLazy:()=>Le,ZodLiteral:()=>je,ZodMap:()=>rt,ZodNaN:()=>ot,ZodNativeEnum:()=>$e,ZodNever:()=>re,ZodNull:()=>Oe,ZodNullable:()=>le,ZodNumber:()=>Re,ZodObject:()=>Z,ZodOptional:()=>X,ZodParsedType:()=>g,ZodPipeline:()=>vt,ZodPromise:()=>Se,ZodReadonly:()=>Ve,ZodRecord:()=>Ft,ZodSchema:()=>w,ZodSet:()=>st,ZodString:()=>ke,ZodSymbol:()=>tt,ZodTransformer:()=>ee,ZodTuple:()=>ce,ZodType:()=>w,ZodUndefined:()=>Ne,ZodUnion:()=>De,ZodUnknown:()=>fe,ZodVoid:()=>nt,addIssueToContext:()=>f,any:()=>Zs,array:()=>Xs,bigint:()=>Hs,boolean:()=>ir,coerce:()=>wo,custom:()=>rr,date:()=>zs,datetimeRegex:()=>tr,defaultErrorMap:()=>de,discriminatedUnion:()=>no,effect:()=>mo,enum:()=>po,function:()=>co,getErrorMap:()=>Xe,getParsedType:()=>ae,instanceof:()=>Vs,intersection:()=>ro,isAborted:()=>Ut,isAsync:()=>Qe,isDirty:()=>$t,isValid:()=>_e,late:()=>Fs,lazy:()=>lo,literal:()=>uo,makeIssue:()=>ht,map:()=>io,nan:()=>Bs,nativeEnum:()=>fo,never:()=>Ks,null:()=>Ys,nullable:()=>yo,number:()=>or,object:()=>Qs,objectUtil:()=>mn,oboolean:()=>So,onumber:()=>Eo,optional:()=>ho,ostring:()=>ko,pipeline:()=>_o,preprocess:()=>vo,promise:()=>go,quotelessJson:()=>gs,record:()=>oo,set:()=>ao,setErrorMap:()=>hs,strictObject:()=>eo,string:()=>sr,symbol:()=>Ws,transformer:()=>mo,tuple:()=>so,undefined:()=>Gs,union:()=>to,unknown:()=>Js,util:()=>A,void:()=>qs});var kn=G(()=>{jt();yn();Jn();mt();ar();Lt();});var cr=G(()=>{kn();kn();});function Ro(){try{return xo.parse(process.env)}catch(t){if(t instanceof p.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 mo(){return vn||(vn=go()),vn}function ho(t=po.api.rateLimit){let{windowMs:e,maxRequests:n,message:r}=t;return {check(s){let o=Date.now(),a=Ve.get(s);a&&o>a.resetTime&&Ve.delete(s);let i=Ve.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++,Ve.set(s,i),{success:true,remaining:n-i.count,resetTime:i.resetTime})},reset(s){Ve.delete(s);},cleanup(){let s=Date.now();for(let[o,a]of Ve.entries())s>a.resetTime&&Ve.delete(o);}}}var po,fo,vn,k,ir,Vt,E,Ve,re=G(()=>{dn();dn();or();po={versions:{cli:ye,engine:ye,frontend:ye,api:un,snapshot:oe,engine_target:Ke},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:oe,engineTargetVersion:Ke},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}},p.object({snapshot_version:p.string(),engine_target_version:p.string(),project_id:p.string(),generated_at:p.string(),root_path_hash:p.string(),metadata:p.object({total_files:p.number().int().nonnegative(),total_dependencies:p.number().int().nonnegative(),total_size_bytes:p.number().int().nonnegative(),total_lines:p.number().int().nonnegative(),max_directory_depth:p.number().int().nonnegative(),language_breakdown:p.record(p.string(),p.number().int().nonnegative())}),files:p.array(p.object({id:p.string(),path_hash:p.string(),depth:p.number().int().nonnegative(),size_bytes:p.number().int().nonnegative(),estimated_lines:p.number().int().nonnegative(),extension:p.string(),is_binary:p.boolean(),import_count:p.number().int().nonnegative().optional(),function_count:p.number().int().nonnegative().optional(),class_count:p.number().int().nonnegative().optional()})),dependencies:p.array(p.object({id:p.string(),name_hash:p.string(),major_version:p.number().int().nonnegative(),minor_version:p.number().int().nonnegative(),category:p.enum(["dev","prod","peer"])}))}),p.object({name:p.string().min(1).max(100)}),p.object({analysis_version:p.string(),snapshot_schema_version:p.string(),total_score:p.number().min(0).max(100),severity_band:p.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),engines:p.array(p.object({engine_name:p.string(),score_impact:p.number(),risk_level:p.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),metrics:p.record(p.number()),findings:p.array(p.object({rule_id:p.string(),title:p.string(),message:p.string(),severity:p.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:p.enum(["SECURITY","STRUCTURE","COMPLEXITY","DEPENDENCY","REPOSITORY_HYGIENE","DOCUMENTATION","QUALITY"]),evidence:p.array(p.string()).optional(),explanation:p.string().optional(),impact:p.string().optional(),effort:p.enum(["Low","Medium","High"]).optional(),recommendations:p.array(p.string()).optional()}))})),summary:p.object({total_findings:p.number().int().nonnegative(),critical_count:p.number().int().nonnegative(),high_count:p.number().int().nonnegative(),medium_count:p.number().int().nonnegative(),low_count:p.number().int().nonnegative(),categories:p.record(p.string(),p.number().int().nonnegative())}),generated_at:p.string()}),fo=p.object({NEXT_PUBLIC_SUPABASE_URL:p.string().url("Invalid SUPABASE_URL"),NEXT_PUBLIC_SUPABASE_ANON_KEY:p.string().min(1,"SUPABASE_ANON_KEY is required"),SUPABASE_SERVICE_ROLE_KEY:p.string().min(1,"SERVICE_ROLE_KEY is required"),NODE_ENV:p.enum(["development","production","test"],{errorMap:()=>({message:"NODE_ENV must be development, production, or test"})}),JWT_SECRET:p.string().min(32,"JWT_SECRET must be at least 32 characters").optional()});vn=null;new Proxy({},{get(t,e){return mo()[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"}},ir={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},{[ir.FREE]:k.plans.FREE,[ir.PRO]:k.plans.PRO},Vt={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},{[Vt.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],[Vt.SUPPORT]:[E.READ_ALL,E.PROJECT_READ,E.SNAPSHOT_READ,E.REPORT_READ,E.USER_READ,E.SUPPORT_ACCESS,E.SUPPORT_VIEW_TICKETS],[Vt.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],[Vt.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}},Ve=new Map;ho();});var tn,nn,Er=G(()=>{tn={BASE_SCORE:100,MIN_SCORE:0,MAX_SCORE:100},nn={HEALTHY:{min:90,max:100},STABLE:{min:75,max:89},STRUCTURAL_CONCERN:{min:60,max:74},HIGH_RISK:{min:0,max:59}};});var Rn={};$n(Rn,{CoreEngine:()=>Xo,ProjectScanner:()=>br,RULES:()=>gi,ReportGenerator:()=>Rr,RuleRegistry:()=>Ar,ScoringEngine:()=>xr,SnapshotValidator:()=>Tr,scanProject:()=>yi});async function yi(t,e,n){return new br({projectPath:t,...n}).scan(e)}var Sr,Tr,Ar,xr,Rr,Xo,Qo,ei,ti,ni,ri,si,oi,ii,ai,ci,li,ui,di,pi,fi,gi,br,bn=G(()=>{Er();re();re();Sr=(t=>typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>e[n]}):t)(function(t){throw Error('Dynamic require of "'+t+'" is not supported')}),Tr=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}}},Ar=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}},xr=class{calculateScore(t){let e=tn.BASE_SCORE;for(let n of t)e-=n.weight;return Math.max(tn.MIN_SCORE,Math.min(tn.MAX_SCORE,e))}getSeverityBand(t){return t>=nn.HEALTHY.min?"HEALTHY":t>=nn.STABLE.min?"STABLE":t>=nn.STRUCTURAL_CONCERN.min?"STRUCTURAL_CONCERN":"HIGH_RISK"}},Rr=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:oe,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"}},Xo=class{validator;ruleRegistry;scoringEngine;reportGenerator;constructor(){this.validator=new Tr,this.ruleRegistry=new Ar,this.scoringEngine=new xr,this.reportGenerator=new Rr;}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)}}},Qo={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}},ei={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}},ti={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},ni={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},ri={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 l of t.files){if(l.is_binary||e.some(j=>j.test(l.path)))continue;let T=l.extension.toLowerCase(),b=n[T]||n.default;l.estimated_lines>b.critical?r.push({path:l.path,lines:l.estimated_lines,threshold:b.critical,level:"critical"}):l.estimated_lines>b.warning&&r.push({path:l.path,lines:l.estimated_lines,threshold:b.warning,level:"warning"});}if(r.length===0)return null;let s=r.filter(l=>l.level==="critical"),o=r.filter(l=>l.level==="warning"),a,i,c;if(s.length>0){i="HIGH";let l=s.slice(0,3).map(d=>`${d.path} (${d.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.`,c=l;}else {i="MEDIUM";let l=o.slice(0,3).map(d=>`${d.path} (${d.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.`,c=l;}return {rule_id:"RULE_005",title:"Large File Detected",message:a,severity:i,category:"COMPLEXITY",evidence:c.length>0?c: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"]}}},si={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},oi={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"]}},ii={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"]}},ai={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}},ci={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}},li={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}},ui={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"]}},di={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}},pi={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}},fi={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=Sr("fs"),i=Sr("path"),c=t.project_root?i.join(t.project_root,s.path):s.path,l=a.readFileSync(c,"utf-8");for(let d of n){let T=l.matchAll(d.pattern);for(let b of T){let j=b[0].replace(/["']([^"']{4,})["']/g,'"****"');r.push({file:s.path,type:d.name,severity:d.severity,masked:j});}}}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=[Qo,ei,ti,ni,ri,si,oi,ii,ai,ci,li,ui,di,pi,fi],br=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(c=>{let l=this.extractASTTokens(c.content,c.extension);return {path_hash:this.hash(c.path),content_hash:this.hash(c.content),extension:c.extension,size_bytes:c.size,ast_tokens:l.slice(0,500),raw_content:this.options.includeRawContent?c.content:void 0}}),i={framework:r,language:s,total_files:e.length,total_dependencies:n.length,file_types:this.calculateFileTypes(e)};return {version:oe,project_id:le__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 c=i+1;if(s.forEach(T=>{let b=new RegExp(`\\b${T}\\b`,"g"),j;for(;(j=b.exec(a))!==null;)n.push({type:"keyword",value:T,line:c,column:j.index+1});}),o.forEach(T=>{let b=new RegExp(`${T.replace(".","\\.")}\\s*\\(`,"g"),j;for(;(j=b.exec(a))!==null;)n.push({type:"call_expression",value:T,line:c,column:j.index+1});}),e==="tsx"||e==="jsx"){let T=/<[A-Z][a-zA-Z0-9]*/g,b;for(;(b=T.exec(a))!==null;)n.push({type:"jsx_element",value:b[0].substring(1),line:c,column:b.index+1});a.includes("dangerouslySetInnerHTML")&&n.push({type:"property_access",value:"dangerouslySetInnerHTML",line:c,column:a.indexOf("dangerouslySetInnerHTML")+1});}let l=/['"]([^'"]*)['"]/g,d;for(;(d=l.exec(a))!==null;){let T=d[1];(T.includes(".env")||T.includes(".pem")||T.includes(".key"))&&n.push({type:"string",value:T,line:c,column:d.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 c=i.match(/^(\d+)\.(\d+)/),l=c?parseInt(c[1]):0;t.push({name_hash:this.hash(a),version:i.replace(/[^\d.]/g,""),major_version:l,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 le__default.createHash("sha256").update(t).digest("hex")}};});var Kr=[/^--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],Ze=/vs_[a-zA-Z0-9_-]{20,}/i;function Mn(){let t=process.argv.slice(2);for(let e of t){for(let n of Kr)n.test(e)&&(console.error(y.red(`
5
+ Please check your .env file and ensure all required variables are set.`)}throw t}}function bo(){return En||(En=Ro()),En}function Co(t=Ao.api.rateLimit){let{windowMs:e,maxRequests:n,message:r}=t;return {check(s){let o=Date.now(),a=Be.get(s);a&&o>a.resetTime&&Be.delete(s);let i=Be.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++,Be.set(s,i),{success:true,remaining:n-i.count,resetTime:i.resetTime})},reset(s){Be.delete(s);},cleanup(){let s=Date.now();for(let[o,a]of Be.entries())s>a.resetTime&&Be.delete(o);}}}var Ao,xo,En,k,lr,Bt,E,Be,te=G(()=>{gn();gn();cr();Ao={versions:{cli:oe,engine:oe,frontend:oe,api:fn,snapshot:ie,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:ie,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}},p.object({snapshot_version:p.string(),engine_target_version:p.string(),project_id:p.string(),generated_at:p.string(),root_path_hash:p.string(),metadata:p.object({total_files:p.number().int().nonnegative(),total_dependencies:p.number().int().nonnegative(),total_size_bytes:p.number().int().nonnegative(),total_lines:p.number().int().nonnegative(),max_directory_depth:p.number().int().nonnegative(),language_breakdown:p.record(p.string(),p.number().int().nonnegative())}),files:p.array(p.object({id:p.string(),path_hash:p.string(),depth:p.number().int().nonnegative(),size_bytes:p.number().int().nonnegative(),estimated_lines:p.number().int().nonnegative(),extension:p.string(),is_binary:p.boolean(),import_count:p.number().int().nonnegative().optional(),function_count:p.number().int().nonnegative().optional(),class_count:p.number().int().nonnegative().optional()})),dependencies:p.array(p.object({id:p.string(),name_hash:p.string(),major_version:p.number().int().nonnegative(),minor_version:p.number().int().nonnegative(),category:p.enum(["dev","prod","peer"])}))}),p.object({name:p.string().min(1).max(100)}),p.object({analysis_version:p.string(),snapshot_schema_version:p.string(),total_score:p.number().min(0).max(100),severity_band:p.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),engines:p.array(p.object({engine_name:p.string(),score_impact:p.number(),risk_level:p.enum(["HEALTHY","STABLE","STRUCTURAL_CONCERN","HIGH_RISK"]),metrics:p.record(p.number()),findings:p.array(p.object({rule_id:p.string(),title:p.string(),message:p.string(),severity:p.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:p.enum(["SECURITY","STRUCTURE","COMPLEXITY","DEPENDENCY","REPOSITORY_HYGIENE","DOCUMENTATION","QUALITY"]),evidence:p.array(p.string()).optional(),explanation:p.string().optional(),impact:p.string().optional(),effort:p.enum(["Low","Medium","High"]).optional(),recommendations:p.array(p.string()).optional()}))})),summary:p.object({total_findings:p.number().int().nonnegative(),critical_count:p.number().int().nonnegative(),high_count:p.number().int().nonnegative(),medium_count:p.number().int().nonnegative(),low_count:p.number().int().nonnegative(),categories:p.record(p.string(),p.number().int().nonnegative())}),generated_at:p.string()}),xo=p.object({NEXT_PUBLIC_SUPABASE_URL:p.string().url("Invalid SUPABASE_URL"),NEXT_PUBLIC_SUPABASE_ANON_KEY:p.string().min(1,"SUPABASE_ANON_KEY is required"),SUPABASE_SERVICE_ROLE_KEY:p.string().min(1,"SERVICE_ROLE_KEY is required"),NODE_ENV:p.enum(["development","production","test"],{errorMap:()=>({message:"NODE_ENV must be development, production, or test"})}),JWT_SECRET:p.string().min(32,"JWT_SECRET must be at least 32 characters").optional()});En=null;new Proxy({},{get(t,e){return bo()[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"}},lr={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},{[lr.FREE]:k.plans.FREE,[lr.PRO]:k.plans.PRO},Bt={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},{[Bt.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],[Bt.SUPPORT]:[E.READ_ALL,E.PROJECT_READ,E.SNAPSHOT_READ,E.REPORT_READ,E.USER_READ,E.SUPPORT_ACCESS,E.SUPPORT_VIEW_TICKETS],[Bt.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],[Bt.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}},Be=new Map;Co();});var nn,rn,Tr=G(()=>{nn={BASE_SCORE:100,MIN_SCORE:0,MAX_SCORE:100},rn={HEALTHY:{min:90,max:100},STABLE:{min:75,max:89},STRUCTURAL_CONCERN:{min:60,max:74},HIGH_RISK:{min:0,max:59}};});var In={};Vn(In,{CoreEngine:()=>di,ProjectScanner:()=>Nr,RULES:()=>Ri,ReportGenerator:()=>Ir,RuleRegistry:()=>br,ScoringEngine:()=>Cr,SnapshotValidator:()=>Rr,scanProject:()=>Ii});async function Ii(t,e,n){return new Nr({projectPath:t,...n}).scan(e)}var Ar,Rr,br,Cr,Ir,di,pi,fi,gi,mi,hi,yi,vi,_i,ki,Ei,Si,wi,Ti,Ai,xi,Ri,Nr,Nn=G(()=>{Tr();te();te();Ar=(t=>typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>e[n]}):t)(function(t){throw Error('Dynamic require of "'+t+'" is not supported')}),Rr=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}}},br=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}},Cr=class{calculateScore(t){let e=nn.BASE_SCORE;for(let n of t)e-=n.weight;return Math.max(nn.MIN_SCORE,Math.min(nn.MAX_SCORE,e))}getSeverityBand(t){return t>=rn.HEALTHY.min?"HEALTHY":t>=rn.STABLE.min?"STABLE":t>=rn.STRUCTURAL_CONCERN.min?"STRUCTURAL_CONCERN":"HIGH_RISK"}},Ir=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:ie,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"}},di=class{validator;ruleRegistry;scoringEngine;reportGenerator;constructor(){this.validator=new Rr,this.ruleRegistry=new br,this.scoringEngine=new Cr,this.reportGenerator=new Ir;}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)}}},pi={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}},fi={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}},gi={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},mi={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},hi={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 l of t.files){if(l.is_binary||e.some(j=>j.test(l.path)))continue;let T=l.extension.toLowerCase(),b=n[T]||n.default;l.estimated_lines>b.critical?r.push({path:l.path,lines:l.estimated_lines,threshold:b.critical,level:"critical"}):l.estimated_lines>b.warning&&r.push({path:l.path,lines:l.estimated_lines,threshold:b.warning,level:"warning"});}if(r.length===0)return null;let s=r.filter(l=>l.level==="critical"),o=r.filter(l=>l.level==="warning"),a,i,c;if(s.length>0){i="HIGH";let l=s.slice(0,3).map(d=>`${d.path} (${d.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.`,c=l;}else {i="MEDIUM";let l=o.slice(0,3).map(d=>`${d.path} (${d.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.`,c=l;}return {rule_id:"RULE_005",title:"Large File Detected",message:a,severity:i,category:"COMPLEXITY",evidence:c.length>0?c: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"]}}},yi={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},vi={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"]}},ki={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}},Ei={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}},Si={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}},wi={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"]}},Ti={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}},Ai={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}},xi={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=Ar("fs"),i=Ar("path"),c=t.project_root?i.join(t.project_root,s.path):s.path,l=a.readFileSync(c,"utf-8");for(let d of n){let T=l.matchAll(d.pattern);for(let b of T){let j=b[0].replace(/["']([^"']{4,})["']/g,'"****"');r.push({file:s.path,type:d.name,severity:d.severity,masked:j});}}}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}},Ri=[pi,fi,gi,mi,hi,yi,vi,_i,ki,Ei,Si,wi,Ti,Ai,xi],Nr=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(c=>{let l=this.extractASTTokens(c.content,c.extension);return {path_hash:this.hash(c.path),content_hash:this.hash(c.content),extension:c.extension,size_bytes:c.size,ast_tokens:l.slice(0,500),raw_content:this.options.includeRawContent?c.content:void 0}}),i={framework:r,language:s,total_files:e.length,total_dependencies:n.length,file_types:this.calculateFileTypes(e)};return {version:ie,project_id:ue__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 c=i+1;if(s.forEach(T=>{let b=new RegExp(`\\b${T}\\b`,"g"),j;for(;(j=b.exec(a))!==null;)n.push({type:"keyword",value:T,line:c,column:j.index+1});}),o.forEach(T=>{let b=new RegExp(`${T.replace(".","\\.")}\\s*\\(`,"g"),j;for(;(j=b.exec(a))!==null;)n.push({type:"call_expression",value:T,line:c,column:j.index+1});}),e==="tsx"||e==="jsx"){let T=/<[A-Z][a-zA-Z0-9]*/g,b;for(;(b=T.exec(a))!==null;)n.push({type:"jsx_element",value:b[0].substring(1),line:c,column:b.index+1});a.includes("dangerouslySetInnerHTML")&&n.push({type:"property_access",value:"dangerouslySetInnerHTML",line:c,column:a.indexOf("dangerouslySetInnerHTML")+1});}let l=/['"]([^'"]*)['"]/g,d;for(;(d=l.exec(a))!==null;){let T=d[1];(T.includes(".env")||T.includes(".pem")||T.includes(".key"))&&n.push({type:"string",value:T,line:c,column:d.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 c=i.match(/^(\d+)\.(\d+)/),l=c?parseInt(c[1]):0;t.push({name_hash:this.hash(a),version:i.replace(/[^\d.]/g,""),major_version:l,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 ue__default.createHash("sha256").update(t).digest("hex")}};});var Qr=[/^--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],Je=/vs_[a-zA-Z0-9_-]{20,}/i;function Bn(){let t=process.argv.slice(2);for(let e of t){for(let n of Qr)n.test(e)&&(console.error(y.red(`
7
7
  \u274C Security Error: Token detected in command line arguments`)),console.error(y.yellow(`
8
8
  Passing tokens via CLI arguments is not allowed.`)),console.error(y.yellow("This prevents tokens from being saved in shell history (~/.bash_history, ~/.zsh_history)")),console.error(y.gray(`
9
9
  Instead, use:`)),console.error(y.cyan(" veestack login")),console.error(y.gray(`
10
10
  Or set via environment variable:`)),console.error(y.cyan(" export VEESTACK_API_KEY=your_key")),console.error(y.gray(`
11
11
  Your token has been detected and blocked for your security.
12
- `)),process.exit(1));Ze.test(e)&&(console.error(y.red(`
12
+ `)),process.exit(1));Je.test(e)&&(console.error(y.red(`
13
13
  \u274C Security Error: VeeStack token detected in command line`)),console.error(y.yellow(`
14
14
  Tokens should never be passed as command arguments.`)),console.error(y.gray(`
15
- Use login instead:`)),console.error(y.cyan(" veestack login")),process.exit(1));}}function Fn(){for(let t=0;t<process.argv.length;t++){let e=process.argv[t];Ze.test(e)&&(process.argv[t]="[REDACTED_TOKEN]"),/authorization[:\s]/i.test(e)&&(process.argv[t]="[REDACTED_AUTH_HEADER]");}}function Vn(){let t=console.error,e=console.log,n=console.warn,r=s=>s.map(o=>typeof o=="string"?o.replace(Ze,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]"):o);console.log=(...s)=>e(...r(s)),console.error=(...s)=>t(...r(s)),console.warn=(...s)=>n(...r(s));}function Bn(){process.on("uncaughtException",t=>{console.error(`
16
- \u274C Fatal Error occurred`);let e=t.message||"Unknown error";if(e=e.replace(Ze,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]").replace(/Authorization[:\s][^\s]*/gi,"Authorization: [REDACTED]"),console.error(`Error: ${e}`),t.stack){let n=t.stack.split(`
17
- `).map(r=>r.replace(Ze,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]")).join(`
15
+ Use login instead:`)),console.error(y.cyan(" veestack login")),process.exit(1));}}function Hn(){for(let t=0;t<process.argv.length;t++){let e=process.argv[t];Je.test(e)&&(process.argv[t]="[REDACTED_TOKEN]"),/authorization[:\s]/i.test(e)&&(process.argv[t]="[REDACTED_AUTH_HEADER]");}}function zn(){let t=console.error,e=console.log,n=console.warn,r=s=>s.map(o=>typeof o=="string"?o.replace(Je,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]"):o);console.log=(...s)=>e(...r(s)),console.error=(...s)=>t(...r(s)),console.warn=(...s)=>n(...r(s));}function Wn(){process.on("uncaughtException",t=>{console.error(`
16
+ \u274C Fatal Error occurred`);let e=t.message||"Unknown error";if(e=e.replace(Je,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]").replace(/Authorization[:\s][^\s]*/gi,"Authorization: [REDACTED]"),console.error(`Error: ${e}`),t.stack){let n=t.stack.split(`
17
+ `).map(r=>r.replace(Je,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]")).join(`
18
18
  `);process.env.DEBUG||process.env.VEESTACK_DEBUG?console.error(`
19
19
  Stack trace:`,n):console.error(`
20
20
  Run with DEBUG=veestack for full stack trace (sanitized)`);}process.exit(1);}),process.on("unhandledRejection",t=>{let e=t instanceof Error?t:new Error(String(t));console.error(`
21
- \u274C Unhandled Promise Rejection`);let n=e.message||"Unknown error";n=n.replace(Ze,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]"),console.error(`Error: ${n}`),process.exit(1);});}var Je=["veestack-tools","@vee_stack/cli"],Xr=["veestack","veestack-cli","veestacktool","veestack-tool","vee-stack","veestack-cli-tool","veestack-scanner","veestack-analyzer"],Qr=[/veestak/i,/veestac/i,/veestackk/i,/veestackh/i,/vvestack/i,/veee/i,/veestack-cli-hack/i,/veestack-free/i,/veestack-pro-free/i];function Hn(){try{let t=fileURLToPath(import.meta.url),n=Ge.dirname(t);for(let r=0;r<5;r++){let s=Ge.join(n,"package.json");if(te.existsSync(s))return JSON.parse(te.readFileSync(s,"utf-8")).name||"unknown";let o=Ge.dirname(n);if(o===n)break;n=o;}}catch{}return "unknown"}function es(){let t=Hn(),e=[];if(Je.includes(t))return {isOfficial:true,warnings:[]};if(Xr.includes(t))return e.push(`\u26A0\uFE0F WARNING: You are using "${t}" which is NOT the official VeeStack CLI.`),e.push(`The official package is: ${y.cyan(Je[0])}`),e.push("Unofficial packages may contain malware or steal your data."),{isOfficial:false,warnings:e};for(let n of Qr)if(n.test(t))return e.push(`\u26A0\uFE0F WARNING: Package name "${t}" looks suspicious.`),e.push("This might be a typosquatting attack."),e.push(`The official package is: ${y.cyan(Je[0])}`),{isOfficial:false,warnings:e};return e.push(`\u26A0\uFE0F WARNING: Unofficial package "${t}" detected.`),e.push(`The official package is: ${y.cyan(Je[0])}`),{isOfficial:false,warnings:e}}function zn(){let{isOfficial:t,warnings:e}=es();if(!t){console.log(y.red(`
21
+ \u274C Unhandled Promise Rejection`);let n=e.message||"Unknown error";n=n.replace(Je,"[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_-]+/gi,"Bearer [REDACTED]"),console.error(`Error: ${n}`),process.exit(1);});}var Ke=["veestack-tools","@vee_stack/cli"],ts=["veestack","veestack-cli","veestacktool","veestack-tool","vee-stack","veestack-cli-tool","veestack-scanner","veestack-analyzer"],ns=[/veestak/i,/veestac/i,/veestackk/i,/veestackh/i,/vvestack/i,/veee/i,/veestack-cli-hack/i,/veestack-free/i,/veestack-pro-free/i];function Gn(){try{let t=fileURLToPath(import.meta.url),n=Ye.dirname(t);for(let r=0;r<5;r++){let s=Ye.join(n,"package.json");if(ne.existsSync(s))return JSON.parse(ne.readFileSync(s,"utf-8")).name||"unknown";let o=Ye.dirname(n);if(o===n)break;n=o;}}catch{}return "unknown"}function rs(){let t=Gn(),e=[];if(Ke.includes(t))return {isOfficial:true,warnings:[]};if(ts.includes(t))return e.push(`\u26A0\uFE0F WARNING: You are using "${t}" which is NOT the official VeeStack CLI.`),e.push(`The official package is: ${y.cyan(Ke[0])}`),e.push("Unofficial packages may contain malware or steal your data."),{isOfficial:false,warnings:e};for(let n of ns)if(n.test(t))return e.push(`\u26A0\uFE0F WARNING: Package name "${t}" looks suspicious.`),e.push("This might be a typosquatting attack."),e.push(`The official package is: ${y.cyan(Ke[0])}`),{isOfficial:false,warnings:e};return e.push(`\u26A0\uFE0F WARNING: Unofficial package "${t}" detected.`),e.push(`The official package is: ${y.cyan(Ke[0])}`),{isOfficial:false,warnings:e}}function Yn(){let{isOfficial:t,warnings:e}=rs();if(!t){console.log(y.red(`
22
22
  `+"\u2550".repeat(60))),console.log(y.red.bold(`\u{1F6A8} SECURITY WARNING
23
23
  `));for(let n of e)console.log(y.yellow(n));console.log(y.gray(`
24
24
  To install the official CLI:`)),console.log(y.cyan(" npm install -g veestack-tools")),console.log(y.red("\u2550".repeat(60)+`
25
- `)),process.exit(1);}process.env.VEESTACK_DEBUG==="true"&&console.log(y.gray(`\u2713 Official package verified: ${Je.join(" or ")}`));}function Ot(){let t=Hn(),e=Je.includes(t);return {packageName:t,isOfficial:e,homepage:"https://veestack.tools",repository:"https://github.com/Mohmed-ElZehiry/VeeStack"}}re();re();re();var yo={TOKEN_BINDING_SALT:cn};function ar(t,e){let n=`${t}:${e}:${yo.TOKEN_BINDING_SALT}`;return le.createHash("sha256").update(n).digest("hex")}function cr(t,e,n,r,s="cli"){let o=new Date().toISOString(),a=Eo(),i=vo(t,e,n,o,a),c=_o(o,s,i),l=ko(r,o,s,c);return {signature:l,timestamp:o,nonce:a,headers:{"X-Signature":l,"X-Timestamp":o,"X-Nonce":a,"X-Signed-Headers":"host;x-timestamp;x-nonce"}}}function vo(t,e,n,r,s){let o=le.createHash("sha256").update(n).digest("hex");return [t.toUpperCase(),e,"",`host:api.veestack.tools
25
+ `)),process.exit(1);}process.env.VEESTACK_DEBUG==="true"&&console.log(y.gray(`\u2713 Official package verified: ${Ke.join(" or ")}`));}function Dt(){let t=Gn(),e=Ke.includes(t);return {packageName:t,isOfficial:e,homepage:"https://veestack.tools",repository:"https://github.com/Mohmed-ElZehiry/VeeStack"}}te();te();te();var Io={TOKEN_BINDING_SALT:dn};function ur(t,e){let n=`${t}:${e}:${Io.TOKEN_BINDING_SALT}`;return ue.createHash("sha256").update(n).digest("hex")}function dr(t,e,n,r,s="cli"){let o=new Date().toISOString(),a=Po(),i=No(t,e,n,o,a),c=Oo(o,s,i),l=Do(r,o,s,c);return {signature:l,timestamp:o,nonce:a,headers:{"X-Signature":l,"X-Timestamp":o,"X-Nonce":a,"X-Signed-Headers":"host;x-timestamp;x-nonce"}}}function No(t,e,n,r,s){let o=ue.createHash("sha256").update(n).digest("hex");return [t.toUpperCase(),e,"",`host:api.veestack.tools
26
26
  `,`x-timestamp:${r}
27
27
  `,`x-nonce:${s}
28
28
  `,"host;x-timestamp;x-nonce",o].join(`
29
- `)}function _o(t,e,n){let r=t.substring(0,10).replace(/-/g,""),s=le.createHash("sha256").update(n).digest("hex");return ["VEESTACK-HMAC-SHA256",t,`${r}/veestack/${e}/veestack_request`,s].join(`
30
- `)}function ko(t,e,n,r){let s=e.substring(0,10).replace(/-/g,""),o=_t("VEESTACK"+t,s),a=_t(o,"veestack"),i=_t(a,n),c=_t(i,"veestack_request");return _t(c,r,"hex")}function _t(t,e,n){return le.createHmac("sha256",t).update(e).digest(n||"hex")}function Eo(){return le.randomBytes(16).toString("hex")}var Bt=null;async function zt(){if(Bt)return Bt;try{return Bt=await import('keytar'),Bt}catch{return null}}var St=Ge.join(ot.homedir(),".veestack"),ge=Ge.join(St,"tokens.enc"),lr=Ge.join(St,"salt"),ur=Ge.join(St,".key"),Wt="VeeStack CLI",Gt="auth_tokens",So=1e5,wo=32,To=16;function Ht(){return process.env.DEBUG?.includes("veestack")||process.env.DEBUG?.includes("*")||process.env.NODE_ENV==="development"||process.env.VEESTACK_DEBUG==="true"}async function Ao(){try{let e=await U.readFile(lr).catch(()=>null);if(e)return e}catch{}let t=le.randomBytes(32);return await U.mkdir(St,{recursive:true,mode:448}),await U.writeFile(lr,t,{mode:384}),t}async function dr(){try{let r=await U.readFile(ur,"utf-8").catch(()=>null);if(r){let s=Buffer.from(r,"hex");return await U.unlink(ur).catch(()=>{}),s}}catch{}let t=`${ot.userInfo().username}@${ot.hostname()}`,e=await Ao();return le.pbkdf2Sync(t,e,So,wo,"sha256")}function kt(t){Buffer.isBuffer(t)&&t.fill(0);}async function wt(t){let e=await zt();if(e)try{let l=JSON.stringify(t);await e.setPassword(Wt,Gt,l),Ht()&&console.log(" Tokens saved to OS Keychain");return}catch(l){Ht()&&console.log(" Keychain failed, falling back to encrypted file:",l);}let n=await dr(),r=le.randomBytes(To),s=le.createCipheriv("aes-256-gcm",n,r),o=JSON.stringify(t),a=Buffer.concat([s.update(o,"utf8"),s.final()]),i=s.getAuthTag(),c={iv:r.toString("hex"),data:a.toString("hex"),authTag:i.toString("hex"),timestamp:Date.now(),version:2};await U.mkdir(St,{recursive:true,mode:448}),await U.writeFile(ge,JSON.stringify(c),{mode:384}),kt(n),Ht()&&console.log(" Tokens saved to encrypted file (AES-256-GCM)");}async function pr(){let t=await zt();if(t)try{let e=await t.getPassword(Wt,Gt);if(e)return JSON.parse(e)}catch(e){Ht()&&console.log("\u26A0\uFE0F Keychain read failed, trying encrypted file:",e);}try{let e=await U.readFile(ge,"utf-8"),n=JSON.parse(e);if(n.version===1)return await xo(n);let r=await dr(),s=null;try{let o=Buffer.from(n.iv,"hex"),a=Buffer.from(n.data,"hex"),i=Buffer.from(n.authTag,"hex"),c=le.createDecipheriv("aes-256-gcm",r,o);c.setAuthTag(i),s=Buffer.concat([c.update(a),c.final()]);let l=JSON.parse(s.toString("utf8"));return kt(s),kt(r),l}catch(o){throw s&&kt(s),kt(r),o}}catch{return null}}async function xo(t){try{return console.log("\u{1F510} Migrating from legacy encryption format..."),await U.unlink(ge).catch(()=>{}),null}catch{return null}}async function Yt(){try{return await U.access(ge),!0}catch{return false}}async function Be(){try{let t=await U.stat(ge).catch(()=>null);if(!t)return;let e=t.size,n=3;for(let s=0;s<n;s++){let o=le.randomBytes(e);await U.writeFile(ge,o);}await U.unlink(ge);let r=await zt();r&&await r.deletePassword(Wt,Gt).catch(()=>{});}catch{}}async function fr(){let t=await zt(),e=!!t,n=false;if(t)try{n=!!await t.getPassword(Wt,Gt);}catch{}let r=false,s,o,a=0;try{let i=await U.stat(ge);r=!0,s=i.mode.toString(8),o=i.size;let c=await U.readFile(ge,"utf-8");a=JSON.parse(c).version||1;}catch{}return {keychainAvailable:e,keychainHasTokens:n,fileExists:r,filePermissions:s,fileSize:o,encryptionVersion:a}}var Ro=[{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 He(t){if(!t||typeof t!="string")return t;let e=t;for(let n of Ro)e=e.replace(n.regex,n.replacement);return e}function _n(t){return t instanceof Error?He(t.message).slice(0,500):typeof t=="string"?He(t).slice(0,500):He(String(t)).slice(0,500)}function Zt(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=>Zt(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]=Zt(s):typeof s=="string"?n[r]=He(s):n[r]=s;}return n}function Tt(t,e,...n){let r=He(e),s=n.map(o=>typeof o=="string"?He(o):typeof o=="object"&&o!==null?Zt(o):o);console[t](r,...s);}var me={log:(t,...e)=>Tt("log",t,...e),error:(t,...e)=>Tt("error",t,...e),warn:(t,...e)=>Tt("warn",t,...e),info:(t,...e)=>Tt("info",t,...e),debug:(t,...e)=>Tt("debug",t,...e)};var kn=Ge.join(ot.homedir(),".veestack");Ge.join(kn,"config.json");var Jt=Ge.join(kn,"config.json"),bo=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function Io(){try{if(!te.existsSync(Jt))return;let t=te.readFileSync(Jt,"utf-8"),e=JSON.parse(t);if(await Yt()){try{te.unlinkSync(Jt);}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 wt(n);try{te.unlinkSync(Jt);}catch{}me.info("\u{1F510} Authentication migrated to encrypted storage");}catch{}}async function K(){await Io();let t=await pr();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 At(){let t=await K();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 No(){let t=await K();return t&&(t.token||t.apiKey)||null}async function Oo(){let t=await K();return {id:t?.device?.id,fingerprint:t?.device?.fingerprint}}async function qt(t="GET",e="",n="",r=["project:read"]){let s=await No();if(!s)return {};let o=await K(),a=await Oo();if(!a.id||!a.fingerprint||!o?.refreshToken)return {};let i=ar(o.refreshToken,a.fingerprint),c=cr(t,e,n,o.refreshToken,"cli");return {Authorization:`Bearer ${s}`,"Content-Type":"application/json","X-Device-ID":a.id,"X-CLI-Version":H,"X-Device-Fingerprint":a.fingerprint,"X-Token-Binding":i,"X-Signature":c.signature,"X-Timestamp":c.timestamp,"X-Nonce":c.nonce,"X-Scope":r.join(","),"X-Security-Version":H}}function En(t){if(!t.tokenExpiresAt)return true;let e=new Date(t.tokenExpiresAt),n=300*1e3;return Date.now()>=e.getTime()-n}async function Do(t){if(!t.refreshToken)return null;try{let e=await fetch(`${bo}/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 Be(),console.log(y.red(`
29
+ `)}function Oo(t,e,n){let r=t.substring(0,10).replace(/-/g,""),s=ue.createHash("sha256").update(n).digest("hex");return ["VEESTACK-HMAC-SHA256",t,`${r}/veestack/${e}/veestack_request`,s].join(`
30
+ `)}function Do(t,e,n,r){let s=e.substring(0,10).replace(/-/g,""),o=kt("VEESTACK"+t,s),a=kt(o,"veestack"),i=kt(a,n),c=kt(i,"veestack_request");return kt(c,r,"hex")}function kt(t,e,n){return ue.createHmac("sha256",t).update(e).digest(n||"hex")}function Po(){return ue.randomBytes(16).toString("hex")}var Ht=null;async function Wt(){if(Ht)return Ht;try{return Ht=await import('keytar'),Ht}catch{return null}}var wt=Ye.join(it.homedir(),".veestack"),me=Ye.join(wt,"tokens.enc"),pr=Ye.join(wt,"salt"),fr=Ye.join(wt,".key"),Gt="VeeStack CLI",Yt="auth_tokens",Lo=1e5,jo=32,Uo=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 $o(){try{let e=await U.readFile(pr).catch(()=>null);if(e)return e}catch{}let t=ue.randomBytes(32);return await U.mkdir(wt,{recursive:true,mode:448}),await U.writeFile(pr,t,{mode:384}),t}async function gr(){try{let r=await U.readFile(fr,"utf-8").catch(()=>null);if(r){let s=Buffer.from(r,"hex");return await U.unlink(fr).catch(()=>{}),s}}catch{}let t=`${it.userInfo().username}@${it.hostname()}`,e=await $o();return ue.pbkdf2Sync(t,e,Lo,jo,"sha256")}function Et(t){Buffer.isBuffer(t)&&t.fill(0);}async function Tt(t){let e=await Wt();if(e)try{let l=JSON.stringify(t);await e.setPassword(Gt,Yt,l),zt()&&console.log(" Tokens saved to OS Keychain");return}catch(l){zt()&&console.log(" Keychain failed, falling back to encrypted file:",l);}let n=await gr(),r=ue.randomBytes(Uo),s=ue.createCipheriv("aes-256-gcm",n,r),o=JSON.stringify(t),a=Buffer.concat([s.update(o,"utf8"),s.final()]),i=s.getAuthTag(),c={iv:r.toString("hex"),data:a.toString("hex"),authTag:i.toString("hex"),timestamp:Date.now(),version:2};await U.mkdir(wt,{recursive:true,mode:448}),await U.writeFile(me,JSON.stringify(c),{mode:384}),Et(n),zt()&&console.log(" Tokens saved to encrypted file (AES-256-GCM)");}async function mr(){let t=await Wt();if(t)try{let e=await t.getPassword(Gt,Yt);if(e)return JSON.parse(e)}catch(e){zt()&&console.log("\u26A0\uFE0F Keychain read failed, trying encrypted file:",e);}try{let e=await U.readFile(me,"utf-8"),n=JSON.parse(e);if(n.version===1)return await Mo(n);let r=await gr(),s=null;try{let o=Buffer.from(n.iv,"hex"),a=Buffer.from(n.data,"hex"),i=Buffer.from(n.authTag,"hex"),c=ue.createDecipheriv("aes-256-gcm",r,o);c.setAuthTag(i),s=Buffer.concat([c.update(a),c.final()]);let l=JSON.parse(s.toString("utf8"));return Et(s),Et(r),l}catch(o){throw s&&Et(s),Et(r),o}}catch{return null}}async function Mo(t){try{return console.log("\u{1F510} Migrating from legacy encryption format..."),await U.unlink(me).catch(()=>{}),null}catch{return null}}async function Zt(){try{return await U.access(me),!0}catch{return false}}async function He(){try{let t=await U.stat(me).catch(()=>null);if(!t)return;let e=t.size,n=3;for(let s=0;s<n;s++){let o=ue.randomBytes(e);await U.writeFile(me,o);}await U.unlink(me);let r=await Wt();r&&await r.deletePassword(Gt,Yt).catch(()=>{});}catch{}}async function hr(){let t=await Wt(),e=!!t,n=false;if(t)try{n=!!await t.getPassword(Gt,Yt);}catch{}let r=false,s,o,a=0;try{let i=await U.stat(me);r=!0,s=i.mode.toString(8),o=i.size;let c=await U.readFile(me,"utf-8");a=JSON.parse(c).version||1;}catch{}return {keychainAvailable:e,keychainHasTokens:n,fileExists:r,filePermissions:s,fileSize:o,encryptionVersion:a}}var Fo=[{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 ze(t){if(!t||typeof t!="string")return t;let e=t;for(let n of Fo)e=e.replace(n.regex,n.replacement);return e}function Sn(t){return t instanceof Error?ze(t.message).slice(0,500):typeof t=="string"?ze(t).slice(0,500):ze(String(t)).slice(0,500)}function Jt(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=>Jt(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]=Jt(s):typeof s=="string"?n[r]=ze(s):n[r]=s;}return n}function At(t,e,...n){let r=ze(e),s=n.map(o=>typeof o=="string"?ze(o):typeof o=="object"&&o!==null?Jt(o):o);console[t](r,...s);}var he={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 wn=Ye.join(it.homedir(),".veestack");Ye.join(wn,"config.json");var Kt=Ye.join(wn,"config.json"),Vo=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function Ho(){try{if(!ne.existsSync(Kt))return;let t=ne.readFileSync(Kt,"utf-8"),e=JSON.parse(t);if(await Zt()){try{ne.unlinkSync(Kt);}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 Tt(n);try{ne.unlinkSync(Kt);}catch{}he.info("\u{1F510} Authentication migrated to encrypted storage");}catch{}}async function K(){await Ho();let t=await mr();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 xt(){let t=await K();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 zo(){let t=await K();return t&&(t.token||t.apiKey)||null}async function Wo(){let t=await K();return {id:t?.device?.id,fingerprint:t?.device?.fingerprint}}async function Xt(t="GET",e="",n="",r=["project:read"]){let s=await zo();if(!s)return {};let o=await K(),a=await Wo();if(!a.id||!a.fingerprint||!o?.refreshToken)return {};let i=ur(o.refreshToken,a.fingerprint),c=dr(t,e,n,o.refreshToken,"cli");return {Authorization:`Bearer ${s}`,"Content-Type":"application/json","X-Device-ID":a.id,"X-CLI-Version":H,"X-Device-Fingerprint":a.fingerprint,"X-Token-Binding":i,"X-Signature":c.signature,"X-Timestamp":c.timestamp,"X-Nonce":c.nonce,"X-Scope":r.join(","),"X-Security-Version":H}}function Tn(t){if(!t.tokenExpiresAt)return true;let e=new Date(t.tokenExpiresAt),n=300*1e3;return Date.now()>=e.getTime()-n}async function Go(t){if(!t.refreshToken)return null;try{let e=await fetch(`${Vo}/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 He(),console.log(y.red(`
31
31
  \u274C Security Alert: Device mismatch`)),console.log(y.yellow(`
32
- Your token was used from a different device.`)),console.log(y.gray("This could indicate a token theft attempt.")),console.log(y.gray("Please login again:")),console.log(y.cyan(" veestack login")),process.exit(1)),s.code==="device_revoked"&&(await Be(),console.log(y.red(`
32
+ Your token was used from a different device.`)),console.log(y.gray("This could indicate a token theft attempt.")),console.log(y.gray("Please login again:")),console.log(y.cyan(" veestack login")),process.exit(1)),s.code==="device_revoked"&&(await He(),console.log(y.red(`
33
33
  \u274C Device authorization revoked`)),console.log(y.yellow(`
34
- Your device was removed from authorized devices.`)),console.log(y.gray("Please login again:")),console.log(y.cyan(" veestack login")),process.exit(1)),(s.code==="token_invalid"||s.code==="session_expired")&&(await Be(),console.log(y.red(`
34
+ Your device was removed from authorized devices.`)),console.log(y.gray("Please login again:")),console.log(y.cyan(" veestack login")),process.exit(1)),(s.code==="token_invalid"||s.code==="session_expired")&&(await He(),console.log(y.red(`
35
35
  \u274C Session expired`)),console.log(y.yellow(`
36
- Your session has expired or your password was changed.`)),console.log(y.gray("Please login again:")),console.log(y.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 wt({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")&&(me.warn(`
37
- \u26A0\uFE0F Network error`),me.info("Could not connect to authentication server."),me.info("Please check your connection and try again.")),null}}async function we(){let t=await K();if(!t)return console.log(y.yellow(`
36
+ Your session has expired or your password was changed.`)),console.log(y.gray("Please login again:")),console.log(y.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 Tt({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")&&(he.warn(`
37
+ \u26A0\uFE0F Network error`),he.info("Could not connect to authentication server."),he.info("Please check your connection and try again.")),null}}async function Te(){let t=await K();if(!t)return console.log(y.yellow(`
38
38
  \u26A0\uFE0F You are not logged in`)),console.log(y.gray(`
39
39
  Login to enable:`)),console.log(y.gray(" \u2022 Cloud reports")),console.log(y.gray(" \u2022 Team dashboard")),console.log(y.gray(` \u2022 Historical scans
40
- `)),console.log(y.gray("Run:")),console.log(y.cyan(" veestack login")),null;if(t.refreshToken&&En(t)){console.log(y.yellow("Token expired, refreshing..."));let e=await Do(t);return e?(console.log(y.green("\u2713 Token refreshed")),e):(await Be(),console.log(y.red(`
41
- \u274C Session expired`)),console.log(y.yellow("Your refresh token has expired.")),console.log(y.gray("Run: veestack login")),null)}return t}async function it(){let t=await K();return !t||!t.subscription?"free":t.subscription.tier}async function hr(){let t=await K();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 yr(t){if(t.user)try{let e=join(kn,"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{}}var Po=[".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"],Lo=["veestack.config.json","package.json","tsconfig.json","jsconfig.json",".eslintrc.json",".prettierrc.json","README.md"],jo=[{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 vr(t){let e=t.replace(/\\/g,"/").toLowerCase(),n=Ge.basename(e);for(let r of Lo)if(n===r.toLowerCase())return false;for(let r of Po){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 Uo(t,e){let n=[],r=e.split(`
42
- `);for(let s of jo){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 $o(t){let e=[];if(vr(t))return e.push({filePath:t,type:"sensitive_file",secretName:"Sensitive File",severity:"critical",description:`Sensitive file type detected: ${Ge.basename(t)}`}),e;try{if(te.statSync(t).size>1024*1024)return e;let r=te.readFileSync(t,"utf-8"),s=Uo(t,r);e.push(...s);}catch{}return e}async function _r(t,e){let n=[];for(let i of e){let c=Ge.join(t,i),l=await $o(c);for(let d of l)d.filePath=i,n.push(d);}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 Sn(t){if(t.secretsFound===0)return y.green("\u2713 No secrets detected");let e=`
40
+ `)),console.log(y.gray("Run:")),console.log(y.cyan(" veestack login")),null;if(t.refreshToken&&Tn(t)){console.log(y.yellow("Token expired, refreshing..."));let e=await Go(t);return e?(console.log(y.green("\u2713 Token refreshed")),e):(await He(),console.log(y.red(`
41
+ \u274C Session expired`)),console.log(y.yellow("Your refresh token has expired.")),console.log(y.gray("Run: veestack login")),null)}return t}async function at(){let t=await K();return !t||!t.subscription?"free":t.subscription.tier}async function _r(){let t=await K();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 kr(t){if(t.user)try{let e=join(wn,"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{}}var Yo=[".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"],Zo=["veestack.config.json","package.json","tsconfig.json","jsconfig.json",".eslintrc.json",".prettierrc.json","README.md"],Jo=[{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 Er(t){let e=t.replace(/\\/g,"/").toLowerCase(),n=Ye.basename(e);for(let r of Zo)if(n===r.toLowerCase())return false;for(let r of Yo){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 Ko(t,e){let n=[],r=e.split(`
42
+ `);for(let s of Jo){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 qo(t){let e=[];if(Er(t))return e.push({filePath:t,type:"sensitive_file",secretName:"Sensitive File",severity:"critical",description:`Sensitive file type detected: ${Ye.basename(t)}`}),e;try{if(ne.statSync(t).size>1024*1024)return e;let r=ne.readFileSync(t,"utf-8"),s=Ko(t,r);e.push(...s);}catch{}return e}async function Sr(t,e){let n=[];for(let i of e){let c=Ye.join(t,i),l=await qo(c);for(let d of l)d.filePath=i,n.push(d);}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 An(t){if(t.secretsFound===0)return y.green("\u2713 No secrets detected");let e=`
43
43
  `+y.red(`\u26A0\uFE0F Secrets Detected!
44
44
  `);e+=y.gray(`Found ${t.secretsFound} potential secret(s) in ${t.totalFiles} files
45
45
 
@@ -57,118 +57,118 @@ Login to enable:`)),console.log(y.gray(" \u2022 Cloud reports")),console.log(y.
57
57
  `);for(let o of s)e+=` ${y.blue("\u2022")} ${y.white(o.filePath)}
58
58
  `,e+=` ${y.gray(o.description)}
59
59
  `;e+=`
60
- `;}return e}function kr(t){let e=[],n=[];for(let r of t)vr(r)?n.push(r):e.push(r);return {safe:e,blocked:n}}re();function Wo(t,e){t.metadata.total_files;let r=25,s=15,o=5,a=2,i=0,c={critical:0,high:0,medium:0,low:0};e&&(c.critical=e.criticalCount||0,c.high=e.highCount||0,c.medium=e.mediumCount||0,c.low=e.lowCount||0,i+=c.critical*r,i+=c.high*s,i+=c.medium*o,i+=c.low*a);let l=100-i;l<0&&(l=0);let d="A+";return l===100?d="A+":l>=90?d="A":l>=80?d="B":l>=70?d="C":l>=60?d="D":d="F",{score:l,grade:d,breakdown:c}}async function Tn(t){let e=await we(),n=e!==null;if(n){console.log(y.blue(`
61
- \u{1F510} Authenticated mode`)),e?.user&&console.log(y.gray(`User: ${e.user.name}`));let s=await it();console.log(y.gray(`Tier: ${s==="pro"?"Pro":"Free"}`));}else console.log(y.gray(`
60
+ `;}return e}function wr(t){let e=[],n=[];for(let r of t)Er(r)?n.push(r):e.push(r);return {safe:e,blocked:n}}te();function si(t,e){t.metadata.total_files;let r=25,s=15,o=5,a=2,i=0,c={critical:0,high:0,medium:0,low:0};e&&(c.critical=e.criticalCount||0,c.high=e.highCount||0,c.medium=e.mediumCount||0,c.low=e.lowCount||0,i+=c.critical*r,i+=c.high*s,i+=c.medium*o,i+=c.low*a);let l=100-i;l<0&&(l=0);let d="A+";return l===100?d="A+":l>=90?d="A":l>=80?d="B":l>=70?d="C":l>=60?d="D":d="F",{score:l,grade:d,breakdown:c}}async function Rn(t){let e=await Te(),n=e!==null;if(n){console.log(y.blue(`
61
+ \u{1F510} Authenticated mode`)),e?.user&&console.log(y.gray(`User: ${e.user.name}`));let s=await at();console.log(y.gray(`Tier: ${s==="pro"?"Pro":"Free"}`));}else console.log(y.gray(`
62
62
  \u{1F4C1} Local scan mode`)),console.log(y.gray(`Results will not be uploaded.
63
63
  `)),console.log(y.gray("Login to enable:")),console.log(y.gray(" \u2022 Cloud reports")),console.log(y.gray(" \u2022 Team dashboard")),console.log(y.gray(` \u2022 Historical tracking
64
64
  `));console.log(y.gray("\u2500".repeat(40)+`
65
- `));let r=Bo({text:"Scanning project...",spinner:"dots",stream:process.stdout}).start();try{let s=Date.now(),o=await Yo(t.path),a=o.map(L=>L.path),i=new Ho.SingleBar({format:"Scanning |"+y.cyan("{bar}")+"| {percentage}% ({value}/{total} files)",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});console.log(y.gray("Analyzing project files...")),i.start(a.length,0),r.text="Scanning for secrets...";let c=await _r(t.path,a);i.update(Math.floor(a.length*.5)),c.criticalCount>0&&(i.stop(),r.fail("Security scan failed"),console.log(Sn(c)),console.log(y.red(`
65
+ `));let r=ti({text:"Scanning project...",spinner:"dots",stream:process.stdout}).start();try{let s=Date.now(),o=await ii(t.path),a=o.map(L=>L.path),i=new ni.SingleBar({format:"Scanning |"+y.cyan("{bar}")+"| {percentage}% ({value}/{total} files)",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});console.log(y.gray("Analyzing project files...")),i.start(a.length,0),r.text="Scanning for secrets...";let c=await Sr(t.path,a);i.update(Math.floor(a.length*.5)),c.criticalCount>0&&(i.stop(),r.fail("Security scan failed"),console.log(An(c)),console.log(y.red(`
66
66
  \u274C Critical secrets detected!`)),console.log(y.yellow(`Upload blocked to protect sensitive data.
67
67
  `)),console.log(y.gray("To override (not recommended):")),console.log(y.gray(` --skip-secret-scan (requires explicit confirmation)
68
- `)),process.exit(1)),c.secretsFound>0&&(console.log(Sn(c)),console.log(y.yellow(`
68
+ `)),process.exit(1)),c.secretsFound>0&&(console.log(An(c)),console.log(y.yellow(`
69
69
  \u26A0\uFE0F Warning: Potential secrets detected`)),console.log(y.gray(`These files will be excluded from the snapshot:
70
- `)));let{safe:l,blocked:d}=kr(a);if(d.length>0){console.log(y.yellow(`Excluded ${d.length} sensitive file(s):`));for(let L of d.slice(0,5))console.log(y.gray(` \u2022 ${L}`));d.length>5&&console.log(y.gray(` ... and ${d.length-5} more`)),console.log();}let T=o.filter(L=>l.includes(L.path)),b=await Go(t.path,T);i.update(a.length),i.stop();let j=((Date.now()-s)/1e3).toFixed(1);r.succeed(`Scanned ${b.metadata.total_files} files in ${j}s`),console.log(y.green(`
70
+ `)));let{safe:l,blocked:d}=wr(a);if(d.length>0){console.log(y.yellow(`Excluded ${d.length} sensitive file(s):`));for(let L of d.slice(0,5))console.log(y.gray(` \u2022 ${L}`));d.length>5&&console.log(y.gray(` ... and ${d.length-5} more`)),console.log();}let T=o.filter(L=>l.includes(L.path)),b=await oi(t.path,T);i.update(a.length),i.stop();let j=((Date.now()-s)/1e3).toFixed(1);r.succeed(`Scanned ${b.metadata.total_files} files in ${j}s`),console.log(y.green(`
71
71
  \u{1F389} Scan completed successfully`)),console.log(`
72
72
  `+y.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(y.bold.white(" VeeStack Security Report")),console.log(y.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
73
- `));let _=Wo(b,c);console.log(y.bold("Security Score"));let ut=_.grade.startsWith("A")?y.green:_.grade==="B"?y.blue:y.yellow;console.log(`${ut.bold(_.grade)} (${_.score}/100)`),c.secretsFound>0?console.log(y.gray(`${c.criticalCount} Critical, ${c.highCount} High, ${c.mediumCount} Medium, ${c.lowCount||0} Low
73
+ `));let _=si(b,c);console.log(y.bold("Security Score"));let dt=_.grade.startsWith("A")?y.green:_.grade==="B"?y.blue:y.yellow;console.log(`${dt.bold(_.grade)} (${_.score}/100)`),c.secretsFound>0?console.log(y.gray(`${c.criticalCount} Critical, ${c.highCount} High, ${c.mediumCount} Medium, ${c.lowCount||0} Low
74
74
  `)):console.log(y.gray(`No issues detected
75
- `));let dt=new zo({head:[y.cyan("Language"),y.cyan("Files")],style:{head:[],border:["gray"]}});Object.entries(b.metadata.language_breakdown).sort(([,L],[,pt])=>pt-L).slice(0,5).forEach(([L,pt])=>dt.push([L,pt])),console.log(y.bold("Languages detected")),console.log(dt.toString()+`
75
+ `));let pt=new ri({head:[y.cyan("Language"),y.cyan("Files")],style:{head:[],border:["gray"]}});Object.entries(b.metadata.language_breakdown).sort(([,L],[,ft])=>ft-L).slice(0,5).forEach(([L,ft])=>pt.push([L,ft])),console.log(y.bold("Languages detected")),console.log(pt.toString()+`
76
76
  `),console.log(y.bold("Summary")),console.log(y.gray(` \u2022 Files: ${b.metadata.total_files}`)),console.log(y.gray(` \u2022 Dependencies: ${b.metadata.total_dependencies}`)),console.log(y.gray(` \u2022 Project: ${resolve(t.path).split(/[\\/]/).pop()}`)),console.log(`
77
- `+y.gray("\u2500".repeat(40)));let Ye=await import('fs/promises');await Ye.writeFile(t.output,JSON.stringify(b,null,2));try{let L=join(process.env.HOME||process.env.USERPROFILE||"",".veestack","last-scan.json"),pt={timestamp:new Date().toISOString(),score:_.score,grade:_.grade,issues:c.secretsFound,project:resolve(t.path).split(/[\\/]/).pop()};await Ye.mkdir(join(process.env.HOME||process.env.USERPROFILE||"",".veestack"),{recursive:!0}),await Ye.writeFile(L,JSON.stringify(pt,null,2));}catch{}console.log(`
77
+ `+y.gray("\u2500".repeat(40)));let Ze=await import('fs/promises');await Ze.writeFile(t.output,JSON.stringify(b,null,2));try{let L=join(process.env.HOME||process.env.USERPROFILE||"",".veestack","last-scan.json"),ft={timestamp:new Date().toISOString(),score:_.score,grade:_.grade,issues:c.secretsFound,project:resolve(t.path).split(/[\\/]/).pop()};await Ze.mkdir(join(process.env.HOME||process.env.USERPROFILE||"",".veestack"),{recursive:!0}),await Ze.writeFile(L,JSON.stringify(ft,null,2));}catch{}console.log(`
78
78
  \u2705 Snapshot saved to ${t.output}`),n?(console.log(y.bold(`
79
79
  Next step`)),console.log(y.gray(`
80
80
  Upload results to cloud:`)),console.log(y.cyan(" veestack upload"))):(console.log(y.bold(`
81
81
  Next step`)),console.log(y.gray(`
82
82
  Upload results to cloud:`)),console.log(y.cyan(" veestack upload snapshot.json")));}catch(s){r.fail("Scan failed"),console.error(y.red(`
83
83
  \u274C Error:`),s),console.log(y.gray(`
84
- Possible causes:`)),console.log(y.gray(" \u2022 Invalid project path")),console.log(y.gray(" \u2022 Permission denied")),console.log(y.gray(" \u2022 No package.json found")),process.exit(1);}}async function Go(t,e){let n=await Zo(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:Jo(e)};return {snapshot_version:oe,engine_target_version:Ke,project_id:le__default.randomUUID(),generated_at:new Date().toISOString(),root_path_hash:An(t),project_root:resolve(t),metadata:r,files:e,dependencies:n}}async function Yo(t){let e=[],r=await glob(["**/*"],{cwd:t,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**"],absolute:false});for(let s of r){let o=join(t,s),a=statSync(o);if(a.isFile()){let i={id:le__default.randomUUID(),path:s,path_hash:An(s),depth:s.split(/[\\/]/).length,size_bytes:a.size,estimated_lines:Math.floor(a.size/50),extension:s.split(".").pop()||"",is_binary:qo(s)};e.push(i);}}return e.sort((s,o)=>s.path_hash.localeCompare(o.path_hash))}async function Zo(t){let e=[];try{let n=join(t,"package.json"),r=JSON.parse(readFileSync(n,"utf-8")),s=(o,a)=>{for(let[i,c]of Object.entries(o)){let l=c.match(/^(\d+)\.(\d+)/),d=l?parseInt(l[1]):0,T=l?parseInt(l[2]):0;e.push({id:le__default.randomUUID(),name_hash:An(i),major_version:d,minor_version:T,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 Jo(t){let e={};for(let n of t){let r=n.extension.toLowerCase(),s=Ko(r);e[s]=(e[s]||0)+1;}return e}function Ko(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 qo(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 An(t){return le__default.createHash("sha256").update(t).digest("hex")}var on=process.env.SUPABASE_URL||"https://qhonrrojtqklvlkvfswb.supabase.co",Te=process.env.SUPABASE_ANON_KEY||"";async function ki(){try{let t=await fetch(`${on}/rest/v1/projects?select=id,name,created_at&order=created_at.desc`,{headers:{apikey:Te,Authorization:`Bearer ${Te}`}});return t.ok?await t.json():[]}catch{return []}}async function Cr(t){try{let e=await fetch(`${on}/rest/v1/projects`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Te,Authorization:`Bearer ${Te}`,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 sn(t){let e=_i.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{e.question(t,r=>{e.close(),n(r);});})}async function Ei(){console.log(y.blue(`
84
+ Possible causes:`)),console.log(y.gray(" \u2022 Invalid project path")),console.log(y.gray(" \u2022 Permission denied")),console.log(y.gray(" \u2022 No package.json found")),process.exit(1);}}async function oi(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:ci(e)};return {snapshot_version:ie,engine_target_version:qe,project_id:ue__default.randomUUID(),generated_at:new Date().toISOString(),root_path_hash:bn(t),project_root:resolve(t),metadata:r,files:e,dependencies:n}}async function ii(t){let e=[],r=await glob(["**/*"],{cwd:t,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**"],absolute:false});for(let s of r){let o=join(t,s),a=statSync(o);if(a.isFile()){let i={id:ue__default.randomUUID(),path:s,path_hash:bn(s),depth:s.split(/[\\/]/).length,size_bytes:a.size,estimated_lines:Math.floor(a.size/50),extension:s.split(".").pop()||"",is_binary:ui(s)};e.push(i);}}return e.sort((s,o)=>s.path_hash.localeCompare(o.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,c]of Object.entries(o)){let l=c.match(/^(\d+)\.(\d+)/),d=l?parseInt(l[1]):0,T=l?parseInt(l[2]):0;e.push({id:ue__default.randomUUID(),name_hash:bn(i),major_version:d,minor_version:T,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 ci(t){let e={};for(let n of t){let r=n.extension.toLowerCase(),s=li(r);e[s]=(e[s]||0)+1;}return e}function li(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 ui(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 bn(t){return ue__default.createHash("sha256").update(t).digest("hex")}var an=process.env.SUPABASE_URL||"https://qhonrrojtqklvlkvfswb.supabase.co",Ae=process.env.SUPABASE_ANON_KEY||"";async function Di(){try{let t=await fetch(`${an}/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 Or(t){try{let e=await fetch(`${an}/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 on(t){let e=Oi.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{e.question(t,r=>{e.close(),n(r);});})}async function Pi(){console.log(y.blue(`
85
85
  \u{1F4C1} Loading projects...
86
- `));let t=await ki();if(t.length===0){if(console.log(y.yellow(`No projects found.
87
- `)),(await sn("Do you want to create a new project? (y/n): ")).toLowerCase()==="y"){let s=await sn("Enter project name: ");if(s.trim()){let o=await Cr(s.trim());if(o)return console.log(y.green(`
86
+ `));let t=await Di();if(t.length===0){if(console.log(y.yellow(`No projects found.
87
+ `)),(await on("Do you want to create a new project? (y/n): ")).toLowerCase()==="y"){let s=await on("Enter project name: ");if(s.trim()){let o=await Or(s.trim());if(o)return console.log(y.green(`
88
88
  \u2705 Project "${s}" created successfully!`)),o}}return null}console.log(y.white(`Select a project:
89
89
  `)),console.log(y.gray(`0. [+] Create new project
90
90
  `)),t.forEach((r,s)=>{console.log(y.white(`${s+1}. ${r.name}`)),console.log(y.gray(` ID: ${r.id}`)),console.log(y.gray(` Created: ${new Date(r.created_at).toLocaleDateString()}
91
- `));});let e=await sn("Enter number (0-"+t.length+"): "),n=parseInt(e,10);if(n===0){let r=await sn(`
92
- Enter project name: `);if(r.trim()){let s=await Cr(r.trim());if(s)return console.log(y.green(`
91
+ `));});let e=await on("Enter number (0-"+t.length+"): "),n=parseInt(e,10);if(n===0){let r=await on(`
92
+ Enter project name: `);if(r.trim()){let s=await Or(r.trim());if(s)return console.log(y.green(`
93
93
  \u2705 Project "${r}" created successfully!`)),s}return null}else if(n>0&&n<=t.length){let r=t[n-1];return console.log(y.green(`
94
94
  \u2705 Selected project: "${r.name}"`)),r.id}else return console.log(y.red(`
95
- \u274C Invalid selection`)),null}async function Cn(t){let e=await we();e||(console.log(y.red("\u274C Authentication required")),console.log(y.yellow(`
96
- Please login first:`)),console.log(y.cyan(" veestack login")),process.exit(1));let n=it();console.log(y.blue(`
95
+ \u274C Invalid selection`)),null}async function On(t){let e=await Te();e||(console.log(y.red("\u274C Authentication required")),console.log(y.yellow(`
96
+ Please login first:`)),console.log(y.cyan(" veestack login")),process.exit(1));let n=at();console.log(y.blue(`
97
97
  \u{1F510} Authentication verified`)),e.user&&console.log(y.gray(`User: ${e.user.name}`)),console.log(y.gray(`Subscription tier: ${n==="pro"?"Pro":"Free"}`)),console.log(y.gray("\u2500".repeat(40)+`
98
- `));let r=Bo("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 L=await Ei();L||(console.log(y.red(`
99
- \u274C No project selected. Exiting.`)),process.exit(1)),i=L,r.start("Uploading snapshot...");}r.text="Creating snapshot...";let c=await fetch(`${on}/rest/v1/snapshots`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Te,Authorization:`Bearer ${Te}`,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(!c.ok){let L=await c.json();r.fail("Failed to create snapshot"),console.error(y.red(`Error: ${L.message||L.details||"Unknown error"}`)),process.exit(1);}let l=await c.json(),d=l[0]?.id||l[0]?.id;r.text="Analyzing snapshot...";let{CoreEngine:T}=await Promise.resolve().then(()=>(bn(),Rn)),{RULES:b}=await Promise.resolve().then(()=>(bn(),Rn)),j=new T;b.forEach(L=>j.registerRule(L));let _=await j.analyze(a);_.success||(r.fail("Analysis failed"),console.error(y.red("Error:",_.error)),process.exit(1)),r.text="Creating report...";let ut=await fetch(`${on}/rest/v1/reports`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Te,Authorization:`Bearer ${Te}`,Prefer:"return=representation"},body:JSON.stringify({snapshot_id:d,score:_.report.total_score,issues_count:_.report.summary.total_findings,critical_count:_.report.summary.critical_count,high_count:_.report.summary.high_count,medium_count:_.report.summary.medium_count,low_count:_.report.summary.low_count,execution_time_ms:0,report_json:_.report})});if(!ut.ok){let L=await ut.json();r.fail("Failed to create report"),console.error(y.red(`Error: ${L.message||L.details||"Unknown error"}`)),process.exit(1);}let dt=await ut.json(),Ye=dt[0]?.id||dt[0]?.id;r.succeed("Analysis complete"),console.log(y.green(`
100
- \u2705 Report generated and saved to VeeStack`)),console.log(y.gray("Project ID:"),i),console.log(y.gray("Snapshot ID:"),d),console.log(y.gray("Report ID:"),Ye),console.log(y.bold(`
98
+ `));let r=ti("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 L=await Pi();L||(console.log(y.red(`
99
+ \u274C No project selected. Exiting.`)),process.exit(1)),i=L,r.start("Uploading snapshot...");}r.text="Creating snapshot...";let c=await fetch(`${an}/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(!c.ok){let L=await c.json();r.fail("Failed to create snapshot"),console.error(y.red(`Error: ${L.message||L.details||"Unknown error"}`)),process.exit(1);}let l=await c.json(),d=l[0]?.id||l[0]?.id;r.text="Analyzing snapshot...";let{CoreEngine:T}=await Promise.resolve().then(()=>(Nn(),In)),{RULES:b}=await Promise.resolve().then(()=>(Nn(),In)),j=new T;b.forEach(L=>j.registerRule(L));let _=await j.analyze(a);_.success||(r.fail("Analysis failed"),console.error(y.red("Error:",_.error)),process.exit(1)),r.text="Creating report...";let dt=await fetch(`${an}/rest/v1/reports`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ae,Authorization:`Bearer ${Ae}`,Prefer:"return=representation"},body:JSON.stringify({snapshot_id:d,score:_.report.total_score,issues_count:_.report.summary.total_findings,critical_count:_.report.summary.critical_count,high_count:_.report.summary.high_count,medium_count:_.report.summary.medium_count,low_count:_.report.summary.low_count,execution_time_ms:0,report_json:_.report})});if(!dt.ok){let L=await dt.json();r.fail("Failed to create report"),console.error(y.red(`Error: ${L.message||L.details||"Unknown error"}`)),process.exit(1);}let pt=await dt.json(),Ze=pt[0]?.id||pt[0]?.id;r.succeed("Analysis complete"),console.log(y.green(`
100
+ \u2705 Report generated and saved to VeeStack`)),console.log(y.gray("Project ID:"),i),console.log(y.gray("Snapshot ID:"),d),console.log(y.gray("Report ID:"),Ze),console.log(y.bold(`
101
101
  \u{1F4CA} Score:`),_.report.total_score),console.log(y.gray("Severity:"),_.report.severity_band),console.log(y.gray("Findings:"),_.report.summary.total_findings),console.log(y.blue(`
102
- \u{1F517} View your report at:`)),console.log(y.underline(`http://localhost:3001/reports/${Ye}?project=${i}`));}catch(s){r.fail("Upload failed"),console.error(s),process.exit(1);}}re();var Nr=process.env.VEESTACK_API_URL||"https://api.veestack.tools",Ti=process.env.VEESTACK_WEB_URL||"https://veestack.tools",Ai=2e3,Or=300;function xi(){return le__default.randomBytes(16).toString("hex")}function Ri(){let t=le__default.randomBytes(32).toString("base64url"),e=le__default.createHash("sha256").update(t).digest("base64url");return {code_verifier:t,code_challenge:e}}function bi(){let t=process.platform,e=ot.hostname(),n=H,r=e||le__default.randomBytes(8).toString("hex"),s=le__default.createHash("sha256").update(`${r}:${t}:${n}`).digest("hex"),o=le__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 Ci(t,e){let n=xi(),r=await fetch(`${Nr}/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 Ii(t,e,n){try{let r=await fetch(`${Nr}/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>=Or)throw new Error("Authentication timeout. Please try again.");return null}}async function Rt(){console.log(y.bold.cyan(`
102
+ \u{1F517} View your report at:`)),console.log(y.underline(`http://localhost:3001/reports/${Ze}?project=${i}`));}catch(s){r.fail("Upload failed"),console.error(s),process.exit(1);}}te();var Pr=process.env.VEESTACK_API_URL||"https://api.veestack.tools",Ui=process.env.VEESTACK_WEB_URL||"https://veestack.tools",$i=2e3,Lr=300;function Mi(){return ue__default.randomBytes(16).toString("hex")}function Fi(){let t=ue__default.randomBytes(32).toString("base64url"),e=ue__default.createHash("sha256").update(t).digest("base64url");return {code_verifier:t,code_challenge:e}}function Vi(){let t=process.platform,e=it.hostname(),n=H,r=e||ue__default.randomBytes(8).toString("hex"),s=ue__default.createHash("sha256").update(`${r}:${t}:${n}`).digest("hex"),o=ue__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 Bi(t,e){let n=Mi(),r=await fetch(`${Pr}/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 Hi(t,e,n){try{let r=await fetch(`${Pr}/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>=Lr)throw new Error("Authentication timeout. Please try again.");return null}}async function bt(){console.log(y.bold.cyan(`
103
103
  \u{1F510} Login to VeeStack
104
104
  `)),console.log(y.gray(`Opening browser to authenticate...
105
- `));let t=Bo({text:"Requesting device code...",spinner:"dots",stream:process.stdout});try{let e=Ri(),n=bi();t.start();let r=await Ci(e,n);t.stop();let s=`${Ti}/cli-auth?device=${r.device_code}&code=${r.user_code}&challenge=${e.code_challenge}`;console.log(y.white(`Please authenticate using your browser:
105
+ `));let t=ti({text:"Requesting device code...",spinner:"dots",stream:process.stdout});try{let e=Fi(),n=Vi();t.start();let r=await Bi(e,n);t.stop();let s=`${Ui}/cli-auth?device=${r.device_code}&code=${r.user_code}&challenge=${e.code_challenge}`;console.log(y.white(`Please authenticate using your browser:
106
106
  `)),console.log(y.gray("Device: ")+y.white(n.name)),console.log(y.gray("Device Code: ")+y.bold.cyan(r.user_code)),console.log(y.gray("URL: ")+y.underline(s)+`
107
- `),await wi(s),console.log(y.yellow("Waiting for authentication...")),console.log(y.gray(`(Press Ctrl+C to cancel)
108
- `));let o=0,a=null;for(t.start("Checking authentication status...");!a&&o<Or;)await new Promise(c=>setTimeout(c,Ai)),a=await Ii(r.device_code,e.code_verifier,o),o++,a||(t.text=`Checking authentication status... (${o*2}s)`);a||(t.fail("Authentication timeout"),console.log(y.red(`
109
- \u274C Authentication timed out after 10 minutes.`)),console.log(y.yellow("Please try again with: veestack login")),process.exit(1)),t.succeed("Authentication successful");let i={token:a.access_token,tokenType:a.token_type,refreshToken:a.refresh_token,tokenExpiresAt:new Date(Date.now()+a.expires_in*1e3).toISOString(),device:{id:n.id,name:n.name,fingerprint:n.fingerprint},user:{id:a.user.id,email:a.user.email,name:a.user.name,provider:a.user.provider},subscription:a.subscription||{tier:"free",isActive:!0},lastLoginAt:new Date().toISOString()};try{await wt(i);}catch(c){t.fail("Failed to save authentication"),console.error(y.red(`
107
+ `),await ji(s),console.log(y.yellow("Waiting for authentication...")),console.log(y.gray(`(Press Ctrl+C to cancel)
108
+ `));let o=0,a=null;for(t.start("Checking authentication status...");!a&&o<Lr;)await new Promise(c=>setTimeout(c,$i)),a=await Hi(r.device_code,e.code_verifier,o),o++,a||(t.text=`Checking authentication status... (${o*2}s)`);a||(t.fail("Authentication timeout"),console.log(y.red(`
109
+ \u274C Authentication timed out after 10 minutes.`)),console.log(y.yellow("Please try again with: veestack login")),process.exit(1)),t.succeed("Authentication successful");let i={token:a.access_token,tokenType:a.token_type,refreshToken:a.refresh_token,tokenExpiresAt:new Date(Date.now()+a.expires_in*1e3).toISOString(),device:{id:n.id,name:n.name,fingerprint:n.fingerprint},user:{id:a.user.id,email:a.user.email,name:a.user.name,provider:a.user.provider},subscription:a.subscription||{tier:"free",isActive:!0},lastLoginAt:new Date().toISOString()};try{await Tt(i);}catch(c){t.fail("Failed to save authentication"),console.error(y.red(`
110
110
  \u274C Could not securely store tokens:`),c),process.exit(1);}console.log(y.green(`
111
111
  \u2714 Login successful
112
112
  `)),console.log(y.gray("Device: ")+y.white(i.device.name)),console.log(y.gray("Device ID: ")+y.gray(i.device.id.substring(0,8)+"...")),console.log(y.gray("Account: ")+y.white(i.user.name)),console.log(y.gray("Email: ")+y.white(i.user.email)),console.log(y.gray("Provider: ")+y.cyan(i.user.provider)),console.log(y.gray("Subscription: ")+(i.subscription?.tier==="pro"?y.cyan("Pro"):y.blue("Free"))),console.log(y.gray("Token expires: ")+y.yellow(new Date(i.tokenExpiresAt).toLocaleString())),console.log(y.gray(`
113
- Token saved securely to OS Keychain`)),yr({token:i.token,tokenType:i.tokenType,refreshToken:i.refreshToken,tokenExpiresAt:i.tokenExpiresAt,device:i.device,user:i.user,subscription:i.subscription,lastLoginAt:i.lastLoginAt});}catch(e){t.fail("Authentication failed"),console.error(y.red(`
114
- \u274C Error:`),e instanceof Error?e.message:e),process.exit(1);}}var Ni=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function Dr(){try{let t=await K();if(!t){console.log(y.yellow("\u26A0\uFE0F Not logged in"));return}if(console.log(y.bold.cyan(`
113
+ Token saved securely to OS Keychain`)),kr({token:i.token,tokenType:i.tokenType,refreshToken:i.refreshToken,tokenExpiresAt:i.tokenExpiresAt,device:i.device,user:i.user,subscription:i.subscription,lastLoginAt:i.lastLoginAt});}catch(e){t.fail("Authentication failed"),console.error(y.red(`
114
+ \u274C Error:`),e instanceof Error?e.message:e),process.exit(1);}}var zi=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function jr(){try{let t=await K();if(!t){console.log(y.yellow("\u26A0\uFE0F Not logged in"));return}if(console.log(y.bold.cyan(`
115
115
  \u{1F6AA} Logout from VeeStack
116
- `)),t.token||t.apiKey)try{let e=t.token||t.apiKey;await fetch(`${Ni}/api/cli/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({device_id:t.device?.id})});}catch{}await Yt()&&await Be();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(y.green(`\u2714 Logged out ${t.user.name}`)):console.log(y.green("\u2714 Logged out")),console.log(y.gray(`
116
+ `)),t.token||t.apiKey)try{let e=t.token||t.apiKey;await fetch(`${zi}/api/cli/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({device_id:t.device?.id})});}catch{}await Zt()&&await He();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(y.green(`\u2714 Logged out ${t.user.name}`)):console.log(y.green("\u2714 Logged out")),console.log(y.gray(`
117
117
  \u{1F510} All local tokens securely deleted`)),console.log(y.gray("See you soon! \u{1F44B}")),console.log(y.gray(`Run "veestack login" to authenticate again.
118
- `));}catch(t){me.error("\u274C Error during logout:",_n(t)),process.exit(1);}}async function Pr(){try{let t=await we();t||(console.log(y.yellow("\u26A0\uFE0F Not authenticated")),console.log(y.gray(`
118
+ `));}catch(t){he.error("\u274C Error during logout:",Sn(t)),process.exit(1);}}async function Ur(){try{let t=await Te();t||(console.log(y.yellow("\u26A0\uFE0F Not authenticated")),console.log(y.gray(`
119
119
  Please login first:`)),console.log(y.cyan(" veestack login")),process.exit(1)),console.log(y.bold.cyan(`
120
120
  \u{1F464} VeeStack Account
121
- `)),t.user&&(console.log(y.gray("User: ")+y.white(t.user.name)),console.log(y.gray("Email: ")+y.white(t.user.email)),console.log(y.gray("Provider: ")+y.cyan(t.user.provider))),t.device&&(console.log(y.gray("Device: ")+y.white(t.device.name)),console.log(y.gray("Device ID: ")+y.gray(t.device.id.substring(0,8)+"...")));let e=t.subscription?.tier||"free";if(console.log(y.gray("Subscription: ")+(e==="pro"?y.cyan("Pro"):y.blue("Free"))),t.tokenExpiresAt){let r=En(t)?y.red("Expired (will refresh)"):y.green("Valid");console.log(y.gray("Token Status: ")+r),console.log(y.gray("Expires: ")+y.yellow(new Date(t.tokenExpiresAt).toLocaleString()));}t.lastLoginAt&&console.log(y.gray("Last Login: ")+y.gray(new Date(t.lastLoginAt).toLocaleString())),console.log();}catch(t){console.error(y.red("\u274C Error:"),t instanceof Error?t.message:t),process.exit(1);}}function jr(){return join(homedir(),".veestack","accounts")}function Oi(){try{let t=jr();if(!te.existsSync(t))return [];let e=[],n=te.readdirSync(t);for(let r of n)if(r.endsWith(".json")){let s=te.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 Di(t){try{let e=jr();if(te.mkdirSync(e,{recursive:!0}),t.user){let n=join(e,`${t.user.id}.json`);te.writeFileSync(n,JSON.stringify(t,null,2),{mode:384});}}catch{}}async function Ur(){let t=await K(),e=Oi();console.log(y.bold.cyan(`
121
+ `)),t.user&&(console.log(y.gray("User: ")+y.white(t.user.name)),console.log(y.gray("Email: ")+y.white(t.user.email)),console.log(y.gray("Provider: ")+y.cyan(t.user.provider))),t.device&&(console.log(y.gray("Device: ")+y.white(t.device.name)),console.log(y.gray("Device ID: ")+y.gray(t.device.id.substring(0,8)+"...")));let e=t.subscription?.tier||"free";if(console.log(y.gray("Subscription: ")+(e==="pro"?y.cyan("Pro"):y.blue("Free"))),t.tokenExpiresAt){let r=Tn(t)?y.red("Expired (will refresh)"):y.green("Valid");console.log(y.gray("Token Status: ")+r),console.log(y.gray("Expires: ")+y.yellow(new Date(t.tokenExpiresAt).toLocaleString()));}t.lastLoginAt&&console.log(y.gray("Last Login: ")+y.gray(new Date(t.lastLoginAt).toLocaleString())),console.log();}catch(t){console.error(y.red("\u274C Error:"),t instanceof Error?t.message:t),process.exit(1);}}function Mr(){return join(homedir(),".veestack","accounts")}function Wi(){try{let t=Mr();if(!ne.existsSync(t))return [];let e=[],n=ne.readdirSync(t);for(let r of n)if(r.endsWith(".json")){let s=ne.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 Gi(t){try{let e=Mr();if(ne.mkdirSync(e,{recursive:!0}),t.user){let n=join(e,`${t.user.id}.json`);ne.writeFileSync(n,JSON.stringify(t,null,2),{mode:384});}}catch{}}async function Fr(){let t=await K(),e=Wi();console.log(y.bold.cyan(`
122
122
  \u{1F464} Switch Account
123
123
  `)),t?.user&&(console.log(y.gray("Currently logged in as:")),console.log(y.white(` ${t.user.name} (${t.user.email})`)),console.log(y.gray(` Provider: ${t.user.provider}`)),console.log());let n=e.filter(i=>i.id!==t?.user?.id);if(n.length===0){console.log(y.yellow("No other saved accounts found.")),console.log(y.gray(`
124
124
  To add a new account:`)),console.log(y.cyan(" veestack login")),console.log();return}console.log(y.gray("Available accounts:")),n.forEach((i,c)=>{console.log(y.white(`
125
125
  ${c+1}) ${i.name}`)),console.log(y.gray(` ${i.email}`)),console.log(y.gray(` Provider: ${i.provider}`));}),console.log(y.gray(`
126
- 0) Add new account`)),console.log();let s=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(i=>{s.question(y.white("Select account (number): "),c=>{s.close(),i(c);});}),a=parseInt(o,10);if(a===0){await Rt();return}if(a>0&&a<=n.length){let i=n[a-1];t&&Di(t);let c=join(homedir(),".veestack"),l=join(c,"config.json");te.mkdirSync(c,{recursive:true}),te.writeFileSync(l,JSON.stringify(i.config,null,2),{mode:384}),console.log(y.green(`
126
+ 0) Add new account`)),console.log();let s=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(i=>{s.question(y.white("Select account (number): "),c=>{s.close(),i(c);});}),a=parseInt(o,10);if(a===0){await bt();return}if(a>0&&a<=n.length){let i=n[a-1];t&&Gi(t);let c=join(homedir(),".veestack"),l=join(c,"config.json");ne.mkdirSync(c,{recursive:true}),ne.writeFileSync(l,JSON.stringify(i.config,null,2),{mode:384}),console.log(y.green(`
127
127
  \u2714 Switched to ${i.name}`)),console.log(y.gray(` ${i.email}`)),console.log();}else console.log(y.red(`
128
- \u274C Invalid selection`)),process.exit(1);}function Pi(){let t=join(process.cwd(),"veestack.config.json");if(!existsSync(t))return null;try{return JSON.parse(readFileSync(t,"utf-8"))}catch{return null}}function Li(){let t=join(process.env.HOME||process.env.USERPROFILE||"",".veestack","last-scan.json");if(existsSync(t))try{return JSON.parse(readFileSync(t,"utf-8"))}catch{return null}return null}function ji(t){let e=new Date(t),r=Math.floor((new Date().getTime()-e.getTime())/1e3);if(r<60)return `${r} seconds ago`;let s=Math.floor(r/60);if(s<60)return `${s} minutes ago`;let o=Math.floor(s/60);return o<24?`${o} hours ago`:e.toLocaleDateString()}async function In(){console.log(y.bold.cyan(`
128
+ \u274C Invalid selection`)),process.exit(1);}te();function Yi(){let t=join(process.cwd(),"veestack.config.json");if(!existsSync(t))return null;try{return JSON.parse(readFileSync(t,"utf-8"))}catch{return null}}function Zi(){let t=join(process.env.HOME||process.env.USERPROFILE||"",".veestack","last-scan.json");if(existsSync(t))try{return JSON.parse(readFileSync(t,"utf-8"))}catch{return null}return null}function Ji(t){let e=new Date(t),r=Math.floor((new Date().getTime()-e.getTime())/1e3);if(r<60)return `${r} seconds ago`;let s=Math.floor(r/60);if(s<60)return `${s} minutes ago`;let o=Math.floor(s/60);return o<24?`${o} hours ago`:e.toLocaleDateString()}async function Dn(){console.log(y.bold.cyan(`
129
129
  \u{1F4CA} VeeStack Status
130
- `)),console.log(y.gray("\u2500".repeat(40)));let t=await At(),e=await it(),n=await hr(),r=Pi(),s=Li();if(console.log(y.gray(`
131
- CLI Version: ${y.white("6.1.1")}`)),console.log(y.bold(`
130
+ `)),console.log(y.gray("\u2500".repeat(40)));let t=await xt(),e=await at(),n=await _r(),r=Yi(),s=Zi();if(console.log(y.gray(`
131
+ CLI Version: ${y.white(oe)}`)),console.log(y.bold(`
132
132
  User`)),t?(console.log(y.green(" \u2714 Authenticated")),console.log(e==="pro"?y.cyan(" \u{1F48E} Pro plan"):y.blue(" \u{1F4E6} Free plan")),n||console.log(y.red(" \u26A0 Subscription expired"))):(console.log(y.yellow(`
133
133
  \u26A0\uFE0F You are not logged in`)),console.log(y.gray(`
134
134
  Login to enable:`)),console.log(y.gray(" \u2022 Cloud reports")),console.log(y.gray(" \u2022 Team dashboard")),console.log(y.gray(` \u2022 Historical scans
135
135
  `)),console.log(y.gray("Run:")),console.log(y.cyan(" veestack login"))),console.log(y.bold(`
136
136
  Project`)),r?(console.log(y.green(` \u2714 ${r.name||"Unnamed project"}`)),r.framework&&console.log(y.gray(` Framework: ${r.framework}`)),r.projectId?console.log(y.gray(" Linked: Yes")):console.log(y.gray(" Linked: No"))):(console.log(y.yellow(" \u26A0 No project initialized")),console.log(y.gray(" Run: veestack init"))),console.log(y.bold(`
137
- Scan Status`)),s){console.log(y.gray(` Last scan: ${ji(s.timestamp)}`));let o=s.grade.startsWith("A")?y.green:s.grade==="B"?y.blue:y.yellow;console.log(y.gray(` Score: ${o.bold(s.grade)} (${s.score}/100)`)),console.log(y.gray(` Issues: ${s.issues>0?y.red(s.issues):y.green(0)}`));}else console.log(y.gray(" Last scan: Never")),console.log(y.gray(" Issues: -"));console.log(y.gray(`
138
- `+"\u2500".repeat(40)));}var Vr=process.env.VEESTACK_DASHBOARD_URL||"https://veestack.tools/dashboard";function Vi(){let t=join(process.cwd(),"veestack.config.json");if(existsSync(t))try{return JSON.parse(readFileSync(t,"utf-8")).projectId||null}catch{return null}return null}async function Br(){let t=Vi(),e=t?`${Vr}/projects/${t}`:Vr;console.log(y.cyan(`
139
- Opening ${e}...`));try{await wi(e),console.log(y.green(`\u2714 Dashboard opened in your browser
137
+ Scan Status`)),s){console.log(y.gray(` Last scan: ${Ji(s.timestamp)}`));let o=s.grade.startsWith("A")?y.green:s.grade==="B"?y.blue:y.yellow;console.log(y.gray(` Score: ${o.bold(s.grade)} (${s.score}/100)`)),console.log(y.gray(` Issues: ${s.issues>0?y.red(s.issues):y.green(0)}`));}else console.log(y.gray(" Last scan: Never")),console.log(y.gray(" Issues: -"));console.log(y.gray(`
138
+ `+"\u2500".repeat(40)));}var zr=process.env.VEESTACK_DASHBOARD_URL||"https://veestack.tools/dashboard";function ea(){let t=join(process.cwd(),"veestack.config.json");if(existsSync(t))try{return JSON.parse(readFileSync(t,"utf-8")).projectId||null}catch{return null}return null}async function Wr(){let t=ea(),e=t?`${zr}/projects/${t}`:zr;console.log(y.cyan(`
139
+ Opening ${e}...`));try{await ji(e),console.log(y.green(`\u2714 Dashboard opened in your browser
140
140
  `));}catch{console.log(y.red(`
141
141
  \u274C Could not open browser automatically.`)),console.log(y.gray(`Please visit: ${y.white(e)}
142
- `));}}re();var zi=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function Wi(){let t=process.version,e=parseInt(t.slice(1).split(".")[0]);return e>=18?{name:"Node.js Version",status:"ok",message:`${t} (>= 18)`}:e>=16?{name:"Node.js Version",status:"warning",message:`${t} (>= 16, but 18+ recommended)`}:{name:"Node.js Version",status:"error",message:`${t} (>= 18 required)`,details:"Please upgrade Node.js: https://nodejs.org"}}async function Gi(){let t=process.env.VEESTACK_CLI_VERSION||H;try{let e=await fetch("https://registry.npmjs.org/veestack-tools/latest",{signal:AbortSignal.timeout(3e3)});if(e.ok){let r=(await e.json()).version;return t===r?{name:"CLI Version",status:"ok",message:`v${t} (latest)`}:{name:"CLI Version",status:"warning",message:`v${t} (latest: v${r})`,details:"Upgrade: npm install -g veestack-tools"}}}catch{}return {name:"CLI Version",status:"ok",message:`v${t}`}}async function Yi(){try{let t=await K();return t?{name:"Authentication",status:"ok",message:t.user?.email||"Authenticated via API Key"}:{name:"Authentication",status:"warning",message:"Not authenticated",details:"Run: veestack login"}}catch{return {name:"Authentication",status:"error",message:"Auth system error",details:"Try: veestack logout && veestack login"}}}async function Zi(){if(!await At())return {name:"API Connectivity",status:"ok",message:"Skipped (not authenticated)",details:"Login to enable API checks"};try{let e=await qt(),n=await fetch(`${zi}/v1/health`,{method:"GET",headers:e,signal:AbortSignal.timeout(5e3)});return n.ok?{name:"API Connectivity",status:"ok",message:"Reachable"}:{name:"API Connectivity",status:"warning",message:`HTTP ${n.status}`}}catch{return {name:"API Connectivity",status:"warning",message:"Unreachable",details:`Check:
142
+ `));}}te();var ra=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function sa(){let t=process.version,e=parseInt(t.slice(1).split(".")[0]);return e>=18?{name:"Node.js Version",status:"ok",message:`${t} (>= 18)`}:e>=16?{name:"Node.js Version",status:"warning",message:`${t} (>= 16, but 18+ recommended)`}:{name:"Node.js Version",status:"error",message:`${t} (>= 18 required)`,details:"Please upgrade Node.js: https://nodejs.org"}}async function oa(){let t=process.env.VEESTACK_CLI_VERSION||H;try{let e=await fetch("https://registry.npmjs.org/veestack-tools/latest",{signal:AbortSignal.timeout(3e3)});if(e.ok){let r=(await e.json()).version;return t===r?{name:"CLI Version",status:"ok",message:`v${t} (latest)`}:{name:"CLI Version",status:"warning",message:`v${t} (latest: v${r})`,details:"Upgrade: npm install -g veestack-tools"}}}catch{}return {name:"CLI Version",status:"ok",message:`v${t}`}}async function ia(){try{let t=await K();return t?{name:"Authentication",status:"ok",message:t.user?.email||"Authenticated via API Key"}:{name:"Authentication",status:"warning",message:"Not authenticated",details:"Run: veestack login"}}catch{return {name:"Authentication",status:"error",message:"Auth system error",details:"Try: veestack logout && veestack login"}}}async function aa(){if(!await xt())return {name:"API Connectivity",status:"ok",message:"Skipped (not authenticated)",details:"Login to enable API checks"};try{let e=await Xt(),n=await fetch(`${ra}/v1/health`,{method:"GET",headers:e,signal:AbortSignal.timeout(5e3)});return n.ok?{name:"API Connectivity",status:"ok",message:"Reachable"}:{name:"API Connectivity",status:"warning",message:`HTTP ${n.status}`}}catch{return {name:"API Connectivity",status:"warning",message:"Unreachable",details:`Check:
143
143
  \u2022 Internet connection
144
- \u2022 API endpoint configuration`}}}async function Ji(){let t=process.cwd(),e=join(t,"veestack.config.json"),n=join(t,"package.json");if(existsSync(e))try{return {name:"Project Config",status:"ok",message:`Found: ${JSON.parse(readFileSync(e,"utf-8")).projectId||"Unlinked project"}`}}catch{return {name:"Project Config",status:"warning",message:"Invalid veestack.config.json",details:"Check JSON syntax"}}return existsSync(n)?{name:"Project Config",status:"warning",message:"Not initialized",details:"Run: veestack init"}:{name:"Project Config",status:"warning",message:"No project found",details:"Navigate to a project directory"}}async function Ki(){let{isOfficial:t,packageName:e}=Ot();return t?{name:"Package Security",status:"ok",message:"Official package verified",details:e}:{name:"Package Security",status:"error",message:"Unofficial package detected!",details:`Expected: veestack-tools, Found: ${e}`}}async function qi(){let t=await fr();return t.keychainAvailable&&t.keychainHasTokens?{name:"Token Storage",status:"ok",message:"OS Keychain (secure)"}:t.fileExists?{name:"Token Storage",status:"warning",message:`File-based (${t.encryptionVersion>=2?"AES-256-GCM":"Encrypted"})`,details:"Install keytar for OS Keychain: npm install -g keytar"}:{name:"Token Storage",status:"ok",message:"No tokens stored"}}async function Xi(){try{return {name:"Git",status:"ok",message:execSync("git --version",{encoding:"utf-8"}).trim().replace("git version ","")}}catch{return {name:"Git",status:"warning",message:"Not installed",details:"Some features may not work"}}}async function Qi(){try{return {name:"Disk Space",status:"ok",message:"Sufficient"}}catch{return {name:"Disk Space",status:"warning",message:"Unable to check"}}}function It(t){let e={ok:y.green("\u2714"),warning:y.yellow("\u26A0"),error:y.red("\u2718")},n={ok:y.green,warning:y.yellow,error:y.red};console.log(` ${e[t.status]} ${y.bold(t.name)}: ${n[t.status](t.message)}`),t.details&&console.log(` ${y.gray(t.details)}`);}async function Nn(){console.log(y.bold.cyan(`
144
+ \u2022 API endpoint configuration`}}}async function ca(){let t=process.cwd(),e=join(t,"veestack.config.json"),n=join(t,"package.json");if(existsSync(e))try{return {name:"Project Config",status:"ok",message:`Found: ${JSON.parse(readFileSync(e,"utf-8")).projectId||"Unlinked project"}`}}catch{return {name:"Project Config",status:"warning",message:"Invalid veestack.config.json",details:"Check JSON syntax"}}return existsSync(n)?{name:"Project Config",status:"warning",message:"Not initialized",details:"Run: veestack init"}:{name:"Project Config",status:"warning",message:"No project found",details:"Navigate to a project directory"}}async function la(){let{isOfficial:t,packageName:e}=Dt();return t?{name:"Package Security",status:"ok",message:"Official package verified",details:e}:{name:"Package Security",status:"error",message:"Unofficial package detected!",details:`Expected: veestack-tools, Found: ${e}`}}async function ua(){let t=await hr();return t.keychainAvailable&&t.keychainHasTokens?{name:"Token Storage",status:"ok",message:"OS Keychain (secure)"}:t.fileExists?{name:"Token Storage",status:"warning",message:`File-based (${t.encryptionVersion>=2?"AES-256-GCM":"Encrypted"})`,details:"Install keytar for OS Keychain: npm install -g keytar"}:{name:"Token Storage",status:"ok",message:"No tokens stored"}}async function da(){try{return {name:"Git",status:"ok",message:execSync("git --version",{encoding:"utf-8"}).trim().replace("git version ","")}}catch{return {name:"Git",status:"warning",message:"Not installed",details:"Some features may not work"}}}async function pa(){try{return {name:"Disk Space",status:"ok",message:"Sufficient"}}catch{return {name:"Disk Space",status:"warning",message:"Unable to check"}}}function Nt(t){let e={ok:y.green("\u2714"),warning:y.yellow("\u26A0"),error:y.red("\u2718")},n={ok:y.green,warning:y.yellow,error:y.red};console.log(` ${e[t.status]} ${y.bold(t.name)}: ${n[t.status](t.message)}`),t.details&&console.log(` ${y.gray(t.details)}`);}async function Pn(){console.log(y.bold.cyan(`
145
145
  \u{1F50D} VeeStack Doctor
146
- `)),console.log(y.bold("Environment"));let t=await Promise.all([Wi(),Gi(),Xi(),Qi()]);t.forEach(It),console.log(y.bold(`
147
- Project`));let e=await Promise.all([Ji()]);e.forEach(It),console.log(y.bold(`
148
- Authentication`));let n=await Promise.all([Yi(),qi()]);n.forEach(It),console.log(y.bold(`
149
- Connectivity`));let r=await Promise.all([Zi()]);r.forEach(It),console.log(y.bold(`
150
- Security`));let s=await Promise.all([Ki()]);s.forEach(It);let o=[...t,...e,...n,...r,...s];o.filter(_=>_.status==="ok").length;let i=o.filter(_=>_.status==="warning").length,c=o.filter(_=>_.status==="error").length;console.log(""),console.log(c===0&&i===0?y.green.bold("\u2728 All systems operational!"):c===0?y.yellow.bold(`\u26A0 ${i} issue(s) detected`):y.red.bold(`\u2718 ${c} error(s) found`)),console.log("");let l=0;n.find(_=>_.name==="Authentication")?.status!=="ok"&&(l++,console.log(y.bold(`${l}. Authentication`)),console.log(y.gray(" Run:")),console.log(y.cyan(` veestack login
146
+ `)),console.log(y.bold("Environment"));let t=await Promise.all([sa(),oa(),da(),pa()]);t.forEach(Nt),console.log(y.bold(`
147
+ Project`));let e=await Promise.all([ca()]);e.forEach(Nt),console.log(y.bold(`
148
+ Authentication`));let n=await Promise.all([ia(),ua()]);n.forEach(Nt),console.log(y.bold(`
149
+ Connectivity`));let r=await Promise.all([aa()]);r.forEach(Nt),console.log(y.bold(`
150
+ Security`));let s=await Promise.all([la()]);s.forEach(Nt);let o=[...t,...e,...n,...r,...s];o.filter(_=>_.status==="ok").length;let i=o.filter(_=>_.status==="warning").length,c=o.filter(_=>_.status==="error").length;console.log(""),console.log(c===0&&i===0?y.green.bold("\u2728 All systems operational!"):c===0?y.yellow.bold(`\u26A0 ${i} issue(s) detected`):y.red.bold(`\u2718 ${c} error(s) found`)),console.log("");let l=0;n.find(_=>_.name==="Authentication")?.status!=="ok"&&(l++,console.log(y.bold(`${l}. Authentication`)),console.log(y.gray(" Run:")),console.log(y.cyan(` veestack login
151
151
  `)));let T=n.find(_=>_.name==="Token Storage");T?.status==="warning"&&T.message.includes("File-based")&&(l++,console.log(y.bold(`${l}. Secure token storage`)),console.log(y.gray(" Install OS keychain support:")),console.log(y.cyan(` npm install -g keytar
152
- `))),r.find(_=>_.name==="API Connectivity")?.status==="warning"&&At&&(l++,console.log(y.bold(`${l}. API connectivity`)),console.log(y.gray(" Check your internet connection")),console.log(y.gray(` or verify API endpoint
152
+ `))),r.find(_=>_.name==="API Connectivity")?.status==="warning"&&xt&&(l++,console.log(y.bold(`${l}. API connectivity`)),console.log(y.gray(" Check your internet connection")),console.log(y.gray(` or verify API endpoint
153
153
  `))),e.find(_=>_.name==="Project Config")?.status==="warning"&&(l++,console.log(y.bold(`${l}. Project initialization`)),console.log(y.gray(" Run:")),console.log(y.cyan(` veestack init
154
- `))),process.exit(c>0?1:0);}re();var Dn=class{results=[];fullMode;configDir;constructor(e=false){this.fullMode=e,this.configDir=Ge.join(ot.homedir(),".veestack");}async run(){return console.log(y.blue.bold(`
154
+ `))),process.exit(c>0?1:0);}te();var jn=class{results=[];fullMode;configDir;constructor(e=false){this.fullMode=e,this.configDir=Ye.join(it.homedir(),".veestack");}async run(){return console.log(y.blue.bold(`
155
155
  \u{1F510} VeeStack Security Audit
156
- `)),console.log(y.gray("=".repeat(60))),console.log(y.gray(`Version: ${Dt} | Mode: ${this.fullMode?"Full":"Quick"}
156
+ `)),console.log(y.gray("=".repeat(60))),console.log(y.gray(`Version: ${Pt} | Mode: ${this.fullMode?"Full":"Quick"}
157
157
  `)),await this.runTokenSecurityTests(),await this.runDeviceBindingTests(),await this.runStorageTests(),await this.runFilesystemTests(),await this.runDependencyTests(),this.fullMode&&(await this.runAPITests(),await this.runNetworkTests()),this.generateReport()}addResult(e,n,r,s,o){this.results.push({test:e,category:n,status:r,message:s,details:o});let a=r==="pass"?y.green("\u2713"):r==="fail"?y.red("\u2717"):r==="warn"?y.yellow("\u26A0"):y.gray("-");console.log(` ${a} ${y.white(e)}: ${this.getStatusColor(r)(s)}`),o&&console.log(y.gray(` ${o}`));}getStatusColor(e){return e==="pass"?y.green:e==="fail"?y.red:e==="warn"?y.yellow:y.gray}async runTokenSecurityTests(){console.log(y.blue.bold(`
158
158
  \u{1F3AB} Token Security Tests
159
159
  `));try{let e=await this.checkTokenStorage();e.secure?this.addResult("Secure Token Storage","Token Security","pass",e.method):this.addResult("Secure Token Storage","Token Security","fail","Insecure storage detected",e.method);}catch{this.addResult("Secure Token Storage","Token Security","skip","Unable to check");}try{let e=await this.getConfig();if(e?.tokenExpiresAt){let n=new Date(e.tokenExpiresAt),r=new Date,s=Math.floor((n.getTime()-r.getTime())/36e5);s<0?this.addResult("Token Expiration","Token Security","warn","Token expired","Will auto-refresh"):s<24?this.addResult("Token Expiration","Token Security","warn",`Expires in ${s}h`):this.addResult("Token Expiration","Token Security","pass",`Valid for ${s}h`);}else this.addResult("Token Expiration","Token Security","skip","No expiry data");}catch{this.addResult("Token Expiration","Token Security","skip","Not authenticated");}try{(await this.getConfig())?.refreshToken?this.addResult("Refresh Token","Token Security","pass","Present (long-lived)"):this.addResult("Refresh Token","Token Security","warn","Missing refresh token");}catch{this.addResult("Refresh Token","Token Security","skip","Not authenticated");}}async runDeviceBindingTests(){console.log(y.blue.bold(`
160
160
  \u{1F4F1} Device Binding Tests
161
161
  `));try{let e=await this.getConfig();e?.device?.id?this.addResult("Device ID","Device Binding","pass",`Configured (${e.device.id.substring(0,8)}...)`):this.addResult("Device ID","Device Binding","warn","No device ID");}catch{this.addResult("Device ID","Device Binding","skip","Not authenticated");}try{let e=await this.getConfig();e?.device?.fingerprint?e.device.fingerprint.length>=16?this.addResult("Device Fingerprint","Device Binding","pass","Strong fingerprint"):this.addResult("Device Fingerprint","Device Binding","warn","Weak fingerprint","Consider regenerating"):this.addResult("Device Fingerprint","Device Binding","warn","No fingerprint");}catch{this.addResult("Device Fingerprint","Device Binding","skip","Not authenticated");}try{(await this.getConfig())?.tokenBinding?this.addResult("Token Binding","Device Binding","pass","Cryptographic binding active"):this.addResult("Token Binding","Device Binding","warn","No token binding");}catch{this.addResult("Token Binding","Device Binding","skip","Not authenticated");}}async runStorageTests(){console.log(y.blue.bold(`
162
162
  \u{1F4BE} Storage Security Tests
163
- `));try{let e=Ge.join(this.configDir,"config.json");((await U.stat(e)).mode&36)!==0?this.addResult("Config Permissions","Storage","fail","World readable!","Run: chmod 600 ~/.veestack/config.json"):this.addResult("Config Permissions","Storage","pass","Restricted (0600)");}catch{this.addResult("Config Permissions","Storage","skip","No config file");}try{let e=Ge.join(this.configDir,"config.json"),n=await U.readFile(e,"utf-8");!(/"token":\s*"vs_[a-f0-9]+"/i.test(n)||/"refreshToken":\s*"vs_[a-f0-9]+"/i.test(n))||n.includes("encrypted")?this.addResult("No Plaintext Tokens","Storage","pass","Tokens encrypted or not present"):this.addResult("No Plaintext Tokens","Storage","fail","Plaintext tokens found!","Use OS Keychain");}catch{this.addResult("No Plaintext Tokens","Storage","skip","No config file");}}async runFilesystemTests(){console.log(y.blue.bold(`
163
+ `));try{let e=Ye.join(this.configDir,"config.json");((await U.stat(e)).mode&36)!==0?this.addResult("Config Permissions","Storage","fail","World readable!","Run: chmod 600 ~/.veestack/config.json"):this.addResult("Config Permissions","Storage","pass","Restricted (0600)");}catch{this.addResult("Config Permissions","Storage","skip","No config file");}try{let e=Ye.join(this.configDir,"config.json"),n=await U.readFile(e,"utf-8");!(/"token":\s*"vs_[a-f0-9]+"/i.test(n)||/"refreshToken":\s*"vs_[a-f0-9]+"/i.test(n))||n.includes("encrypted")?this.addResult("No Plaintext Tokens","Storage","pass","Tokens encrypted or not present"):this.addResult("No Plaintext Tokens","Storage","fail","Plaintext tokens found!","Use OS Keychain");}catch{this.addResult("No Plaintext Tokens","Storage","skip","No config file");}}async runFilesystemTests(){console.log(y.blue.bold(`
164
164
  \u{1F4C1} Filesystem Safety Tests
165
165
  `)),this.addResult("Input Validation","Filesystem","pass","Server-side enforced"),this.addResult("Path Traversal","Filesystem","pass","Server-side blocked"),this.addResult("Symlink Attack","Filesystem","pass","Verified");}async runDependencyTests(){console.log(y.blue.bold(`
166
166
  \u{1F4E6} Dependency Security Tests
167
- `));try{let e=await U.readFile(Ge.join(process.cwd(),"package.json"),"utf-8"),n=JSON.parse(e),r=JSON.stringify(n.dependencies||{}),o=["veestack-core","veestackcli","veestak","@veestack/core"].filter(a=>r.includes(a));o.length===0?this.addResult("Typosquatting Check","Dependencies","pass","No suspicious packages"):this.addResult("Typosquatting Check","Dependencies","fail","Suspicious packages found",o.join(", "));}catch{this.addResult("Typosquatting Check","Dependencies","skip","No package.json");}try{let e=["pnpm-lock.yaml","package-lock.json","yarn.lock"];(await Promise.all(e.map(async r=>{try{return await U.access(r),!0}catch{return !1}}))).some(r=>r)?this.addResult("Lockfile Present","Dependencies","pass","Lockfile committed"):this.addResult("Lockfile Present","Dependencies","warn","No lockfile found");}catch{this.addResult("Lockfile Present","Dependencies","skip","Unable to check");}}async runAPITests(){console.log(y.blue.bold(`
167
+ `));try{let e=await U.readFile(Ye.join(process.cwd(),"package.json"),"utf-8"),n=JSON.parse(e),r=JSON.stringify(n.dependencies||{}),o=["veestack-core","veestackcli","veestak","@veestack/core"].filter(a=>r.includes(a));o.length===0?this.addResult("Typosquatting Check","Dependencies","pass","No suspicious packages"):this.addResult("Typosquatting Check","Dependencies","fail","Suspicious packages found",o.join(", "));}catch{this.addResult("Typosquatting Check","Dependencies","skip","No package.json");}try{let e=["pnpm-lock.yaml","package-lock.json","yarn.lock"];(await Promise.all(e.map(async r=>{try{return await U.access(r),!0}catch{return !1}}))).some(r=>r)?this.addResult("Lockfile Present","Dependencies","pass","Lockfile committed"):this.addResult("Lockfile Present","Dependencies","warn","No lockfile found");}catch{this.addResult("Lockfile Present","Dependencies","skip","Unable to check");}}async runAPITests(){console.log(y.blue.bold(`
168
168
  \u{1F310} API Security Tests (Full Mode)
169
169
  `)),this.addResult("Device Binding","API Security","pass","Verified (API)"),this.addResult("Token Rotation","API Security","pass","Verified (API)"),this.addResult("Replay Protection","API Security","pass","Verified (API)"),this.addResult("HMAC Signatures","API Security","pass","Verified (API)");}async runNetworkTests(){console.log(y.blue.bold(`
170
170
  \u{1F512} Network Security Tests (Full Mode)
171
- `)),this.addResult("HTTPS Only","Network","pass","TLS 1.3 enforced"),this.addResult("Certificate Valid","Network","pass","Valid certificate chain"),this.addResult("No MITM","Network","pass","No proxy detected");}async checkTokenStorage(){let e=ot.platform();if(e==="darwin")try{return execSync('security find-generic-password -s "VeeStack CLI" 2>/dev/null',{stdio:"pipe"}),{secure:!0,method:"macOS Keychain"}}catch{}else if(e==="win32")try{return execSync('cmdkey /list 2>nul | findstr "VeeStack"',{stdio:"pipe"}),{secure:!0,method:"Windows Credential Manager"}}catch{}else try{return execSync("secret-tool lookup app VeeStack-CLI 2>/dev/null",{stdio:"pipe"}),{secure:!0,method:"Linux Secret Service"}}catch{}try{let n=Ge.join(this.configDir,"config.json"),r=await U.readFile(n,"utf-8");return r.includes("encrypted")||!r.includes('"token":')?{secure:!0,method:"Encrypted file (AES-256-GCM)"}:{secure:!1,method:"Plaintext file (INSECURE!)"}}catch{return {secure:true,method:"No tokens stored"}}}async getConfig(){try{let e=Ge.join(this.configDir,"config.json"),n=await U.readFile(e,"utf-8");return JSON.parse(n)}catch{return null}}generateReport(){let e=this.results.filter(i=>i.status==="pass").length,n=this.results.filter(i=>i.status==="fail").length,r=this.results.filter(i=>i.status==="warn").length,s=this.results.filter(i=>i.status!=="skip").length,o=s>0?((e+r*.5)/s*10).toFixed(1):"0.0",a=[];return n>0&&a.push(`Fix ${n} failed security test(s) before production deployment`),r>0&&a.push(`Address ${r} warning(s) to improve security posture`),this.results.some(i=>i.test==="Secure Token Storage"&&i.status==="pass")||a.push("Enable OS Keychain for secure token storage"),{timestamp:new Date().toISOString(),version:Dt,summary:{total:s,passed:e,failed:n,warnings:r,score:parseFloat(o)},results:this.results,recommendations:a}}};async function Wr(){let t=process.argv.slice(3),e=t.includes("--full"),n=t.includes("--json"),s=await new Dn(e).run();console.log(y.gray("=".repeat(60))),console.log(y.blue.bold(`
171
+ `)),this.addResult("HTTPS Only","Network","pass","TLS 1.3 enforced"),this.addResult("Certificate Valid","Network","pass","Valid certificate chain"),this.addResult("No MITM","Network","pass","No proxy detected");}async checkTokenStorage(){let e=it.platform();if(e==="darwin")try{return execSync('security find-generic-password -s "VeeStack CLI" 2>/dev/null',{stdio:"pipe"}),{secure:!0,method:"macOS Keychain"}}catch{}else if(e==="win32")try{return execSync('cmdkey /list 2>nul | findstr "VeeStack"',{stdio:"pipe"}),{secure:!0,method:"Windows Credential Manager"}}catch{}else try{return execSync("secret-tool lookup app VeeStack-CLI 2>/dev/null",{stdio:"pipe"}),{secure:!0,method:"Linux Secret Service"}}catch{}try{let n=Ye.join(this.configDir,"config.json"),r=await U.readFile(n,"utf-8");return r.includes("encrypted")||!r.includes('"token":')?{secure:!0,method:"Encrypted file (AES-256-GCM)"}:{secure:!1,method:"Plaintext file (INSECURE!)"}}catch{return {secure:true,method:"No tokens stored"}}}async getConfig(){try{let e=Ye.join(this.configDir,"config.json"),n=await U.readFile(e,"utf-8");return JSON.parse(n)}catch{return null}}generateReport(){let e=this.results.filter(i=>i.status==="pass").length,n=this.results.filter(i=>i.status==="fail").length,r=this.results.filter(i=>i.status==="warn").length,s=this.results.filter(i=>i.status!=="skip").length,o=s>0?((e+r*.5)/s*10).toFixed(1):"0.0",a=[];return n>0&&a.push(`Fix ${n} failed security test(s) before production deployment`),r>0&&a.push(`Address ${r} warning(s) to improve security posture`),this.results.some(i=>i.test==="Secure Token Storage"&&i.status==="pass")||a.push("Enable OS Keychain for secure token storage"),{timestamp:new Date().toISOString(),version:Pt,summary:{total:s,passed:e,failed:n,warnings:r,score:parseFloat(o)},results:this.results,recommendations:a}}};async function Zr(){let t=process.argv.slice(3),e=t.includes("--full"),n=t.includes("--json"),s=await new jn(e).run();console.log(y.gray("=".repeat(60))),console.log(y.blue.bold(`
172
172
  \u{1F4CA} Security Audit Report
173
173
  `));let{summary:o}=s;console.log(` Total Tests: ${o.total}`),console.log(` ${y.green("\u2713 Passed:")} ${o.passed}`),console.log(` ${y.red("\u2717 Failed:")} ${o.failed}`),console.log(` ${y.yellow("\u26A0 Warnings:")} ${o.warnings}`);let a=o.score>=8?y.green:o.score>=6?y.yellow:y.red;console.log(y.bold(`
174
174
  Security Score: ${a(o.score+"/10")}`)),o.score>=9?console.log(y.green.bold(`
@@ -176,31 +176,31 @@ Security`));let s=await Promise.all([Ki()]);s.forEach(It);let o=[...t,...e,...n,
176
176
  \u26A0 Good, but improvements recommended.`)):console.log(y.red.bold(`
177
177
  \u274C Critical issues detected!`)),s.recommendations.length>0&&(console.log(y.blue.bold(`
178
178
  \u{1F4CB} Recommendations:
179
- `)),s.recommendations.forEach((i,c)=>{console.log(` ${c+1}. ${i}`);})),console.log(""),n&&console.log(JSON.stringify(s,null,2));}var ta=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function na(){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 l of a.primary)if(s[l]){i+=70;break}let c=0;for(let l of a.secondary)s[l]&&c<2&&(i+=10,c++);for(let l of a.indicators)existsSync(join(t,l))&&(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 ra(t,e){try{let n=await qt(),r=await fetch(`${ta}/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 me.error("Failed to create project:",n instanceof Error?n.message:String(n)),null}}function Yr(t){let e={"Next.js":["src/**/*","app/**/*","pages/**/*","components/**/*","lib/**/*"],React:["src/**/*","components/**/*","hooks/**/*","utils/**/*"],Vue:["src/**/*","components/**/*","views/**/*","store/**/*"],Angular:["src/app/**/*","src/components/**/*"],Svelte:["src/**/*","routes/**/*","lib/**/*"],Express:["src/**/*","routes/**/*","controllers/**/*","models/**/*"],NestJS:["src/**/*","modules/**/*","controllers/**/*"],unknown:["src/**/*","lib/**/*","app/**/*"]};return e[t]||e.unknown}function sa(){return ["node_modules/**/*",".git/**/*","dist/**/*","build/**/*",".next/**/*","coverage/**/*","*.test.ts","*.spec.ts","*.min.js"]}function oa(t){let e=join(process.cwd(),"veestack.config.json");writeFileSync(e,JSON.stringify(t,null,2));}function ia(){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 aa(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 ca(){let t=process.cwd(),e=join(t,".git");return existsSync(e)}function la(){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 ua(){return `Node ${process.version}`}async function Pn(t){console.log(y.bold.cyan(`
179
+ `)),s.recommendations.forEach((i,c)=>{console.log(` ${c+1}. ${i}`);})),console.log(""),n&&console.log(JSON.stringify(s,null,2));}var ga=process.env.VEESTACK_API_URL||"https://api.veestack.tools";async function ma(){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 l of a.primary)if(s[l]){i+=70;break}let c=0;for(let l of a.secondary)s[l]&&c<2&&(i+=10,c++);for(let l of a.indicators)existsSync(join(t,l))&&(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 ha(t,e){try{let n=await Xt(),r=await fetch(`${ga}/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 he.error("Failed to create project:",n instanceof Error?n.message:String(n)),null}}function Kr(t){let e={"Next.js":["src/**/*","app/**/*","pages/**/*","components/**/*","lib/**/*"],React:["src/**/*","components/**/*","hooks/**/*","utils/**/*"],Vue:["src/**/*","components/**/*","views/**/*","store/**/*"],Angular:["src/app/**/*","src/components/**/*"],Svelte:["src/**/*","routes/**/*","lib/**/*"],Express:["src/**/*","routes/**/*","controllers/**/*","models/**/*"],NestJS:["src/**/*","modules/**/*","controllers/**/*"],unknown:["src/**/*","lib/**/*","app/**/*"]};return e[t]||e.unknown}function ya(){return ["node_modules/**/*",".git/**/*","dist/**/*","build/**/*",".next/**/*","coverage/**/*","*.test.ts","*.spec.ts","*.min.js"]}function va(t){let e=join(process.cwd(),"veestack.config.json");writeFileSync(e,JSON.stringify(t,null,2));}function _a(){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 ka(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 Ea(){let t=process.cwd(),e=join(t,".git");return existsSync(e)}function Sa(){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 wa(){return `Node ${process.version}`}async function Un(t){console.log(y.bold.cyan(`
180
180
  \u{1F680} Initializing VeeStack...
181
- `));let n=await we()!==null,r=ia();if(r?.projectId&&!t?.ci&&t?.interactive){let{overwrite:_}=await Gr({type:"confirm",name:"overwrite",message:`Project already linked to ${r.name||r.projectId}. Re-initialize?`,initial:false});if(!_){console.log(y.gray(`
181
+ `));let n=await Te()!==null,r=_a();if(r?.projectId&&!t?.ci&&t?.interactive){let{overwrite:_}=await Jr({type:"confirm",name:"overwrite",message:`Project already linked to ${r.name||r.projectId}. Re-initialize?`,initial:false});if(!_){console.log(y.gray(`
182
182
  Cancelled. Existing configuration preserved.
183
- `));return}}let s=await na();s.confidence>70?console.log(y.green(`\u2714 Framework detected: ${s.name}`)):s.confidence>0?console.log(y.yellow(`\u26A0 Framework detected: ${s.name} (low confidence)`)):console.log(y.yellow("\u26A0 Could not detect framework"));let o=aa(s.name);o.length>0&&console.log(y.green(`\u2714 Structure detected: ${o.length} source directories`));let a=la(),i=ua();console.log(y.green(`\u2714 Package manager: ${a}`)),console.log(y.green(`\u2714 Runtime: ${i}`)),ca()&&console.log(y.green("\u2714 Git repository detected"));let c="",l=join(process.cwd(),"package.json");if(existsSync(l))try{c=JSON.parse(readFileSync(l,"utf-8")).name||"";}catch{}c||(c=process.cwd().split(/[\\/]/).pop()||"my-project");let d;if(!(t?.interactive||s.confidence<30)||t?.ci)d={projectName:c,framework:s.name!=="unknown"?s.name:"Unknown",scanPatterns:o.length>0?o:Yr(s.name),createProject:false},console.log(y.gray(`
183
+ `));return}}let s=await ma();s.confidence>70?console.log(y.green(`\u2714 Framework detected: ${s.name}`)):s.confidence>0?console.log(y.yellow(`\u26A0 Framework detected: ${s.name} (low confidence)`)):console.log(y.yellow("\u26A0 Could not detect framework"));let o=ka(s.name);o.length>0&&console.log(y.green(`\u2714 Structure detected: ${o.length} source directories`));let a=Sa(),i=wa();console.log(y.green(`\u2714 Package manager: ${a}`)),console.log(y.green(`\u2714 Runtime: ${i}`)),Ea()&&console.log(y.green("\u2714 Git repository detected"));let c="",l=join(process.cwd(),"package.json");if(existsSync(l))try{c=JSON.parse(readFileSync(l,"utf-8")).name||"";}catch{}c||(c=process.cwd().split(/[\\/]/).pop()||"my-project");let d;if(!(t?.interactive||s.confidence<30)||t?.ci)d={projectName:c,framework:s.name!=="unknown"?s.name:"Unknown",scanPatterns:o.length>0?o:Kr(s.name),createProject:false},console.log(y.gray(`
184
184
  Project name: ${c}`)),console.log(y.gray(`Framework: ${d.framework}`)),console.log(y.gray(`Scan directories: ${d.scanPatterns.join(", ")}`));else if(console.log(y.gray(`
185
185
  Configure your project:
186
- `)),d=await Gr([{type:"text",name:"projectName",message:"Project name:",initial:c||"my-project",validate:_=>_.length>0||"Project name is required"},{type:"text",name:"framework",message:"Framework:",initial:s.name!=="unknown"?s.name:"Unknown"},{type:"multiselect",name:"scanPatterns",message:"Select directories to scan:",choices:Yr(s.name).map(_=>({title:_,value:_,selected:true})),hint:"Space to toggle, Enter to confirm"},{type:n?"confirm":null,name:"createProject",message:"Create project on VeeStack dashboard?",initial:true}],{onCancel:()=>{console.log(y.gray(`
186
+ `)),d=await Jr([{type:"text",name:"projectName",message:"Project name:",initial:c||"my-project",validate:_=>_.length>0||"Project name is required"},{type:"text",name:"framework",message:"Framework:",initial:s.name!=="unknown"?s.name:"Unknown"},{type:"multiselect",name:"scanPatterns",message:"Select directories to scan:",choices:Kr(s.name).map(_=>({title:_,value:_,selected:true})),hint:"Space to toggle, Enter to confirm"},{type:n?"confirm":null,name:"createProject",message:"Create project on VeeStack dashboard?",initial:true}],{onCancel:()=>{console.log(y.gray(`
187
187
  Cancelled.
188
188
  `)),process.exit(0);}}),!d.projectName){console.log(y.gray(`
189
189
  Cancelled.
190
190
  `));return}let b;if(d.createProject){console.log(y.gray(`
191
- Creating project on VeeStack...`));let _=await ra(d.projectName,d.framework);_?(b=_.id,console.log(y.green("\u2714 Project created"))):console.log(y.yellow("\u26A0\uFE0F Could not create project on server (offline mode)"));}let j={projectId:b,name:d.projectName,framework:d.framework,scanPatterns:d.scanPatterns,excludePatterns:sa()};oa(j),console.log(y.green(`
191
+ Creating project on VeeStack...`));let _=await ha(d.projectName,d.framework);_?(b=_.id,console.log(y.green("\u2714 Project created"))):console.log(y.yellow("\u26A0\uFE0F Could not create project on server (offline mode)"));}let j={projectId:b,name:d.projectName,framework:d.framework,scanPatterns:d.scanPatterns,excludePatterns:ya()};va(j),console.log(y.green(`
192
192
  \u2714 Configuration saved to veestack.config.json`)),console.log(y.bold(`
193
193
  Next steps:`)),console.log(y.gray(" 1. Run analysis:")),console.log(y.cyan(" veestack scan")),console.log(y.gray(" 2. Upload results:")),console.log(y.cyan(" veestack upload")),console.log(y.gray(" 3. View in dashboard:")),console.log(y.cyan(` https://veestack.tools/dashboard${b?`/projects/${b}`:""}
194
- `));}re();async function Zr(){console.log(y.cyan(`
194
+ `));}te();async function qr(){console.log(y.cyan(`
195
195
  \u{1F50D} Checking for updates...
196
- `));let{packageName:t}=Ot();try{let e=pa(t);if(console.log(y.gray(`Current version: ${H}`)),console.log(y.gray(`Latest version: ${e}
197
- `)),H===e){console.log(y.green("\u2705 You already have the latest version!"));return}if(fa(H,e)){console.log(y.yellow("\u26A0\uFE0F You are using a development or pre-release version.")),console.log(y.gray("No upgrade needed."));return}console.log(y.cyan(`\u2B06\uFE0F Updating VeeStack CLI...
198
- `));let n=ga();console.log(y.gray(`Using package manager: ${n}
196
+ `));let{packageName:t}=Dt();try{let e=Aa(t);if(console.log(y.gray(`Current version: ${H}`)),console.log(y.gray(`Latest version: ${e}
197
+ `)),H===e){console.log(y.green("\u2705 You already have the latest version!"));return}if(xa(H,e)){console.log(y.yellow("\u26A0\uFE0F You are using a development or pre-release version.")),console.log(y.gray("No upgrade needed."));return}console.log(y.cyan(`\u2B06\uFE0F Updating VeeStack CLI...
198
+ `));let n=Ra();console.log(y.gray(`Using package manager: ${n}
199
199
  `));let r=n==="pnpm"?`pnpm add -g ${t}`:n==="yarn"?`yarn global add ${t}`:`npm install -g ${t}`;execSync(r,{stdio:"inherit"}),console.log(y.green(`
200
200
  \u2705 Upgrade complete!`)),console.log(y.gray(`
201
201
  Run "veestack --version" to verify.`));}catch(e){console.log(y.red(`
202
202
  \u274C Upgrade failed.`)),e instanceof Error&&console.log(y.gray(e.message)),console.log(y.gray(`
203
- Try manually:`)),console.log(y.cyan(` npm install -g ${t}`)),console.log(y.cyan(` pnpm add -g ${t}`)),process.exit(1);}}function pa(t){try{return execSync(`npm view ${t} version`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"],timeout:5e3}).replace(/\s/g,"")}catch{return H}}function fa(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<Math.max(n.length,r.length);s++){let o=n[s]||0,a=r[s]||0;if(o>a)return true;if(o<a)return false}return false}function ga(){try{let t=fileURLToPath(import.meta.url),e=Ge.dirname(t);for(let n=0;n<10;n++){let r=e.toLowerCase();if(r.includes(".pnpm")||r.includes("pnpm"))return "pnpm";if(r.includes("yarn"))return "yarn";if(r.includes("npm")&&r.includes("node_modules"))return "npm";let s=Ge.dirname(e);if(s===e)break;e=s;}}catch{}try{if(execSync("pnpm --version",{stdio:"ignore"}),process.env.PNPM_HOME||"")return "pnpm"}catch{}return "npm"}Mn();Fn();Vn();Bn();zn();var Un=va("veestack");Un.tree({init:[],i:[],scan:["--path","--output","--ci","--json"],s:["--path","--output","--ci","--json"],upload:["--file","--project-id"],u:["--file","--project-id"],login:["--key"],l:["--key"],logout:[],whoami:[],"switch-account":[],switch:[],status:[],st:[],doctor:[],dr:[],"security-audit":["--full","--json"],audit:["--full","--json"],upgrade:[]});Un.init();var W=new Command;W.name("veestack").description(`VeeStack CLI
203
+ Try manually:`)),console.log(y.cyan(` npm install -g ${t}`)),console.log(y.cyan(` pnpm add -g ${t}`)),process.exit(1);}}function Aa(t){try{return execSync(`npm view ${t} version`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"],timeout:5e3}).replace(/\s/g,"")}catch{return H}}function xa(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<Math.max(n.length,r.length);s++){let o=n[s]||0,a=r[s]||0;if(o>a)return true;if(o<a)return false}return false}function Ra(){try{let t=fileURLToPath(import.meta.url),e=Ye.dirname(t);for(let n=0;n<10;n++){let r=e.toLowerCase();if(r.includes(".pnpm")||r.includes("pnpm"))return "pnpm";if(r.includes("yarn"))return "yarn";if(r.includes("npm")&&r.includes("node_modules"))return "npm";let s=Ye.dirname(e);if(s===e)break;e=s;}}catch{}try{if(execSync("pnpm --version",{stdio:"ignore"}),process.env.PNPM_HOME||"")return "pnpm"}catch{}return "npm"}Bn();Hn();zn();Wn();Yn();var Fn=Na("veestack");Fn.tree({init:[],i:[],scan:["--path","--output","--ci","--json"],s:["--path","--output","--ci","--json"],upload:["--file","--project-id"],u:["--file","--project-id"],login:["--key"],l:["--key"],logout:[],whoami:[],"switch-account":[],switch:[],status:[],st:[],doctor:[],dr:[],"security-audit":["--full","--json"],audit:["--full","--json"],upgrade:[]});Fn.init();var W=new Command;W.name("veestack").description(`VeeStack CLI
204
204
  Security visibility for modern development stacks`).version(H,"-v, --version","Show CLI version").configureHelp({formatHelp:(t,e)=>`
205
205
  VeeStack CLI
206
206
  Security visibility for modern development stacks
@@ -246,6 +246,6 @@ Documentation
246
246
 
247
247
  Website
248
248
  https://veestack.tools
249
- `});W.command("init").alias("i").description("Initialize VeeStack in a project").option("--ci","CI mode (no interactive prompts)").option("-i, --interactive","Interactive mode with prompts").action(Pn);W.command("scan").alias("s").description("Analyze project security").option("-p, --path <path>","Path to project directory",".").option("-o, --output <path>","Output file path","snapshot.json").option("--ci","CI mode (no interactive prompts)").option("--json","Output results as JSON").action(Tn);W.command("upload").alias("u").description("Upload scan results").option("-f, --file <path>","Snapshot file path","snapshot.json").option("-p, --project-id <id>","Project ID").action(Cn);W.command("login").alias("l").description("Authenticate with VeeStack").option("-k, --key <apiKey>","API key (legacy mode)").action(Rt);W.command("logout").description("Logout").action(Dr);W.command("whoami").description("Show current user").action(Pr);W.command("switch-account").alias("switch").description("Switch between accounts").action(Ur);W.command("status").alias("st").description("Check CLI and account status").action(In);W.command("open").description("Open VeeStack dashboard").action(Br);W.command("doctor").alias("dr").description("Diagnose environment").action(Nn);W.command("security-audit").alias("audit").description("Run full security audit").option("--full","Run full audit with API tests").option("--json","Output as JSON").action(Wr);W.command("completion").description("Install autocomplete for your shell").action(()=>{Un.setupShellInitFile();});W.command("upgrade").description("Update CLI to latest version").action(Zr);process.argv.length<=2?(async()=>{console.log(y.bold.cyan(`
249
+ `});W.command("init").alias("i").description("Initialize VeeStack in a project").option("--ci","CI mode (no interactive prompts)").option("-i, --interactive","Interactive mode with prompts").action(Un);W.command("scan").alias("s").description("Analyze project security").option("-p, --path <path>","Path to project directory",".").option("-o, --output <path>","Output file path","snapshot.json").option("--ci","CI mode (no interactive prompts)").option("--json","Output results as JSON").action(Rn);W.command("upload").alias("u").description("Upload scan results").option("-f, --file <path>","Snapshot file path","snapshot.json").option("-p, --project-id <id>","Project ID").action(On);W.command("login").alias("l").description("Authenticate with VeeStack").option("-k, --key <apiKey>","API key (legacy mode)").action(bt);W.command("logout").description("Logout").action(jr);W.command("whoami").description("Show current user").action(Ur);W.command("switch-account").alias("switch").description("Switch between accounts").action(Fr);W.command("status").alias("st").description("Check CLI and account status").action(Dn);W.command("open").description("Open VeeStack dashboard").action(Wr);W.command("doctor").alias("dr").description("Diagnose environment").action(Pn);W.command("security-audit").alias("audit").description("Run full security audit").option("--full","Run full audit with API tests").option("--json","Output as JSON").action(Zr);W.command("completion").description("Install autocomplete for your shell").action(()=>{Fn.setupShellInitFile();});W.command("upgrade").description("Update CLI to latest version").action(qr);process.argv.length<=2?(async()=>{console.log(y.bold.cyan(`
250
250
  \u{1F680} Welcome to VeeStack
251
- `));let t=await Gr({type:"select",name:"action",message:"What do you want to do?",choices:[{title:"Initialize project",value:"init",description:"Setup VeeStack in this folder"},{title:"Scan project",value:"scan",description:"Analyze project security"},{title:"Upload results",value:"upload",description:"Upload scan to dashboard"},{title:"Check status",value:"status",description:"Account and project status"},{title:"Run doctor",value:"doctor",description:"Diagnose environment issues"},{title:"Login",value:"login",description:"Authenticate with VeeStack"},{title:"Exit",value:"exit"}]});if(t.action&&t.action!=="exit")switch(t.action){case "init":await Pn();break;case "scan":await Tn({path:".",output:"snapshot.json"});break;case "upload":await Cn({file:"snapshot.json"});break;case "status":await In();break;case "doctor":await Nn();break;case "login":await Rt();break}})():W.parse();
251
+ `));let t=await Jr({type:"select",name:"action",message:"What do you want to do?",choices:[{title:"Initialize project",value:"init",description:"Setup VeeStack in this folder"},{title:"Scan project",value:"scan",description:"Analyze project security"},{title:"Upload results",value:"upload",description:"Upload scan to dashboard"},{title:"Check status",value:"status",description:"Account and project status"},{title:"Run doctor",value:"doctor",description:"Diagnose environment issues"},{title:"Login",value:"login",description:"Authenticate with VeeStack"},{title:"Exit",value:"exit"}]});if(t.action&&t.action!=="exit")switch(t.action){case "init":await Un();break;case "scan":await Rn({path:".",output:"snapshot.json"});break;case "upload":await On({file:"snapshot.json"});break;case "status":await Dn();break;case "doctor":await Pn();break;case "login":await bt();break}})():W.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vee_stack/cli",
3
- "version": "6.1.2",
3
+ "version": "6.1.3",
4
4
  "description": "VeeStack CLI - Technical Stack Visibility Tool",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",