@oxog/vld 2.2.7 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/README.md +113 -1
- package/dist/chunks/errors-core-BU14-Dk8.js +1 -0
- package/dist/chunks/index-CKPStM3V.js +1 -0
- package/dist/cjs/chunks/errors-core-C0mA6tfa.cjs +1 -0
- package/dist/cjs/chunks/index-lejEpLfv.cjs +1 -0
- package/dist/cjs/cli/bin.cjs +1 -1
- package/dist/cjs/codecs/index.cjs +1 -1
- package/dist/cjs/coercion/index.cjs +1 -1
- package/dist/cjs/compile.cjs +1 -0
- package/dist/cjs/errors.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/locales/gu.cjs +1 -0
- package/dist/cjs/locales/index.cjs +1 -1
- package/dist/cjs/locales/kn.cjs +1 -0
- package/dist/cjs/locales/ne.cjs +1 -0
- package/dist/cjs/locales/pt-BR-v4.cjs +1 -0
- package/dist/cjs/locales/sk.cjs +1 -0
- package/dist/cjs/mini.cjs +1 -1
- package/dist/cjs/v3/index.cjs +1 -1
- package/dist/cjs/v4/core/index.cjs +1 -1
- package/dist/cjs/v4/index.cjs +1 -1
- package/dist/cjs/v4/locales/index.cjs +1 -1
- package/dist/cjs/v4/mini/index.cjs +1 -1
- package/dist/cjs/v4-mini/index.cjs +1 -1
- package/dist/cjs/validators/any.cjs +1 -1
- package/dist/cjs/validators/array-v2.cjs +1 -0
- package/dist/cjs/validators/array.cjs +1 -1
- package/dist/cjs/validators/base.cjs +1 -1
- package/dist/cjs/validators/base64.cjs +1 -1
- package/dist/cjs/validators/bigint-v2.cjs +1 -0
- package/dist/cjs/validators/bigint.cjs +1 -1
- package/dist/cjs/validators/boolean.cjs +1 -1
- package/dist/cjs/validators/codec.cjs +1 -1
- package/dist/cjs/validators/composite-v2.cjs +1 -0
- package/dist/cjs/validators/custom.cjs +1 -1
- package/dist/cjs/validators/date-v2.cjs +1 -0
- package/dist/cjs/validators/date.cjs +1 -1
- package/dist/cjs/validators/discriminated-union.cjs +1 -1
- package/dist/cjs/validators/enum.cjs +1 -1
- package/dist/cjs/validators/file.cjs +1 -1
- package/dist/cjs/validators/function.cjs +1 -1
- package/dist/cjs/validators/hex.cjs +1 -1
- package/dist/cjs/validators/index.cjs +1 -1
- package/dist/cjs/validators/intersection.cjs +1 -1
- package/dist/cjs/validators/json.cjs +1 -1
- package/dist/cjs/validators/lazy.cjs +1 -1
- package/dist/cjs/validators/leaf-v2.cjs +1 -0
- package/dist/cjs/validators/literal.cjs +1 -1
- package/dist/cjs/validators/map.cjs +1 -1
- package/dist/cjs/validators/nan.cjs +1 -1
- package/dist/cjs/validators/never.cjs +1 -1
- package/dist/cjs/validators/null.cjs +1 -1
- package/dist/cjs/validators/number-v2.cjs +1 -0
- package/dist/cjs/validators/number.cjs +1 -1
- package/dist/cjs/validators/object-v2.cjs +1 -0
- package/dist/cjs/validators/object.cjs +1 -1
- package/dist/cjs/validators/promise.cjs +1 -1
- package/dist/cjs/validators/record.cjs +1 -1
- package/dist/cjs/validators/set.cjs +1 -1
- package/dist/cjs/validators/string-bool.cjs +1 -1
- package/dist/cjs/validators/string-formats.cjs +1 -1
- package/dist/cjs/validators/string-v2.cjs +1 -0
- package/dist/cjs/validators/string.cjs +1 -1
- package/dist/cjs/validators/symbol.cjs +1 -1
- package/dist/cjs/validators/template-literal.cjs +1 -1
- package/dist/cjs/validators/tuple.cjs +1 -1
- package/dist/cjs/validators/uint8array.cjs +1 -1
- package/dist/cjs/validators/undefined.cjs +1 -1
- package/dist/cjs/validators/union-v2.cjs +1 -0
- package/dist/cjs/validators/union.cjs +1 -1
- package/dist/cjs/validators/unknown.cjs +1 -1
- package/dist/cjs/validators/void.cjs +1 -1
- package/dist/cjs/validators/wrapper-v2.cjs +1 -0
- package/dist/cjs/validators/xor.cjs +1 -1
- package/dist/compile.d.ts +81 -0
- package/dist/compile.js +1 -0
- package/dist/errors-core.d.ts +3 -0
- package/dist/errors.js +1 -1
- package/dist/index.d.ts +484 -21
- package/dist/index.js +1 -1
- package/dist/locales/gu.d.ts +2 -0
- package/dist/locales/gu.js +1 -0
- package/dist/locales/index.js +1 -1
- package/dist/locales/kn.d.ts +2 -0
- package/dist/locales/kn.js +1 -0
- package/dist/locales/ne.d.ts +2 -0
- package/dist/locales/ne.js +1 -0
- package/dist/locales/pt-BR-v4.d.ts +2 -0
- package/dist/locales/pt-BR-v4.js +1 -0
- package/dist/locales/sk.d.ts +2 -0
- package/dist/locales/sk.js +1 -0
- package/dist/v3/index.js +1 -1
- package/dist/v4/core/index.d.ts +13 -0
- package/dist/v4/core/index.js +1 -1
- package/dist/v4/index.d.ts +1 -0
- package/dist/v4/index.js +1 -1
- package/dist/v4/locales/index.d.ts +6 -0
- package/dist/v4/locales/index.js +1 -1
- package/dist/v4/mini/index.js +1 -1
- package/dist/v4-mini/index.d.ts +2 -0
- package/dist/v4-mini/index.js +1 -1
- package/dist/validators/array-v2.d.ts +113 -0
- package/dist/validators/array-v2.js +1 -0
- package/dist/validators/array.js +1 -1
- package/dist/validators/base.js +1 -1
- package/dist/validators/base64.js +1 -1
- package/dist/validators/bigint-v2.d.ts +105 -0
- package/dist/validators/bigint-v2.js +1 -0
- package/dist/validators/bigint.js +1 -1
- package/dist/validators/boolean.js +1 -1
- package/dist/validators/codec.js +1 -1
- package/dist/validators/composite-v2.d.ts +59 -0
- package/dist/validators/composite-v2.js +1 -0
- package/dist/validators/custom.js +1 -1
- package/dist/validators/date-v2.d.ts +140 -0
- package/dist/validators/date-v2.js +1 -0
- package/dist/validators/date.js +1 -1
- package/dist/validators/enum.js +1 -1
- package/dist/validators/file.js +1 -1
- package/dist/validators/function.js +1 -1
- package/dist/validators/hex.js +1 -1
- package/dist/validators/intersection.js +1 -1
- package/dist/validators/leaf-v2.d.ts +138 -0
- package/dist/validators/leaf-v2.js +1 -0
- package/dist/validators/literal.js +1 -1
- package/dist/validators/map.js +1 -1
- package/dist/validators/nan.js +1 -1
- package/dist/validators/never.js +1 -1
- package/dist/validators/null.js +1 -1
- package/dist/validators/number-v2.d.ts +252 -0
- package/dist/validators/number-v2.js +1 -0
- package/dist/validators/number.js +1 -1
- package/dist/validators/object-v2.d.ts +40 -0
- package/dist/validators/object-v2.js +1 -0
- package/dist/validators/object.d.ts +9 -0
- package/dist/validators/object.js +1 -1
- package/dist/validators/record.js +1 -1
- package/dist/validators/set.js +1 -1
- package/dist/validators/string-formats.d.ts +1 -0
- package/dist/validators/string-formats.js +1 -1
- package/dist/validators/string-v2.d.ts +274 -0
- package/dist/validators/string-v2.js +1 -0
- package/dist/validators/string.js +1 -1
- package/dist/validators/symbol.js +1 -1
- package/dist/validators/tuple.js +1 -1
- package/dist/validators/uint8array.js +1 -1
- package/dist/validators/undefined.js +1 -1
- package/dist/validators/union-v2.d.ts +28 -0
- package/dist/validators/union-v2.js +1 -0
- package/dist/validators/void.js +1 -1
- package/dist/validators/wrapper-v2.d.ts +74 -0
- package/dist/validators/wrapper-v2.js +1 -0
- package/dist/zod-error.d.ts +84 -0
- package/package.json +7 -2
- package/dist/chunks/errors-core-CerMg2rq.js +0 -1
- package/dist/chunks/index-yjpbvFgw.js +0 -1
- package/dist/cjs/chunks/errors-core-DrydF46s.cjs +0 -1
- package/dist/cjs/chunks/index-BEV9nG0N.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),s=require("../locales/runtime.cjs"),r=require("../chunks/ip-validation-BZqPamPC.cjs"),t=require("../chunks/errors-core-DrydF46s.cjs");require("../registry.cjs"),require("../locales/en.cjs");const i={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,url:/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,uuidv4:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv6:/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv7:/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,emoji:/^(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(?:\u200D(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,base64url:/^[A-Za-z0-9_-]*$/,jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,nanoid:/^[A-Za-z0-9_-]{21}$/,cuid:/^c[^\s-]{8,}$/i,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,cidrv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(?:3[0-2]|[12]?[0-9])$/,cidrv6:/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^(?:[0-9a-fA-F]{1,4}:){1,7}:\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e164:/^\+[1-9]\d{1,14}$/,xid:/^[A-HJKMNP-TV-Z0-9]{20}$/,guid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i,ksuid:/^[0-9A-Za-z]{27}$/,isoDate:/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/,isoTime:/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?$/,isoDateTime:/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z?$/,isoDuration:/^-?P(?!$)(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?=\d)(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/};class VldString extends e.VldBase{constructor(s){super(s?.validatorType||e.VLD_VALIDATOR_TYPES.STRING),this.config={checks:s?.checks||[],transforms:s?.transforms||[],errorMessage:s?.errorMessage,jsonSchema:s?.jsonSchema,checkMetas:s?.checkMetas},this._checks=this.config.checks,this._transforms=this.config.transforms,this._isSimple=0===this._checks.length&&0===this._transforms.length,this._checkMetas=this.config.checkMetas}static create(){return new VldString}get isSimple(){return this._isSimple}get minLength(){return this.config.jsonSchema?.minLength??null}get maxLength(){return this.config.jsonSchema?.maxLength??null}_createCheckIssue(e){switch(e.kind){case"min":return{code:"too_small",path:[],origin:"string",minimum:e.value,inclusive:!0,message:e.message||`Too small: expected string to have >=${e.value} characters`};case"max":return{code:"too_big",path:[],origin:"string",maximum:e.value,inclusive:!0,message:e.message||`Too big: expected string to have <=${e.value} characters`};case"length":return{code:"too_big",path:[],origin:"string",exact:e.value,message:e.message||`Too big: expected string to have exactly ${e.value} characters`};case"format":{const s={code:"invalid_format",path:[],origin:"string",format:e.format,message:e.message||`Invalid ${e.format}`};return void 0!==e.pattern&&(s.pattern=e.pattern),s}case"regex":{const s={code:"invalid_format",path:[],origin:"string",format:"regex",message:e.message||"Invalid string: does not match pattern"};return void 0!==e.pattern&&(s.pattern=e.pattern),s}default:return{code:"custom",path:[],message:e.message||"Invalid string"}}}_runChecks(e){const s=this._checks,r=this._checkMetas;for(let t=0;t<s.length;t++)if(!s[t](e))return r?.[t]??this._fallbackMeta();return null}_fallbackMeta(){return{kind:"other",message:this.config.errorMessage}}parse(e){if("string"!=typeof e)throw new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)]);return this._isSimple?e:this.parseKnownString(e)}parseKnownString(e){if(this._isSimple)return e;const s=this._transforms;let r=e;switch(s.length){case 0:break;case 1:r=s[0](r);break;case 2:r=s[1](s[0](r));break;case 3:r=s[2](s[1](s[0](r)));break;default:for(let e=0;e<s.length;e++)r=s[e](r)}const i=this._runChecks(r);if(i)throw new t.VldError([this._createCheckIssue(i)]);return r}safeParse(e){if("string"!=typeof e)return{success:!1,error:new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)])};if(this._isSimple)return{success:!0,data:e};try{return{success:!0,data:this.parseKnownString(e)}}catch(e){return e instanceof t.VldError?{success:!1,error:e}:{success:!1,error:(s=e.message,new t.VldError([{code:"invalid_string",path:[],message:s}]))}}var s}min(r,t){return new VldString({checks:[...this.config.checks,e=>e.length>=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMin(r)),jsonSchema:{...this.config.jsonSchema,minLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMin(r))}]})}max(r,t){return new VldString({checks:[...this.config.checks,e=>e.length<=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMax(r)),jsonSchema:{...this.config.jsonSchema,maxLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMax(r))}]})}length(r,t){return new VldString({checks:[...this.config.checks,e=>e.length===r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringLength(r)),jsonSchema:{...this.config.jsonSchema,exactLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"length",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringLength(r))}]})}email(r){return new VldString({checks:[...this.config.checks,e=>i.email.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmail),jsonSchema:{...this.config.jsonSchema,format:"email"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"email",message:e.resolveErrorMessage(r,s.getMessages().stringEmail)}]})}url(r){return new VldString({checks:[...this.config.checks,e=>i.url.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUrl),jsonSchema:{...this.config.jsonSchema,format:"uri"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"url",message:e.resolveErrorMessage(r,s.getMessages().stringUrl)}]})}uuid(r){return new VldString({checks:[...this.config.checks,e=>i.uuid.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUuid),jsonSchema:{...this.config.jsonSchema,format:"uuid"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"uuid",message:e.resolveErrorMessage(r,s.getMessages().stringUuid)}]})}format(s,r,t){return new VldString({checks:[...this.config.checks,e=>s.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,`Invalid ${r}`),jsonSchema:{...this.config.jsonSchema,format:r,pattern:s.source},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:r,pattern:s.source,message:e.resolveErrorMessage(t,`Invalid ${r}`)}]})}uuidv4(e){return this.format(i.uuidv4,"uuid",e)}uuidv6(e){return this.format(i.uuidv6,"uuid",e)}uuidv7(e){return this.format(i.uuidv7,"uuid",e)}emoji(e){return this.format(i.emoji,"emoji",e)}base64(e){return this.format(i.base64,"base64",e)}base64url(e){return this.format(i.base64url,"base64url",e)}jwt(e){return this.format(i.jwt,"jwt",e)}nanoid(e){return this.format(i.nanoid,"nanoid",e)}cuid(e){return this.format(i.cuid,"cuid",e)}cuid2(e){return this.format(i.cuid2,"cuid2",e)}ulid(e){return this.format(i.ulid,"ulid",e)}cidrv4(e){return this.format(i.cidrv4,"cidrv4",e)}cidrv6(e){return this.format(i.cidrv6,"cidrv6",e)}e164(e){return this.format(i.e164,"e164",e)}xid(e){return this.format(i.xid,"xid",e)}guid(e){return this.format(i.guid,"guid",e)}ksuid(e){return this.format(i.ksuid,"ksuid",e)}date(e){return this.format(i.isoDate,"date",e)}time(e){return this.format(i.isoTime,"time",e)}datetime(e){return this.format(i.isoDateTime,"datetime",e)}duration(e){return this.format(i.isoDuration,"duration",e)}regex(r,t){return new VldString({checks:[...this.config.checks,e=>r.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringRegex),jsonSchema:{...this.config.jsonSchema,pattern:r.source},checkMetas:[...this.config.checkMetas??[],{kind:"regex",pattern:r.source,message:e.resolveErrorMessage(t,s.getMessages().stringRegex)}]})}trim(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.trim()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}toLowerCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}lowercase(){return this.toLowerCase()}toUpperCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toUpperCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}uppercase(){return this.toUpperCase()}normalize(e){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,s=>s.normalize(e)],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}slugify(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}startsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.startsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringStartsWith(r)),jsonSchema:this.config.jsonSchema})}endsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.endsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringEndsWith(r)),jsonSchema:this.config.jsonSchema})}includes(r,t){return new VldString({checks:[...this.config.checks,e=>e.includes(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIncludes(r)),jsonSchema:this.config.jsonSchema})}ip(t){return new VldString({checks:[...this.config.checks,e=>!(e.length>100)&&(i.ipv4.test(e)||r.isValidIPv6(e))],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIp),jsonSchema:{...this.config.jsonSchema,format:"ip"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ip",message:e.resolveErrorMessage(t,s.getMessages().stringIp)}]})}ipv4(r){return new VldString({checks:[...this.config.checks,e=>i.ipv4.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringIpv4),jsonSchema:{...this.config.jsonSchema,format:"ipv4"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv4",message:e.resolveErrorMessage(r,s.getMessages().stringIpv4)}]})}ipv6(t){return new VldString({checks:[...this.config.checks,e=>r.isValidIPv6(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIpv6),jsonSchema:{...this.config.jsonSchema,format:"ipv6"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv6",message:e.resolveErrorMessage(t,s.getMessages().stringIpv6)}]})}nonempty(r){return new VldString({checks:[...this.config.checks,e=>e.length>0],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmpty),jsonSchema:{...this.config.jsonSchema,minLength:Math.max(this.config.jsonSchema?.minLength||0,1)},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:1,message:e.resolveErrorMessage(r,s.getMessages().stringEmpty)}]})}}exports.VldString=VldString;
|
|
1
|
+
"use strict";var e=require("./base.cjs"),s=require("../locales/runtime.cjs"),r=require("../chunks/ip-validation-BZqPamPC.cjs"),t=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");const i={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,url:/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,uuidv4:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv6:/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv7:/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,emoji:/^(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(?:\u200D(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,base64url:/^[A-Za-z0-9_-]*$/,jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,nanoid:/^[A-Za-z0-9_-]{21}$/,cuid:/^c[^\s-]{8,}$/i,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,cidrv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(?:3[0-2]|[12]?[0-9])$/,cidrv6:/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^(?:[0-9a-fA-F]{1,4}:){1,7}:\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e164:/^\+[1-9]\d{1,14}$/,xid:/^[A-HJKMNP-TV-Z0-9]{20}$/,guid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i,ksuid:/^[0-9A-Za-z]{27}$/,isoDate:/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/,isoTime:/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?$/,isoDateTime:/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z?$/,isoDuration:/^-?P(?!$)(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?=\d)(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/};class VldString extends e.VldBase{constructor(s){super(s?.validatorType||e.VLD_VALIDATOR_TYPES.STRING),this.config={checks:s?.checks||[],transforms:s?.transforms||[],errorMessage:s?.errorMessage,jsonSchema:s?.jsonSchema,checkMetas:s?.checkMetas},this._checks=this.config.checks,this._transforms=this.config.transforms,this._isSimple=0===this._checks.length&&0===this._transforms.length,this._checkMetas=this.config.checkMetas}static create(){return new VldString}get isSimple(){return this._isSimple}get minLength(){return this.config.jsonSchema?.minLength??null}get maxLength(){return this.config.jsonSchema?.maxLength??null}_createCheckIssue(e){switch(e.kind){case"min":return{code:"too_small",path:[],origin:"string",minimum:e.value,inclusive:!0,message:e.message||`Too small: expected string to have >=${e.value} characters`};case"max":return{code:"too_big",path:[],origin:"string",maximum:e.value,inclusive:!0,message:e.message||`Too big: expected string to have <=${e.value} characters`};case"length":return{code:"too_big",path:[],origin:"string",exact:e.value,message:e.message||`Too big: expected string to have exactly ${e.value} characters`};case"format":{const s={code:"invalid_format",path:[],origin:"string",format:e.format,message:e.message||`Invalid ${e.format}`};return void 0!==e.pattern&&(s.pattern=e.pattern),s}case"regex":{const s={code:"invalid_format",path:[],origin:"string",format:"regex",message:e.message||"Invalid string: does not match pattern"};return void 0!==e.pattern&&(s.pattern=e.pattern),s}default:return{code:"custom",path:[],message:e.message||"Invalid string"}}}_runChecks(e){const s=this._checks,r=this._checkMetas;for(let t=0;t<s.length;t++)if(!s[t](e))return r?.[t]??this._fallbackMeta();return null}_fallbackMeta(){return{kind:"other",message:this.config.errorMessage}}parse(e){if("string"!=typeof e)throw new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)]);return this._isSimple?e:this.parseKnownString(e)}parseKnownString(e){if(this._isSimple)return e;const s=this._transforms;let r=e;switch(s.length){case 0:break;case 1:r=s[0](r);break;case 2:r=s[1](s[0](r));break;case 3:r=s[2](s[1](s[0](r)));break;default:for(let e=0;e<s.length;e++)r=s[e](r)}const i=this._runChecks(r);if(i)throw new t.VldError([this._createCheckIssue(i)]);return r}safeParse(e){if("string"!=typeof e)return{success:!1,error:new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)])};if(this._isSimple)return{success:!0,data:e};try{return{success:!0,data:this.parseKnownString(e)}}catch(e){return e instanceof t.VldError?{success:!1,error:e}:{success:!1,error:(s=e.message,new t.VldError([{code:"invalid_string",path:[],message:s}]))}}var s}min(r,t){return new VldString({checks:[...this.config.checks,e=>e.length>=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMin(r)),jsonSchema:{...this.config.jsonSchema,minLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMin(r))}]})}max(r,t){return new VldString({checks:[...this.config.checks,e=>e.length<=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMax(r)),jsonSchema:{...this.config.jsonSchema,maxLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMax(r))}]})}length(r,t){return new VldString({checks:[...this.config.checks,e=>e.length===r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringLength(r)),jsonSchema:{...this.config.jsonSchema,exactLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"length",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringLength(r))}]})}email(r){return new VldString({checks:[...this.config.checks,e=>i.email.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmail),jsonSchema:{...this.config.jsonSchema,format:"email"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"email",message:e.resolveErrorMessage(r,s.getMessages().stringEmail)}]})}url(r){return new VldString({checks:[...this.config.checks,e=>i.url.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUrl),jsonSchema:{...this.config.jsonSchema,format:"uri"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"url",message:e.resolveErrorMessage(r,s.getMessages().stringUrl)}]})}uuid(r){return new VldString({checks:[...this.config.checks,e=>i.uuid.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUuid),jsonSchema:{...this.config.jsonSchema,format:"uuid"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"uuid",message:e.resolveErrorMessage(r,s.getMessages().stringUuid)}]})}format(s,r,t){return new VldString({checks:[...this.config.checks,e=>s.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,`Invalid ${r}`),jsonSchema:{...this.config.jsonSchema,format:r,pattern:s.source},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:r,pattern:s.source,message:e.resolveErrorMessage(t,`Invalid ${r}`)}]})}uuidv4(e){return this.format(i.uuidv4,"uuid",e)}uuidv6(e){return this.format(i.uuidv6,"uuid",e)}uuidv7(e){return this.format(i.uuidv7,"uuid",e)}emoji(e){return this.format(i.emoji,"emoji",e)}base64(e){return this.format(i.base64,"base64",e)}base64url(e){return this.format(i.base64url,"base64url",e)}jwt(e){return this.format(i.jwt,"jwt",e)}nanoid(e){return this.format(i.nanoid,"nanoid",e)}cuid(e){return this.format(i.cuid,"cuid",e)}cuid2(e){return this.format(i.cuid2,"cuid2",e)}ulid(e){return this.format(i.ulid,"ulid",e)}cidrv4(e){return this.format(i.cidrv4,"cidrv4",e)}cidrv6(e){return this.format(i.cidrv6,"cidrv6",e)}e164(e){return this.format(i.e164,"e164",e)}xid(e){return this.format(i.xid,"xid",e)}guid(e){return this.format(i.guid,"guid",e)}ksuid(e){return this.format(i.ksuid,"ksuid",e)}date(e){return this.format(i.isoDate,"date",e)}time(e){return this.format(i.isoTime,"time",e)}datetime(e){return this.format(i.isoDateTime,"datetime",e)}duration(e){return this.format(i.isoDuration,"duration",e)}regex(r,t){return new VldString({checks:[...this.config.checks,e=>r.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringRegex),jsonSchema:{...this.config.jsonSchema,pattern:r.source},checkMetas:[...this.config.checkMetas??[],{kind:"regex",pattern:r.source,message:e.resolveErrorMessage(t,s.getMessages().stringRegex)}]})}trim(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.trim()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}toLowerCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}lowercase(){return this.toLowerCase()}toUpperCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toUpperCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}uppercase(){return this.toUpperCase()}normalize(e){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,s=>s.normalize(e)],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}slugify(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}startsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.startsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringStartsWith(r)),jsonSchema:this.config.jsonSchema})}endsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.endsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringEndsWith(r)),jsonSchema:this.config.jsonSchema})}includes(r,t){return new VldString({checks:[...this.config.checks,e=>e.includes(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIncludes(r)),jsonSchema:this.config.jsonSchema})}ip(t){return new VldString({checks:[...this.config.checks,e=>!(e.length>100)&&(i.ipv4.test(e)||r.isValidIPv6(e))],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIp),jsonSchema:{...this.config.jsonSchema,format:"ip"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ip",message:e.resolveErrorMessage(t,s.getMessages().stringIp)}]})}ipv4(r){return new VldString({checks:[...this.config.checks,e=>i.ipv4.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringIpv4),jsonSchema:{...this.config.jsonSchema,format:"ipv4"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv4",message:e.resolveErrorMessage(r,s.getMessages().stringIpv4)}]})}ipv6(t){return new VldString({checks:[...this.config.checks,e=>r.isValidIPv6(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIpv6),jsonSchema:{...this.config.jsonSchema,format:"ipv6"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv6",message:e.resolveErrorMessage(t,s.getMessages().stringIpv6)}]})}nonempty(r){return new VldString({checks:[...this.config.checks,e=>e.length>0],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmpty),jsonSchema:{...this.config.jsonSchema,minLength:Math.max(this.config.jsonSchema?.minLength||0,1)},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:1,message:e.resolveErrorMessage(r,s.getMessages().stringEmpty)}]})}}exports.VldString=VldString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");class VldSymbol extends e.VldBase{constructor(r){super(e.VLD_VALIDATOR_TYPES.SYMBOL),this.errorMessage=r}static create(){return new VldSymbol}get isSimple(){return!0}parse(e){if("symbol"!=typeof e)throw new Error(this.errorMessage||r.getMessages().invalidSymbol);return e}parseKnownSymbol(e){return e}safeParse(e){return"symbol"==typeof e?{success:!0,data:e}:{success:!1,error:(t=this.errorMessage||r.getMessages().invalidSymbol,new s.VldError([{code:"invalid_type",path:[],message:t}]))};var t}}exports.VldSymbol=VldSymbol;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs");require("../registry.cjs"),require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs");require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs"),require("../locales/en.cjs");class VldTemplateLiteral extends e.VldBase{constructor(r){super(e.VLD_VALIDATOR_TYPES.TEMPLATE_LITERAL),this.pattern=r}static create(...e){let r="^";for(const s of e)r+="string"==typeof s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):t(s);return r+="$",new VldTemplateLiteral(new RegExp(r))}parse(e){if("string"!=typeof e)throw new Error(r.getMessages().invalidString);if(!this.pattern.test(e))throw new Error(r.getMessages().stringPatternInvalid);return e}safeParse(r){try{return{success:!0,data:this.parse(r)}}catch(r){return{success:!1,error:e.ensureVldError(r)}}}}function t(r){switch(r.validatorType){case e.VLD_VALIDATOR_TYPES.STRING:case e.VLD_VALIDATOR_TYPES.STRING_FORMAT:return"(.+)";case e.VLD_VALIDATOR_TYPES.NUMBER:case e.VLD_VALIDATOR_TYPES.COERCE_NUMBER:return"(-?\\d+(?:\\.\\d+)?)";case e.VLD_VALIDATOR_TYPES.BIGINT:case e.VLD_VALIDATOR_TYPES.COERCE_BIGINT:return"(-?\\d+)";case e.VLD_VALIDATOR_TYPES.BOOLEAN:case e.VLD_VALIDATOR_TYPES.COERCE_BOOLEAN:return"(true|false)";case e.VLD_VALIDATOR_TYPES.NULL:return"(null)";case e.VLD_VALIDATOR_TYPES.UNDEFINED:case e.VLD_VALIDATOR_TYPES.VOID:return"(undefined)";case e.VLD_VALIDATOR_TYPES.LITERAL:{const e=r;if(void 0!==e.literal){return"("+String(e.literal).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+")"}break}}return"(.+)"}exports.VldTemplateLiteral=VldTemplateLiteral,exports.templateLiteral=function(...e){return VldTemplateLiteral.create(...e)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),t=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),t=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-C0mA6tfa.cjs");function r(e){return new s.VldError([{code:"invalid_array",path:[],message:e}])}require("../registry.cjs"),require("../locales/en.cjs");class VldTuple extends e.VldBase{constructor(t,s,r=null){super(e.VLD_VALIDATOR_TYPES.TUPLE),this.validators=t,this.errorMessage=s,this.restValidator=r,this._length=t.length,this._validatorTypes=t.map(e=>e.validatorType),this._simpleItemModes=t.map((e,t)=>this.getSimpleItemMode(e,this._validatorTypes[t])),this._simpleItemValues=t.map((e,t)=>"literal"===this._simpleItemModes[t]?e.literal:void 0)}get items(){return this.validators}getSimpleItemMode(t,s){if(!0===t.isSimple)switch(s){case e.VLD_VALIDATOR_TYPES.STRING:return"string";case e.VLD_VALIDATOR_TYPES.NUMBER:return"number";case e.VLD_VALIDATOR_TYPES.BOOLEAN:return"boolean";case e.VLD_VALIDATOR_TYPES.BIGINT:return"bigint";case e.VLD_VALIDATOR_TYPES.SYMBOL:return"symbol";case e.VLD_VALIDATOR_TYPES.NULL:return"null";case e.VLD_VALIDATOR_TYPES.UNDEFINED:case e.VLD_VALIDATOR_TYPES.VOID:return"undefinedValue";case e.VLD_VALIDATOR_TYPES.LITERAL:return"literal";case e.VLD_VALIDATOR_TYPES.ANY:case e.VLD_VALIDATOR_TYPES.UNKNOWN:return"passthrough";default:return}}getSimpleItemError(e,s,r){switch(e){case"string":return t.getMessages().invalidString;case"number":return t.getMessages().invalidNumber;case"boolean":return t.getMessages().invalidBoolean;case"bigint":return t.getMessages().invalidBigint;case"symbol":return t.getMessages().invalidSymbol;case"null":return"Expected null, received "+typeof r;case"undefinedValue":return t.getMessages().expectedUndefined;case"literal":return t.getMessages().literalExpected(JSON.stringify(s),JSON.stringify(r));default:return t.getMessages().invalidTuple}}static create(...e){return new VldTuple(e)}rest(e){return new VldTuple(this.validators,this.errorMessage,e)}parse(e){if(!Array.isArray(e))throw new Error(this.errorMessage||t.getMessages().invalidTuple);return this.parseKnownTuple(e)}parseKnownTuple(e){if(null===this.restValidator&&e.length!==this._length||null!==this.restValidator&&e.length<this._length)throw new Error(this.errorMessage||t.getMessages().tupleLength(this._length,e.length));const s=new Array(e.length);for(let r=0;r<this._length;r++){const a=this._simpleItemModes[r],i=e[r];if(void 0!==a)switch(a){case"string":if("string"!=typeof i)throw new Error(t.getMessages().arrayItem(r,t.getMessages().invalidString));s[r]=i;continue;case"number":if("number"!=typeof i||isNaN(i))throw new Error(t.getMessages().arrayItem(r,t.getMessages().invalidNumber));s[r]=i;continue;case"boolean":if("boolean"!=typeof i)throw new Error(t.getMessages().arrayItem(r,t.getMessages().invalidBoolean));s[r]=i;continue;case"bigint":if("bigint"!=typeof i)throw new Error(t.getMessages().arrayItem(r,t.getMessages().invalidBigint));s[r]=i;continue;case"symbol":if("symbol"!=typeof i)throw new Error(t.getMessages().arrayItem(r,t.getMessages().invalidSymbol));s[r]=i;continue;case"null":if(null!==i)throw new Error(t.getMessages().arrayItem(r,this.getSimpleItemError(a,void 0,i)));s[r]=null;continue;case"undefinedValue":if(void 0!==i)throw new Error(t.getMessages().arrayItem(r,t.getMessages().expectedUndefined));s[r]=void 0;continue;case"literal":{const e=this._simpleItemValues[r];if(i!==e)throw new Error(t.getMessages().arrayItem(r,this.getSimpleItemError(a,e,i)));s[r]=e;continue}case"passthrough":s[r]=i;continue}try{const e=this.validators[r];s[r]=e.parse(i)}catch(e){throw new Error(t.getMessages().arrayItem(r,e.message))}}if(this.restValidator)for(let r=this._length;r<e.length;r++)try{s[r]=this.restValidator.parse(e[r])}catch(e){throw new Error(t.getMessages().arrayItem(r,e.message))}return s}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:r(e.message)}}}encode(e){if(!Array.isArray(e))throw new Error(this.errorMessage||t.getMessages().invalidTuple);this.validateEncodedLength(e.length);const s=new Array(e.length);for(let t=0;t<this._length;t++)s[t]=this.validators[t].encode(e[t]);if(this.restValidator)for(let t=this._length;t<e.length;t++)s[t]=this.restValidator.encode(e[t]);return s}safeEncode(e){try{return{success:!0,data:this.encode(e)}}catch(e){return{success:!1,error:r(e.message)}}}async encodeAsync(e){if(!Array.isArray(e))throw new Error(this.errorMessage||t.getMessages().invalidTuple);this.validateEncodedLength(e.length);const s=new Array(e.length);for(let t=0;t<this._length;t++)s[t]=await this.validators[t].encodeAsync(e[t]);if(this.restValidator)for(let t=this._length;t<e.length;t++)s[t]=await this.restValidator.encodeAsync(e[t]);return s}async safeEncodeAsync(e){try{return{success:!0,data:await this.encodeAsync(e)}}catch(e){return{success:!1,error:r(e.message)}}}validateEncodedLength(e){if(null===this.restValidator&&e!==this._length||null!==this.restValidator&&e<this._length)throw new Error(this.errorMessage||t.getMessages().tupleLength(this._length,e))}}exports.VldTuple=VldTuple;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),r=require("../errors.cjs"),t=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../errors.cjs"),t=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../pigment.cjs"),require("../locales/en.cjs");class VldUint8Array extends e.VldBase{constructor(r){super(e.VLD_VALIDATOR_TYPES.UINT8_ARRAY),this.config=r||{}}parse(e){const r=this.safeParse(e);if(!r.success)throw r.error;return r.data}safeParse(e){return e instanceof Uint8Array?void 0!==this.config.exactLength&&e.length!==this.config.exactLength?{success:!1,error:new s.VldError([r.createIssue("custom",[],t.getMessages().uint8ArrayExactLength(this.config.exactLength))])}:void 0!==this.config.minLength&&e.length<this.config.minLength?{success:!1,error:new s.VldError([r.createIssue("custom",[],t.getMessages().uint8ArrayMinLength(this.config.minLength))])}:void 0!==this.config.maxLength&&e.length>this.config.maxLength?{success:!1,error:new s.VldError([r.createIssue("custom",[],t.getMessages().uint8ArrayMaxLength(this.config.maxLength))])}:{success:!0,data:e}:{success:!1,error:new s.VldError([r.createIssue("invalid_type",[],t.getMessages().expectedUint8Array)])}}min(e){return new VldUint8Array({...this.config,minLength:e})}max(e){return new VldUint8Array({...this.config,maxLength:e})}length(e){return new VldUint8Array({exactLength:e,minLength:void 0,maxLength:void 0})}static create(){return new VldUint8Array}}exports.VldUint8Array=VldUint8Array;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),r=require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs");class VldUndefined extends e.VldBase{constructor(){super(e.VLD_VALIDATOR_TYPES.UNDEFINED)}static create(){return new VldUndefined}get isSimple(){return!0}parse(e){if(void 0!==e)throw new Error("Expected undefined, received "+typeof e)}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(s=e.message,new r.VldError([{code:"invalid_type",path:[],message:s}]))}}var s}}exports.VldUndefined=VldUndefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../chunks/errors-core-C0mA6tfa.cjs"),s=require("../locales/runtime.cjs");function t(r){if(!0===r.isSimple)switch(r.validatorType){case e.VLD_VALIDATOR_TYPES.STRING:return"string";case e.VLD_VALIDATOR_TYPES.NUMBER:return"number";case e.VLD_VALIDATOR_TYPES.BOOLEAN:return"boolean";case e.VLD_VALIDATOR_TYPES.BIGINT:return"bigint";case e.VLD_VALIDATOR_TYPES.SYMBOL:return"symbol";case e.VLD_VALIDATOR_TYPES.NULL:return"null";case e.VLD_VALIDATOR_TYPES.UNDEFINED:case e.VLD_VALIDATOR_TYPES.VOID:return"undefined";case e.VLD_VALIDATOR_TYPES.LITERAL:return"literal";case e.VLD_VALIDATOR_TYPES.ANY:case e.VLD_VALIDATOR_TYPES.UNKNOWN:return"passthrough";default:return}}function n(r){switch(r.validatorType){case e.VLD_VALIDATOR_TYPES.STRING:return e=>"string"==typeof e;case e.VLD_VALIDATOR_TYPES.NUMBER:return e=>"number"==typeof e&&!isNaN(e);case e.VLD_VALIDATOR_TYPES.BOOLEAN:return e=>"boolean"==typeof e;case e.VLD_VALIDATOR_TYPES.BIGINT:return e=>"bigint"==typeof e;case e.VLD_VALIDATOR_TYPES.SYMBOL:return e=>"symbol"==typeof e;case e.VLD_VALIDATOR_TYPES.NAN:return e=>"number"==typeof e&&Number.isNaN(e);case e.VLD_VALIDATOR_TYPES.ARRAY:return Array.isArray;case e.VLD_VALIDATOR_TYPES.OBJECT:return e=>"object"==typeof e&&null!==e&&!Array.isArray(e);case e.VLD_VALIDATOR_TYPES.NULL:return e=>null===e;case e.VLD_VALIDATOR_TYPES.UNDEFINED:case e.VLD_VALIDATOR_TYPES.VOID:return e=>void 0===e;case e.VLD_VALIDATOR_TYPES.ENUM:return e=>"string"==typeof e||"number"==typeof e;case e.VLD_VALIDATOR_TYPES.LITERAL:{const e=r.literal;return r=>r===e}case e.VLD_VALIDATOR_TYPES.NEVER:return()=>!1;case e.VLD_VALIDATOR_TYPES.ANY:case e.VLD_VALIDATOR_TYPES.UNKNOWN:default:return()=>!0}}require("../registry.cjs"),require("../locales/en.cjs");class VldUnionV2 extends e.VldBase{constructor(r,s){super(e.VLD_VALIDATOR_TYPES.UNION),this.__def=function(e,r){const s=e.map(n),a=e.map(t),c=e.map((e,r)=>"literal"===a[r]?e.literal:void 0);return{type:"union",validators:e,typeCheckers:s,simpleModes:a,simpleValues:c,errorMessage:r}}(r,s)}static create(...e){return new VldUnionV2(e)}get options(){return this.__def.validators}parse(e){const r=[],{validators:t,typeCheckers:n,simpleModes:a,simpleValues:c}=this.__def;for(let s=0;s<t.length;s++){const u=t[s],V=n[s];if(V&&!V(e))continue;const i=a[s];if(void 0!==i)switch(i){case"string":case"number":case"boolean":case"bigint":case"symbol":case"passthrough":return e;case"null":return null;case"undefined":return;case"literal":return c[s]}try{return u.parse(e)}catch(e){r.push(e instanceof Error?e.message:String(e))}}throw new Error(this.__def.errorMessage||s.getMessages().unionNoMatch(r))}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:e instanceof r.VldError?e:new r.VldError([{code:"custom",path:[],message:e.message}])}}}}exports.VldUnionV2=VldUnionV2;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs");require("../registry.cjs"),require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs");require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs"),require("../locales/en.cjs");class VldUnion extends e.VldBase{constructor(r,s){super(e.VLD_VALIDATOR_TYPES.UNION),this.validators=r,this.errorMessage=s,this.typeCheckers=r.map(e=>this.createTypeChecker(e)),this.simpleModes=r.map(e=>this.createSimpleMode(e)),this.simpleValues=r.map((e,r)=>"literal"===this.simpleModes[r]?e.literal:void 0)}get options(){return this.validators}createSimpleMode(r){if(!0===r.isSimple)switch(r.validatorType){case e.VLD_VALIDATOR_TYPES.STRING:return"string";case e.VLD_VALIDATOR_TYPES.NUMBER:return"number";case e.VLD_VALIDATOR_TYPES.BOOLEAN:return"boolean";case e.VLD_VALIDATOR_TYPES.BIGINT:return"bigint";case e.VLD_VALIDATOR_TYPES.SYMBOL:return"symbol";case e.VLD_VALIDATOR_TYPES.NULL:return"null";case e.VLD_VALIDATOR_TYPES.UNDEFINED:case e.VLD_VALIDATOR_TYPES.VOID:return"undefined";case e.VLD_VALIDATOR_TYPES.LITERAL:return"literal";case e.VLD_VALIDATOR_TYPES.ANY:case e.VLD_VALIDATOR_TYPES.UNKNOWN:return"passthrough";default:return}}parseSimpleValue(e,r,s){switch(e){case"string":case"number":case"boolean":case"bigint":case"symbol":case"passthrough":return s;case"null":return null;case"undefined":default:return;case"literal":return this.simpleValues[r]}}createTypeChecker(r){switch(r.validatorType){case e.VLD_VALIDATOR_TYPES.STRING:return e=>"string"==typeof e;case e.VLD_VALIDATOR_TYPES.NUMBER:return e=>"number"==typeof e&&!isNaN(e);case e.VLD_VALIDATOR_TYPES.BOOLEAN:return e=>"boolean"==typeof e;case e.VLD_VALIDATOR_TYPES.BIGINT:return e=>"bigint"==typeof e;case e.VLD_VALIDATOR_TYPES.SYMBOL:return e=>"symbol"==typeof e;case e.VLD_VALIDATOR_TYPES.NAN:return e=>"number"==typeof e&&Number.isNaN(e);case e.VLD_VALIDATOR_TYPES.ARRAY:return Array.isArray;case e.VLD_VALIDATOR_TYPES.OBJECT:return e=>"object"==typeof e&&null!==e&&!Array.isArray(e);case e.VLD_VALIDATOR_TYPES.NULL:return e=>null===e;case e.VLD_VALIDATOR_TYPES.UNDEFINED:case e.VLD_VALIDATOR_TYPES.VOID:return e=>void 0===e;case e.VLD_VALIDATOR_TYPES.ENUM:return e=>"string"==typeof e||"number"==typeof e;case e.VLD_VALIDATOR_TYPES.LITERAL:{const e=r.literal;return r=>r===e}case e.VLD_VALIDATOR_TYPES.NEVER:return()=>!1;case e.VLD_VALIDATOR_TYPES.ANY:case e.VLD_VALIDATOR_TYPES.UNKNOWN:default:return()=>!0}}static create(...e){return new VldUnion(e)}parse(e){const s=[];for(let r=0;r<this.validators.length;r++){const t=this.validators[r],a=this.typeCheckers[r];if(a&&!a(e))continue;const n=this.simpleModes[r];if(void 0!==n)return this.parseSimpleValue(n,r,e);try{return t.parse(e)}catch(e){const r=e instanceof Error?e.message:String(e);s.push(r)}}throw new Error(this.errorMessage||r.getMessages().unionNoMatch(s))}safeParse(s){const t=[];for(let e=0;e<this.validators.length;e++){const r=this.validators[e],a=this.typeCheckers[e];if(a&&!a(s))continue;const n=this.simpleModes[e];if(void 0!==n)return{success:!0,data:this.parseSimpleValue(n,e,s)};try{return{success:!0,data:r.parse(s)}}catch(e){const r=e instanceof Error?e.message:String(e);t.push(r)}}return{success:!1,error:e.ensureVldError(this.errorMessage||r.getMessages().unionNoMatch(t))}}}exports.VldUnion=VldUnion;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs");require("../registry.cjs"),require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs");require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs");class VldUnknown extends e.VldBase{constructor(){super(e.VLD_VALIDATOR_TYPES.UNKNOWN)}static create(){return new VldUnknown}get isSimple(){return!0}parse(e){return e}safeParse(e){return{success:!0,data:e}}}exports.VldUnknown=VldUnknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../locales/runtime.cjs"),s=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");class VldVoid extends e.VldBase{constructor(){super(e.VLD_VALIDATOR_TYPES.VOID)}static create(){return new VldVoid}get isSimple(){return!0}parse(e){if(void 0!==e)throw new Error(r.getMessages().expectedUndefined)}safeParse(e){return void 0===e?{success:!0,data:void 0}:{success:!1,error:new s.VldError([{code:"invalid_type",path:[],message:r.getMessages().expectedUndefined}])}}}exports.VldVoid=VldVoid;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("./base.cjs"),r=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs");class VldOptionalV2 extends e.VldBase{constructor(r){super(e.VLD_VALIDATOR_TYPES.OPTIONAL),this.__def=Object.freeze({type:"optional",inner:r})}static create(e){return new VldOptionalV2(e)}parse(e){if(void 0!==e)return this.__def.inner.parse(e)}safeParse(e){return void 0===e?{success:!0,data:void 0}:this.__def.inner.safeParse(e)}unwrap(){return this.__def.inner}}class VldNullableV2 extends e.VldBase{constructor(r){super(e.VLD_VALIDATOR_TYPES.NULLABLE),this.__def=Object.freeze({type:"nullable",inner:r})}static create(e){return new VldNullableV2(e)}parse(e){return null===e?null:this.__def.inner.parse(e)}safeParse(e){return null===e?{success:!0,data:null}:this.__def.inner.safeParse(e)}unwrap(){return this.__def.inner}}class VldNullishV2 extends e.VldBase{constructor(r){super(e.VLD_VALIDATOR_TYPES.NULLISH),this.__def=Object.freeze({type:"nullish",inner:r})}static create(e){return new VldNullishV2(e)}parse(e){return null==e?e:this.__def.inner.parse(e)}safeParse(e){return null==e?{success:!0,data:e}:this.__def.inner.safeParse(e)}unwrap(){return this.__def.inner}}class VldRefineV2 extends e.VldBase{constructor(r,s,t="Refinement check failed",n){super(e.VLD_VALIDATOR_TYPES.REFINE),this.__def=Object.freeze({type:"refine",inner:r,predicate:s,message:t,path:n})}static create(e,r,s="Refinement check failed"){return new VldRefineV2(e,r,s)}parse(e){const s=this.__def.inner.parse(e),t=this.__def.predicate(s);if(t instanceof Promise)throw new Error("Use parseAsync for async refinements");if(!t)throw new r.VldError([{code:"custom",path:this.__def.path?[...this.__def.path]:[],message:this.__def.message}]);return s}safeParse(r){try{return{success:!0,data:this.parse(r)}}catch(r){return{success:!1,error:e.ensureVldError(r)}}}async parseAsync(e){const s=await this.__def.inner.parseAsync(e);if(!await this.__def.predicate(s))throw new r.VldError([{code:"custom",path:[],message:this.__def.message}]);return s}async safeParseAsync(r){try{return{success:!0,data:await this.parseAsync(r)}}catch(r){return{success:!1,error:e.ensureVldError(r)}}}unwrap(){return this.__def.inner}}class VldTransformV2 extends e.VldBase{constructor(r,s){super(e.VLD_VALIDATOR_TYPES.TRANSFORM),this.__def=Object.freeze({type:"transform",inner:r,transformer:s})}static create(e,r){return new VldTransformV2(e,r)}parse(e){const r=this.__def.inner.parse(e);try{const e=this.__def.transformer(r);if(e instanceof Promise)throw new Error("Use parseAsync for async transforms");return e}catch(e){throw new Error(`Transform failed: ${e.message}`)}}safeParse(r){try{return{success:!0,data:this.parse(r)}}catch(r){return{success:!1,error:e.ensureVldError(r)}}}async parseAsync(e){const r=await this.__def.inner.parseAsync(e);return this.__def.transformer(r)}async safeParseAsync(r){try{return{success:!0,data:await this.parseAsync(r)}}catch(r){return{success:!1,error:e.ensureVldError(r)}}}unwrap(){return this.__def.inner}}exports.VldNullableV2=VldNullableV2,exports.VldNullishV2=VldNullishV2,exports.VldOptionalV2=VldOptionalV2,exports.VldRefineV2=VldRefineV2,exports.VldTransformV2=VldTransformV2;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var r=require("./base.cjs");require("../registry.cjs"),require("../chunks/errors-core-
|
|
1
|
+
"use strict";var r=require("./base.cjs");require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs");class VldXor extends r.VldBase{constructor(s){super(r.VLD_VALIDATOR_TYPES.XOR),this._options=s}static create(r){return new VldXor(r)}parse(r){const s=this.safeParse(r);if(!s.success)throw s.error;return s.data}safeParse(s){let e=0,t=null;for(const r of this._options){const o=r.safeParse(s);if(o.success&&(e++,t=o,e>1))break}return 0===e?{success:!1,error:r.ensureVldError("No schema matched in XOR union")}:e>1?{success:!1,error:r.ensureVldError(`Input matches ${e} schemas in XOR union, but exactly one is required`)}:t}getOptions(){return this._options}}exports.VldXor=VldXor;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VLD AOT compiler - generates a flat, loop-free JavaScript validator that
|
|
3
|
+
* mirrors Zod 4.5's `z.compile()` strategy.
|
|
4
|
+
*
|
|
5
|
+
* Zod's secret: a compiled validator is a single function whose body is a
|
|
6
|
+
* sequence of `const vNinput["key"]; if (typeof vN !== "X") return INVALID;`
|
|
7
|
+
* statements, followed by either `return true` (validate-only path) or a
|
|
8
|
+
* result-building step (parse path). No function calls, no IIFEs, no shadow
|
|
9
|
+
* bindings. V8's TurboFan inliner produces machine code that is essentially
|
|
10
|
+
* a sequence of type checks and a `return`.
|
|
11
|
+
*
|
|
12
|
+
* The implementation below walks the schema, emits the same shape, and
|
|
13
|
+
* caches compiled validators on the schema's `_zod.bag.validator` so
|
|
14
|
+
* subsequent `v.validate()` / `v.compile()` calls return the same function.
|
|
15
|
+
*/
|
|
16
|
+
import { VldBase } from './validators/base.js';
|
|
17
|
+
import { VldObject } from './validators/object.js';
|
|
18
|
+
export declare class ZodCompileError extends Error {
|
|
19
|
+
constructor(message: string);
|
|
20
|
+
}
|
|
21
|
+
export declare class ZodCompileAsyncError extends ZodCompileError {
|
|
22
|
+
constructor(message?: string);
|
|
23
|
+
}
|
|
24
|
+
export { ZodCompileAsyncError as _ZodCompileAsyncError };
|
|
25
|
+
export declare class ZodCompileUnsupportedError extends ZodCompileError {
|
|
26
|
+
constructor(message?: string);
|
|
27
|
+
}
|
|
28
|
+
export { ZodCompileUnsupportedError as _ZodCompileUnsupportedError };
|
|
29
|
+
/**
|
|
30
|
+
* A compiled validator is `(input) => parsedValue | COMPILE_INVALID`. It is
|
|
31
|
+
* identified so the outer `validate()` and `parse()` wrappers can take the
|
|
32
|
+
* fast path and fall back to the standard parser on rejection.
|
|
33
|
+
*/
|
|
34
|
+
export type CompiledValidator = ((input: unknown) => unknown) & {
|
|
35
|
+
__vld_compiled: true;
|
|
36
|
+
};
|
|
37
|
+
declare const COMPILE_INVALID: unique symbol;
|
|
38
|
+
export declare const memoizer: <K extends object, V>(compute: (key: K) => V) => ((key: K) => V);
|
|
39
|
+
/**
|
|
40
|
+
* Build the compiled validator for a schema. Returns `null` if the schema
|
|
41
|
+
* cannot be fully lowered - callers fall back to the runtime parser.
|
|
42
|
+
*/
|
|
43
|
+
export declare function compileFn(schema: VldBase<any, any>, options?: {
|
|
44
|
+
validateOnly?: boolean;
|
|
45
|
+
}): CompiledValidator | null;
|
|
46
|
+
/**
|
|
47
|
+
* Slimmer validator used by `v.validate()`. Identical checks to `compileFn`
|
|
48
|
+
* but emits `return true` instead of allocating a result object/array, so
|
|
49
|
+
* V8 inlines the body more aggressively.
|
|
50
|
+
*/
|
|
51
|
+
export declare function compileFnValidate(schema: VldBase<any, any>): CompiledValidator | null;
|
|
52
|
+
/**
|
|
53
|
+
* Wrap a compiled validator into a VLD-compatible schema. The wrapper's
|
|
54
|
+
* `parse` and `safeParse` first call the compiled fast path; on failure
|
|
55
|
+
* they delegate to the underlying schema.
|
|
56
|
+
*
|
|
57
|
+
* `compiled` is the *parse* validator: it returns the parsed value on
|
|
58
|
+
* success and COMPILE_INVALID on failure. `validateOnly` (if supplied)
|
|
59
|
+
* is a slimmer validator that only returns `true` / COMPILE_INVALID; it is
|
|
60
|
+
* what `validate()` uses.
|
|
61
|
+
*
|
|
62
|
+
* For maximum parse performance we delegate the result-construction step
|
|
63
|
+
* to the schema's own parse method (VldObject.parse, VldArray.parse, etc.),
|
|
64
|
+
* which already does the per-shape work (strip unknown keys, clone, etc.)
|
|
65
|
+
* and is heavily optimised. The compiled parse path then becomes
|
|
66
|
+
* "compiledValidate(input) ? schema.parse(input) : throw", which keeps
|
|
67
|
+
* V8's inlining budget focused on a tiny validator function - exactly
|
|
68
|
+
* Zod 4.5's strategy.
|
|
69
|
+
*/
|
|
70
|
+
export declare function applyCompiled<T extends VldBase<any, any>>(schema: T, compiled: CompiledValidator, validateOnly?: CompiledValidator): T;
|
|
71
|
+
export declare function compile<T extends VldBase<any, any>>(schema: T, options?: {
|
|
72
|
+
JITless?: boolean;
|
|
73
|
+
}): T;
|
|
74
|
+
export declare function validate(schema: VldBase<any, any>, value: unknown): boolean;
|
|
75
|
+
export declare function validateAsync(schema: VldBase<any, any>, value: unknown): Promise<boolean>;
|
|
76
|
+
export declare function properties<T extends Record<string, VldBase<any, any>>>(shape: T): VldObject<Partial<{
|
|
77
|
+
[K in keyof T]: T[K] extends VldBase<any, infer O> ? O : never;
|
|
78
|
+
}>>;
|
|
79
|
+
export declare function getDiscriminatedOption(discriminator: string, options: ReadonlyArray<VldBase<any, any>>, value: unknown): VldBase<any, any> | undefined;
|
|
80
|
+
export declare function toZod(value: unknown): VldBase<any, any>;
|
|
81
|
+
export { COMPILE_INVALID };
|
package/dist/compile.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{VldBase as t}from"./validators/base.js";import{VldString as e}from"./validators/string.js";import{VldNumber as i}from"./validators/number.js";import{VldBoolean as r}from"./validators/boolean.js";import{VldBigInt as n}from"./validators/bigint.js";import{VldUndefined as s}from"./validators/undefined.js";import{VldNull as o}from"./validators/null.js";import{VldObject as a}from"./validators/object.js";import{VldArray as u}from"./validators/array.js";import{VldUnknown as l}from"./validators/unknown.js";class h extends Error{constructor(t){super(t),this.name="ZodCompileError"}}class c extends h{constructor(t="Cannot compile async schema"){super(t),this.name="ZodCompileAsyncError"}}class f extends h{constructor(t="Schema node is not supported by the AOT compiler"){super(t),this.name="ZodCompileUnsupportedError"}}const $=Symbol.for("@oxog/vld/compile-invalid");const d=t=>{const e=new WeakMap;return i=>{const r=e.get(i);if(void 0!==r)return r;const n=t(i);return e.set(i,n),n}};function v(t){return t&&t.constructor&&t.constructor.name||""}function p(t,e){return`__${e}${t.scratch++}`}function _(t,e,i){if(!i.failed){if("VldString"===v(t)){const r=t._checks,n=t._checkMetas,s=[];if(n)for(const t of n)switch(t.kind){case"min":s.push(`__v.length >= ${t.value}`);break;case"max":s.push(`__v.length <= ${t.value}`);break;case"length":s.push(`__v.length === ${t.value}`);break;case"regex":{const e=(t.pattern??t.value?.source??String(t.value)).replace(/\\/g,"\\\\").replace(/\//g,"\\/");s.push(`/${e}/.test(__v)`);break}case"startsWith":s.push(`__v.startsWith(${JSON.stringify(t.value)})`);break;case"endsWith":s.push(`__v.endsWith(${JSON.stringify(t.value)})`);break;case"includes":s.push(`__v.includes(${JSON.stringify(t.value)})`);break;case"email":case"url":case"uuid":case"ip":break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);return void(0===s.length?i.hoist.push(`if (typeof ${e} !== "string") ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`):i.hoist.push(`{ const __v = ${e}; if (typeof __v !== "string" || !(${s.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`))}if("VldNumber"===v(t)){const r=t._checks,n=t._checkMetas,s=[];if(n)for(const t of n)switch(t.kind){case"int":s.push("Number.isInteger(__v)");break;case"finite":s.push("Number.isFinite(__v)");break;case"min":s.push(!1!==t.inclusive?`__v >= ${t.value}`:`__v > ${t.value}`);break;case"max":s.push(!1!==t.inclusive?`__v <= ${t.value}`:`__v < ${t.value}`);break;case"gt":s.push(`__v > ${t.value}`);break;case"gte":s.push(`__v >= ${t.value}`);break;case"lt":s.push(`__v < ${t.value}`);break;case"lte":s.push(`__v <= ${t.value}`);break;case"multipleOf":s.push(`__v % ${t.value} === 0`);break;case"positive":s.push("__v > 0");break;case"negative":s.push("__v < 0");break;case"nonnegative":s.push("__v >= 0");break;case"nonpositive":s.push("__v <= 0");break;case"safe":s.push("Number.isSafeInteger(__v)");break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);const o=['typeof __v === "number"',"!Number.isNaN(__v)",...s];return void i.hoist.push(`{ const __v = ${e}; if (!(${o.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}if("VldBoolean"!==v(t)){if("VldBigInt"===v(t)){const r=t._checks,n=t._checkMetas,s=[];if(n)for(const t of n)switch(t.kind){case"min":s.push(`__v >= ${t.value}n`);break;case"max":s.push(`__v <= ${t.value}n`);break;case"positive":s.push("__v > 0n");break;case"negative":s.push("__v < 0n");break;case"nonnegative":s.push("__v >= 0n");break;case"nonpositive":s.push("__v <= 0n");break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);const o=['typeof __v === "bigint"',...s];return void i.hoist.push(`{ const __v = ${e}; if (!(${o.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}if("VldDate"!==v(t))if("VldNull"!==v(t))if("VldUndefined"!==v(t))if("VldAny"!==v(t)&&"VldUnknown"!==v(t)){if("VldLiteral"===v(t)){const r=t._values||[];if(0===r.length)return void i.hoist.push(`${i.throwOnFail?"throw":"return"} ${i.invalid};`);if(1===r.length){const t=r[0],n="number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t);return void i.hoist.push(`if (!Object.is(${n}, ${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}const n=p(i,"set");return i.hoist.push(`const ${n} = new Set([${r.map(t=>"number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t)).join(",")}]);`),void i.hoist.push(`if (!${n}.has(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}if("VldEnum"===v(t)){const r=t._values||[],n=p(i,"set");return i.hoist.push(`const ${n} = new Set([${r.map(t=>JSON.stringify(t)).join(",")}]);`),void i.hoist.push(`if (!${n}.has(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}if("VldOptional"===v(t)){const r=t.baseValidator;return i.hoist.push(`if (${e} === undefined) { ${i.outParam} = undefined; } else {`),_(r,e,i),void i.hoist.push("}")}if("VldArray"===v(t)){const r=t.config?.itemValidator??t.config?.element;if(!r)return void(i.failed=!0);const n=p(i,"arr"),s=p(i,"i");if("VldObject"===v(r)){if(i.hoist.push(`if (!Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){if(i.hoist.push(`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`),_(r,`${e}[${s}]`,i),i.failed)return;return i.hoist.push("}"),void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${n} = new Array(${e}.length);`);const t={invalid:i.invalid,outParam:"__slot",scratch:0,hoist:[],failed:!1,skipOutAssign:!0};return t.hoist.push(`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`," let __slot;"),_(r,`${e}[${s}]`,t),t.failed?void(i.failed=!0):(t.hoist.push(` ${n}[${s}] = __slot;`,"}"),i.hoist.push(...t.hoist),void i.hoist.push(`${i.outParam} = ${n};`))}const o=p(i,"it");if(i.hoist.push(`if (!Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly)return i.hoist.push(`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`,` const ${o} = ${e}[${s}];`),_(r,o,i),i.hoist.push("}"),void i.hoist.push(`${i.outParam} = true;`);if(i.hoist.push(`const ${n} = new Array(${e}.length);`,`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`),_(r,`${e}[${s}]`,i),i.failed)return;return void i.hoist.push(` ${n}[${s}] = ${e}[${s}];`,"}",`${i.outParam} = ${n};`)}if("VldTuple"===v(t)){const r=t.validators.filter(t=>Boolean(t)),n=t.restValidator,s=p(i,"tup"),o=n?`${e}.length < ${r.length}`:`${e}.length !== ${r.length}`;if(i.hoist.push(`if (!Array.isArray(${e}) || ${o}) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){for(let t=0;t<r.length;t++){const n=r[t];if(!n)return void(i.failed=!0);if(_(n,`${e}[${t}]`,i),i.failed)return}if(n){const t=p(i,"i");i.hoist.push(`for (let ${t} = ${r.length}; ${t} < ${e}.length; ${t}++) {`),_(n,`${e}[${t}]`,i),i.hoist.push("}")}return void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${s} = new Array(${e}.length);`);for(let t=0;t<r.length;t++){const n=r[t];if(!n)return void(i.failed=!0);const o=p(i,"it");i.hoist.push(`{ const ${o} = ${e}[${t}];`);const a=i.skipOutAssign??!1;i.skipOutAssign=!0,_(n,o,i),i.skipOutAssign=a,i.hoist.push(` ${s}[${t}] = ${o}; }`)}if(n){const t=p(i,"i"),o=p(i,"it");i.hoist.push(`for (let ${t} = ${r.length}; ${t} < ${e}.length; ${t}++) {`,` const ${o} = ${e}[${t}];`);const a=i.skipOutAssign??!1;i.skipOutAssign=!0,_(n,o,i),i.skipOutAssign=a,i.hoist.push(` ${s}[${t}] = ${o}; }`)}return void i.hoist.push(`${i.outParam} = ${s};`)}if("VldObject"===v(t)){const r=t._config?.shape;if(!r)return void(i.failed=!0);const n=p(i,"o");if(i.hoist.push(`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){for(const t of Object.keys(r)){const n=r[t];if(!n)return void(i.failed=!0);if(_(n,`${e}${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`}`,i),i.failed)return}return void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${n} = {};`);for(const t of Object.keys(r)){const s=r[t];if(!s)return void(i.failed=!0);const o=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`,a=p(i,"p");i.hoist.push(`{ const ${a} = ${e}${o};`);const u=i.skipOutAssign??!1;i.skipOutAssign=!0,_(s,a,i),i.skipOutAssign=u,i.hoist.push(` ${n}${o} = ${a}; }`)}return void i.hoist.push(`${i.outParam} = ${n};`)}if("VldRecord"===v(t)){const r=t.keyValidator,n=t.valueValidator,s=p(i,"rec"),o=p(i,"ks"),a=p(i,"i"),u=p(i,"k"),l=p(i,"v");return i.hoist.push(`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`,`const ${s} = {};`,`const ${o} = Object.keys(${e});`,`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`,` let ${u} = ${o}[${a}];`),_(r,u,i),i.hoist.push(` let ${l} = ${e}[${o}[${a}]];`),_(n,l,i),void i.hoist.push(` ${s}[${u}] = ${l};`,"}",""+(i.validateOnly?i.outParam+" = true; ":i.outParam+" = "+s+";"))}if("VldUnion"===v(t)){const e=t.validators.filter(t=>Boolean(t));if(0===e.length)return void(i.failed=!0);const r=p(i,"u");i.hoist.push(`let ${r} = ${i.invalid};`);for(let t=0;t<e.length;t++){const n=e[t],s=v(n);if("VldString"===s){i.hoist.push(`if (typeof value === "string") { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through to next option */ }`);continue}if("VldNumber"===s){i.hoist.push(`if (typeof value === "number" && value === value) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldBoolean"===s){i.hoist.push(`if (typeof value === "boolean") { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldNull"===s){i.hoist.push(`if (value === null) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldUndefined"===s){i.hoist.push(`if (value === undefined) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldLiteral"===s){const t=n._values||[];if(1===t.length){const e=t[0],n="number"==typeof e&&Number.isNaN(e)?"NaN":JSON.stringify(e);i.hoist.push(`if (Object.is(${n}, value)) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}}const o={invalid:i.invalid,outParam:r,scratch:0,hoist:[],failed:!1,skipOutAssign:!0};if(_(n,"value",o),o.failed)return void(i.failed=!0);i.hoist.push(`${r} = ((value) => {`,...o.hoist.map(t=>" "+t)," return value;","})(value);",`if (${r} !== ${i.invalid}) { /* matched */ }`)}return void i.hoist.push(`if (${r} === ${i.invalid}) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = ${r};`)}i.failed=!0}else i.hoist.push((i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e)+";");else i.hoist.push(`if (${e} !== undefined) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = undefined;`);else i.hoist.push(`if (${e} !== null) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = null;`);else i.hoist.push(`{ const __v = ${e}; if (!(__v instanceof Date) || __v.getTime() !== __v.getTime()) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}else i.hoist.push(`if (typeof ${e} !== "boolean") ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}}function g(t,e){if(!t||"function"!=typeof t.parse)return null;const i=!!e?.validateOnly,r={invalid:"__INV",outParam:i?"__ok":"__out",scratch:0,hoist:[],failed:!1,validateOnly:i};if(r.hoist.push(i?"let __ok;":"let __out;"),_(t,"value",r),r.failed)return"1"===process.env.VLD_COMPILE_DEBUG&&console.error("[compile] failed to lower schema; partial body:\n"+r.hoist.join("\n")),null;r.hoist.push(i?"return __ok;":"return __out;");const n=r.hoist.join("\n"),s=new Function("value",r.invalid,n),o=t=>s(t,$);return Object.defineProperty(o,"__vld_compiled",{value:!0,enumerable:!1}),o}function m(t){return g(t,{validateOnly:!0})}function b(t,e,i){const r=t.parse.bind(t),n=t.safeParse.bind(t),s=$,o=i??e;return t.parse=t=>o(t)===s?r(t):t,t.safeParse=t=>o(t)===s?n(t):{success:!0,data:t},Object.defineProperty(t,"_zod",{value:{bag:{validator:e,validatorValidate:i}},enumerable:!1,configurable:!0}),t}function y(t,e){const i=t?._zod?.bag?.validator;if(i)return t;const r=function(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}(t);if(e?.JITless)return Object.defineProperty(r,"_zod",{value:{bag:{}},enumerable:!1,configurable:!0}),r;const n=m(r);return n?b(r,n,n):r}function O(t,e){const i=t?._zod?.bag?.validatorValidate??t?._zod?.bag?.validator;if(i)try{return i(e)!==$}catch{return!1}const r=t.safeParse(e);return Boolean(r?.success)}async function k(t,e){const i=t?._zod?.bag?.validatorValidate??t?._zod?.bag?.validator;if(i)try{return i(e)!==$}catch{return!1}const r=await t.safeParseAsync(e);return Boolean(r?.success)}function w(t){const e={};for(const i of Object.keys(t))e[i]=t[i].optional();return a.create(e)}function A(t,e,i){if(null===i||"object"!=typeof i||Array.isArray(i))return;const r=i[t];for(const i of e){const e=i._config?.shape;if(!e)continue;const n=e[t];if(!n)continue;const s=n._values||[];for(const t of s)if(Object.is(t,r))return i}}function P(h){if(h instanceof t)return h;if(null===h)return o.create();switch(null===h?"null":Array.isArray(h)?"array":typeof h){case"string":return e.create();case"number":return i.create();case"boolean":return r.create();case"bigint":return n.create();case"undefined":return s.create();case"array":return u.create(l.create());case"object":return a.create(h);default:return l.create()}}export{$ as COMPILE_INVALID,c as ZodCompileAsyncError,h as ZodCompileError,f as ZodCompileUnsupportedError,c as _ZodCompileAsyncError,f as _ZodCompileUnsupportedError,b as applyCompiled,y as compile,g as compileFn,m as compileFnValidate,A as getDiscriminatedOption,d as memoizer,w as properties,P as toZod,O as validate,k as validateAsync};
|
package/dist/errors-core.d.ts
CHANGED
|
@@ -49,7 +49,10 @@ export interface VldErrorJSON {
|
|
|
49
49
|
}
|
|
50
50
|
export declare class VldError extends Error {
|
|
51
51
|
readonly issues: VldIssue[];
|
|
52
|
+
private _stack;
|
|
52
53
|
constructor(issues: VldIssue[], customMessage?: string);
|
|
54
|
+
/** Force-capture the stack trace on demand. */
|
|
55
|
+
captureStack(): void;
|
|
53
56
|
get firstError(): VldIssue | undefined;
|
|
54
57
|
get errors(): VldIssue[];
|
|
55
58
|
get isEmpty(): boolean;
|
package/dist/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{vldTheme as e}from"./pigment.js";export{V as VldError}from"./chunks/errors-core-
|
|
1
|
+
import{vldTheme as e}from"./pigment.js";export{V as VldError}from"./chunks/errors-core-BU14-Dk8.js";function r(e){const r={errors:[]};for(const t of e.issues){let e=r;const s=t.path;for(let r=0;r<s.length;r++){const o=s[r],n=r===s.length-1;if("string"==typeof o)e.properties||(e.properties={}),e.properties[o]||(e.properties[o]={errors:[]}),n?e.properties[o].errors.push(t.message):e=e.properties[o];else if("number"==typeof o){for(e.items||(e.items=[]);e.items.length<=o;)e.items.push(void 0);e.items[o]||(e.items[o]={errors:[]}),n?e.items[o].errors.push(t.message):e=e.items[o]}}0===s.length&&r.errors.push(t.message)}return r}function t(r,t={}){const{colored:s=!0,theme:o=e,includeCode:n=!1,includeDetails:i=!1}=t,c=[];for(const e of r.issues){let r=`${s?o.symbol("✖"):"✖"} ${s?o.error(e.message):e.message}`;if(n){r+=` ${s?o.muted(`[${e.code}]`):`[${e.code}]`}`}if(e.path.length>0){const t=e.path.map((e,r)=>{if("string"==typeof e){const t=0===r?e:`.${e}`;return s?o.path(t):t}{const r=`[${e}]`;return s?o.path(r):r}}).join("");r+=`\n ${s?o.muted("→ at "):"→ at "}${t}`}if(i){if(e.expected){r+=`\n ${s?o.muted("expected: ")+o.success(e.expected):`expected: ${e.expected}`}`}if(e.received){r+=`\n ${s?o.muted("received: ")+o.warning(e.received):`received: ${e.received}`}`}}c.push(r)}return c.join("\n")}function s(e,r={}){return t(e,{...r,colored:!0})}function o(e,r={}){return t(e,{...r,colored:!1})}function n(e){const r=[],t={};for(const s of e.issues)if(0===s.path.length)r.push(s.message);else{const e=s.path[0].toString();t[e]||(t[e]=[]),t[e].push(s.message)}return{formErrors:r,fieldErrors:t}}function i(e,r,t,s){return{code:e,path:[...r],message:t,...s}}function c(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":e instanceof Date?"date":typeof e}export{i as createIssue,n as flattenError,c as getValueType,t as prettifyError,s as prettifyErrorColored,o as prettifyErrorPlain,r as treeifyError};
|