validlyjs
Version:
A high-performance Laravel-inspired validation library for TypeScript/JavaScript
258 lines • 76.6 kB
JavaScript
function e(e){if("string"!=typeof e)return null
const t=e.toLowerCase().trim(),i=new Date
switch(t){case"today":return new Date(i.getFullYear(),i.getMonth(),i.getDate())
case"tomorrow":const e=new Date(i.getFullYear(),i.getMonth(),i.getDate())
return e.setDate(e.getDate()+1),e
case"yesterday":const s=new Date(i.getFullYear(),i.getMonth(),i.getDate())
return s.setDate(s.getDate()-1),s
case"now":return new Date
default:const r=t.match(/^([+-]?\d+)\s*(day|days|week|weeks|month|months|year|years)$/)
if(r){const e=parseInt(r[1]),t=r[2],s=new Date(i.getFullYear(),i.getMonth(),i.getDate())
switch(t){case"day":case"days":s.setDate(s.getDate()+e)
break
case"week":case"weeks":s.setDate(s.getDate()+7*e)
break
case"month":case"months":s.setMonth(s.getMonth()+e)
break
case"year":case"years":s.setFullYear(s.getFullYear()+e)}return s}}const s=e.length
if(s>=19&&"-"===e[4]&&"-"===e[7]&&"T"===e[10]&&"Z"===e[s-1]){let t=!0
for(let i=0;4>i;i++)if(48>e.charCodeAt(i)||e.charCodeAt(i)>57){t=!1
break}if(t&&$.test(e)){const t=new Date(e)
return isNaN(t.getTime())?null:t}}if(s>=4&&11>=s&&-1!==e.indexOf(":")&&R.test(e))return z(e)?e:null
let r=-1
for(let t=0;s>t;t++)if(" "===e[t]){r=t
break}const n=-1===r?e:e.substring(0,r),a=-1===r?null:e.substring(r+1)
let o=-1,l=-1,d=""
for(let e=0;n.length>e;e++)if("/"===n[e]||"-"===n[e])if(-1===o)o=e,d=n[e]
else if(n[e]===d){l=e
break}if(-1===o||-1===l)return null
let u=0,h=0,c=0,f=0
for(let e=0;o>e;e++){const t=n.charCodeAt(e)-48
if(0>t||t>9)return null
f=10*f+t}let m=0
for(let e=o+1;l>e;e++){const t=n.charCodeAt(e)-48
if(0>t||t>9)return null
m=10*m+t}let p=0
for(let e=l+1;n.length>e;e++){const t=n.charCodeAt(e)-48
if(0>t||t>9)return null
p=10*p+t}if(4===o&&f>1900?(c=f,h=m,u=p):(u=f,h=m,c=p),1>h||h>12||1>u||u>31||1>c)return null
const g=2===h&&(e=>!(3&e||!(e%100)&&e%400))(c)?29:P[h-1]
if(u>g)return null
let b=0,y=0,w=0
if(a){const e=z(a)
if(!e)return null;({hours:b,minutes:y,seconds:w}=e)}const v=new Date(Date.UTC(c,h-1,u,b,y,w))
return isNaN(v.getTime())?null:v}function t(e){return U.configure(e)}function i(e,t){return U.extend(e,t)}function s(e){return U.usePreset(e)}function r(e,t){return U.createPreset(e,t)}let n=null
var a
class o{static register(e,t){const i=this.normalizeRule(e,t)
this.rules.set(e,i),i.message&&(this.defaultMessages.has(e)||this.defaultMessages.set(e,i.message))}static registerCustomRule(e,t){const i=this.normalizeRule(e,t)
this.customRules.set(e,i),this.rules.set(e,i),i.message&&this.defaultMessages.set(e,i.message)}static isCustomRule(e){return this.customRules.has(e)}static get(e){return this.rules.get(e)}static has(e){return this.customRules.has(e)||this.rules.has(e)}static getAll(){return new Map(this.rules)}static getCustomRules(){return new Map(this.customRules)}static getDefaultMessage(e){return this.defaultMessages.get(e)}static remove(e){return this.defaultMessages.delete(e),this.customRules.delete(e),this.rules.delete(e)}static clear(){this.rules.clear(),this.customRules.clear(),this.defaultMessages.clear(),this.loadedModules.clear()}static clearCustomRules(){for(const[e]of this.customRules)this.rules.delete(e),this.defaultMessages.delete(e)
this.customRules.clear()}static normalizeRule(e,t){var i,s,r
return"name"in t&&t.name===e?t:{name:e,validate:t.validate,message:null!==(i=t.message)&&void 0!==i?i:"unknown",async:null!==(s=t.async)&&void 0!==s&&s,priority:null!==(r=t.priority)&&void 0!==r?r:0}}static loadBuiltInRules(){Promise.all([this.loadCoreRules(),this.loadStringRules(),this.loadNumberRules(),this.loadDateRules(),this.loadFileRules(),this.loadArrayRules(),this.loadBooleanRules(),this.loadNetworkRules(),this.loadObjectRules()]).catch(()=>{})}static async loadCoreRules(){if(!this.loadedModules.has("core"))try{const[e,t,i,s]=await Promise.all([import("./required-DHRsHzQ8.js"),import("./union-DehvwJdW.js"),import("./conditional-BxOwVK6F.js"),import("./type-checking-xnae9Kwq.js")]);[["required",e.requiredRule],["nullable",e.nullableRule],["optional",e.optionalRule],["present",e.presentRule],["confirmed",e.confirmedRule],["same",e.sameRule],["different",e.differentRule],["union",t.unionRule]].forEach(([e,t])=>this.register(e,t)),[["required_if",i.requiredIfRule],["required_unless",i.requiredUnlessRule],["required_with",i.requiredWithRule],["required_with_all",i.requiredWithAllRule],["required_without",i.requiredWithoutRule],["required_without_all",i.requiredWithoutAllRule],["prohibited",i.prohibitedRule],["prohibited_if",i.prohibitedIfRule],["prohibited_unless",i.prohibitedUnlessRule]].forEach(([e,t])=>this.register(e,t)),[["string",s.stringRule],["number",s.numberRule],["integer",s.integerRule],["boolean",s.booleanRule],["array",s.arrayRule],["object",s.objectRule],["date",s.dateRule],["file",s.fileRule],["numeric",s.numericRule],["scalar",s.scalarRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("core")}catch(e){}}static async loadStringRules(){if(!this.loadedModules.has("string"))try{const e=await import("./index-HBiHFgQh.js");[["string.min",e.stringMinRule],["string.max",e.stringMaxRule],["string.length",e.stringLengthRule],["string.size",e.stringSizeRule],["string.between",e.stringBetweenRule],["string.starts_with",e.startsWithRule],["string.ends_with",e.endsWithRule],["string.contains",e.containsRule],["string.in",e.inRule],["string.not_in",e.notInRule],["string.regex",e.regexRule],["string.alpha",e.alphaRule],["string.alpha_num",e.alphaNumericRule],["string.alpha_dash",e.alphaDashRule],["string.alpha_space",e.alphaSpaceRule],["string.email",e.emailRule],["string.url",e.urlRule],["string.uuid",e.uuidRule],["string.json",e.jsonRule],["string.ipv4",e.ipv4Rule],["string.ipv6",e.ipv6Rule],["string.ip",e.ipRule],["string.mac_address",e.macAddressRule],["string.hex_color",e.hexColorRule],["string.credit_card",e.creditCardRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("string")}catch(e){}}static async loadNumberRules(){if(!this.loadedModules.has("number"))try{const e=await import("./index-LbBiNZoC.js");[["number.min",e.numberMinRule],["number.max",e.numberMaxRule],["number.between",e.numberBetweenRule],["number.numeric",e.numberNumericRule],["number.size",e.numberSizeRule],["number.in",e.numberInRule],["number.not_in",e.numberNotInRule],["number.positive",e.numberPositiveRule],["number.negative",e.numberNegativeRule],["number.integer",e.numberIntegerRule],["number.decimal",e.numberDecimalRule],["number.multiple_of",e.numberMultipleOfRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("number")}catch(e){}}static async loadBooleanRules(){if(!this.loadedModules.has("boolean"))try{const e=await import("./index-BMWr1K15.js");[["boolean.true",e.booleanTrueRule],["boolean.accepted",e.booleanAcceptedRule],["boolean.false",e.booleanFalseRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("boolean")}catch(e){}}static async loadDateRules(){if(!this.loadedModules.has("date"))try{const e=await import("./index-CqZuVQ-H.js");[["date.format",e.dateFormatRule],["date.iso",e.dateIsoRule],["date.timezone",e.dateTimezoneRule],["date.weekday",e.dateWeekdayRule],["date.weekend",e.dateWeekendRule],["date.after",e.dateAfterRule],["date.before",e.dateBeforeRule],["date.after_or_equal",e.dateAfterOrEqualRule],["date.before_or_equal",e.dateBeforeOrEqualRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("date")}catch(e){}}static async loadArrayRules(){if(!this.loadedModules.has("array"))try{const[e,t,i]=await Promise.all([import("./size-CigDe_3H.js"),import("./content-fJbj4Uek.js"),import("./each-QcuJ4eqW.js")]);[["array.min",e.arrayMinRule],["array.max",e.arrayMaxRule],["array.length",e.arrayLengthRule],["array.between",e.arrayBetweenRule],["array.unique",t.arrayUniqueRule],["array.distinct",t.arrayDistinctRule],["array.contains",t.arrayContainsRule],["array.notContains",t.arrayNotContainsRule],["array.each",i.arrayEachRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("array")}catch(e){}}static async loadObjectRules(){if(!this.loadedModules.has("object"))try{const e=await import("./index-9RdYmWTn.js");[["object.shape",e.objectShapeRule],["object.has",e.objectHasRule],["object.keys",e.objectKeysRule],["object.requiredKeys",e.objectRequiredKeysRule],["object.keyCount",e.objectKeyCountRule],["object.strict",e.objectStrictRule],["object.notEmpty",e.objectNotEmptyRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("object")}catch(e){}}static async loadFileRules(){if(!this.loadedModules.has("file"))try{const[e,t,i,s]=await Promise.all([import("./size-fkYsZzly.js"),import("./type-CwsfpKnG.js"),import("./image-DwFM3n5X.js"),import("./dimensions-DDNzm6BB.js")]);[["file.min",e.fileMinRule],["file.max",e.fileMaxRule],["file.size",e.fileSizeRule],["file.between",e.fileRangeRule],["file.mimes",t.fileMimeTypesRule],["file.extensions",t.fileExtensionsRule],["file.image",i.fileImageRule],["file.width",s.fileWidthRule],["file.height",s.fileHeightRule],["file.min_width",s.fileMinWidthRule],["file.max_width",s.fileMaxWidthRule],["file.min_height",s.fileMinHeightRule],["file.max_height",s.fileMaxHeightRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("file")}catch(e){}}static async loadNetworkRules(){if(!this.loadedModules.has("network"))try{const[e,t]=await Promise.all([import("./port-CTqDvaLN.js"),import("./domain-KhfqFHps.js")]);[["network.port",e.portRule],["network.domain",t.domainRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("network")}catch(e){}}}a=o,o.rules=new Map,o.defaultMessages=new Map,o.customRules=new Map,o.loadedModules=new Set,n={getCustomRuleMessage:e=>a.defaultMessages.get(e)}
class l{constructor(){this.hits=0,this.misses=0,this.evictions=0}reset(){this.hits=0,this.misses=0,this.evictions=0}getHitRate(){const e=this.hits+this.misses
return e>0?this.hits/e:0}}class d{constructor(){this.cache=new Map,this.maxSize=1e3,this.accessOrder=[],this.stats=new l}set(e,t){if(this.cache.size>=this.maxSize){const e=this.accessOrder.shift()
e&&(this.cache.delete(e),this.stats.evictions++)}this.cache.set(e,t),this.accessOrder.push(e)}get(e){const t=this.cache.get(e)
if(t){this.stats.hits++
const t=this.accessOrder.indexOf(e)
this.accessOrder.splice(t,1),this.accessOrder.push(e)}else this.stats.misses++
return t}clear(){this.cache.clear(),this.accessOrder=[]}generateKey(e){if(!e)throw Error("Invalid rule definition")
if("string"==typeof e)return e
if(Array.isArray(e))return e.map(e=>this.generateKey(e)).join("|")
if("fluent"===e.t)return`${e.i}:${e.o.map(e=>e.name).join("|")}`
throw Error("Unsupported rule type")}}class u{constructor(){this.cache=new Map,this.maxSize=1e3,this.accessOrder=[]}set(e,t){if(this.cache.size>=this.maxSize){const e=this.accessOrder.shift()
e&&this.cache.delete(e)}this.cache.set(e,t),this.accessOrder.push(e)}get(e){const t=this.cache.get(e)
if(t){const t=this.accessOrder.indexOf(e)
this.accessOrder.splice(t,1),this.accessOrder.push(e)}return t}clear(){this.cache.clear(),this.accessOrder=[]}generateKey(e){if(!e)throw Error("Invalid rule definition")
if("string"==typeof e)return e
if(Array.isArray(e))return e.map(e=>this.generateKey(e)).join("|")
if("fluent"===e.t)return`${e.i}:${e.o.map(e=>e.name).join("|")}`
throw Error("Unsupported rule type")}}class h{constructor(){this.priority=1,this.unionParser=null}setUnionParser(e){this.unionParser=e}canParse(e){return"string"==typeof e&&e.length>0&&!e.startsWith("union:")}parse(e){if(!(null==e?void 0:e.trim()))throw Error("Invalid string schema")
const t=this.splitRules(e),i=[],s=[]
let r=null
for(const e of t)try{const t=this.parseRule(e)
if(this.isUnionRule(t,e))return this.handleUnionRule(e,t,s)
const n=this.processRule(t,r)
n.isModifier?s.push(n):(n.dataType&&h.DATA_TYPES.has(n.dataType)&&(r=n.dataType),i.push(n))}catch(t){throw Error(`Error parsing rule '${e}': ${t.message}`)}return[...s,...i]}isUnionRule(e,t){return"union"===e[0]||t.startsWith("union:")}handleUnionRule(e,t,i){var s
if(!this.unionParser)throw Error("Union parser not available")
const r=e.startsWith("union:")?e:"union:"+((null===(s=t[1])||void 0===s?void 0:s.join(","))||""),n=this.unionParser.parse(r)
return i.length>0?[...i,...n]:n}processRule(e,t){const[i,s]=e
return h.DATA_TYPES.has(i)?{name:i,parameters:s||[],modifiers:[],dataType:i}:h.MODIFIERS.has(i)?{name:i,parameters:s||[],modifiers:[],isModifier:!0}:o.isCustomRule(i)?{name:i,parameters:s||[],modifiers:[],dataType:"custom"}:(t||(t="string"),{name:`${t}.${i}`,parameters:s||[],modifiers:[],dataType:t})}splitRules(e){const t=[]
let i="",s={inParameters:!1,bracketDepth:0,inQuotes:!1,quoteChar:""}
for(let r=0;e.length>r;r++){const n=e[r]
this.handleQuotes(n,s)?i+=n:this.handleSpecialCharacters(n,s,i,t,r,e)?i="":i+=n}return i.trim()&&t.push(i.trim()),t}handleQuotes(e,t){return'"'!==e&&"'"!==e||t.inQuotes?e===t.quoteChar&&t.inQuotes?(t.inQuotes=!1,t.quoteChar="",!0):!!t.inQuotes:(t.inQuotes=!0,t.quoteChar=e,!0)}handleSpecialCharacters(e,t,i,s,r,n){if(":"===e&&!t.inParameters)return t.inParameters=!0,!1
if("("===e&&t.inParameters)return t.bracketDepth++,!1
if(")"===e&&t.inParameters)return t.bracketDepth--,!1
if("|"===e&&0===t.bracketDepth){if(t.inParameters){const e=this.findNextNonSpace(n,r+1);-1!==e&&/[a-zA-Z]/.test(n[e])&&(t.inParameters=!1)}if(!t.inParameters)return s.push(i.trim()),!0}return!1}findNextNonSpace(e,t){for(let i=t;e.length>i;i++)if(" "!==e[i])return i
return-1}parseRule(e){const t=this.findParameterSeparator(e)
if(-1===t)return[e.trim(),null]
const i=e.substring(0,t).trim(),s=e.substring(t+1)
return s?"union"===i?[i,[s]]:h.LITERAL_PARAMETER_RULES.has(i)?[i,[s.trim()]]:[i,this.parseParameters(s)]:[i,null]}parseParameters(e){const t=[]
let i="",s=!1,r=""
for(const n of e)this.handleParameterQuotes(n,{inQuotes:s,quoteChar:r},i,t)?({inQuotes:s,quoteChar:r}={inQuotes:s,quoteChar:r}):","!==n||s?i+=n:(t.push(this.convertParameter(i.trim())),i="")
return i.trim()&&t.push(this.convertParameter(i.trim())),t}handleParameterQuotes(e,t,i,s){return'"'!==e&&"'"!==e||t.inQuotes?!(e!==t.quoteChar||!t.inQuotes||(t.inQuotes=!1,t.quoteChar="",0)):(t.inQuotes=!0,t.quoteChar=e,!0)}convertParameter(e){const t=+e
return isNaN(t)||""===e?"true"===e||"false"!==e&&e:t}findParameterSeparator(e){for(const t of h.LITERAL_PARAMETER_RULES)if(e.startsWith(t+":"))return t.length
return e.indexOf(":")}}h.MODIFIERS=new Set(["required","optional","nullable","required_with","required_unless","required_with_all","required_without","required_if","prohibited_if","prohibited_unless","prohibited","same","present","confirmed","different"]),h.DATA_TYPES=new Set(["string","number","boolean","date","array","object","file"]),h.LITERAL_PARAMETER_RULES=new Set(["format","regex","pattern"])
class c{constructor(){this.cache=new d,this.stringParser=new h,o.loadBuiltInRules()}registerRule(e){o.register(e.name,e)}registerCustomRule(e){o.registerCustomRule(e.name,e)}getRule(e){return o.get(e)}getAllRules(){return Array.from(o.getAll().values())}hasRule(e){return o.has(e)}async executeRule(e,t,i,s){const r=`${e}:${s.field}:${JSON.stringify(i)}:${JSON.stringify(t)}`,n=this.cache.get(r)
if(n)return n
const a=this.getRule(e)
if(!a)return{passed:!1,message:"Unknown validation rule: "+e}
if(this.isNullableRule(a.name)&&this.isNullOrEmpty(t))return{passed:!0,skip:!0}
try{this.validateParameters(a,i)
const e=await a.validate(t,i,s.field,s.data),n={passed:e,skip:!1,...!e&&a.message&&{message:a.message}}
return this.cache.set(r,n),n}catch(t){const i={passed:!1,message:`Rule "${e}" execution failed: ${t.message}`,skip:!1}
return this.cache.set(r,i),i}}isNullableRule(e){return"nullable"===e||"optional"===e}isNullOrEmpty(e){return null==e||"string"==typeof e&&""===e.trim()}validateParameters(e,t){if(!e.name.startsWith("string."))return
const i=e.name.split(".")[1]
i&&["min","max","length","size","between"].includes(i)&&t.forEach((t,i)=>{if(isNaN(+t))throw Error(`Parameter ${i} for ${e.name} must be a number`)})}async validateValue(e,t,i){return Array.isArray(t)?this.validateArrayRules(e,t,i):"string"==typeof t?this.validateStringRule(e,t,i):"fluent"===t.t?this.validateFluentRule(e,t,i):"union"===t.t?this.validateUnionRule(e,t,i):{passed:!1,message:"Unsupported rule format: "+JSON.stringify(t),skip:!1}}async validateArrayRules(e,t,i){for(const s of t){const t=await this.validateValue(e,s,i)
if(!t.passed||t.skip)return t}return{passed:!0,skip:!1}}async validateStringRule(e,t,i){try{const s=this.stringParser.parse(t)
for(const t of s){const s=await this.executeRule(t.name,e,t.parameters||[],i)
if(!s.passed||s.skip)return s}return{passed:!0,skip:!1}}catch(e){return{passed:!1,message:`Failed to parse rule '${t}': ${e.message}`}}}async validateFluentRule(e,t,i){if(t.l&&t.l.length>0){const s=await this.processModifiers(e,t.l,i)
if(!s.passed||s.skip)return s}for(const s of t.o){const t=await this.executeRule(s.name,e,s.parameters||[],i)
if(!t.passed||t.skip)return t}return{passed:!0,skip:!1}}async processModifiers(e,t,i){for(const s of t){let t
switch(s.type){case"required":t=await this.executeRule("required",e,[],i)
break
case"nullable":t=await this.executeRule("nullable",e,[],i)
break
case"conditional":if(s.parameters){const[r,...n]=s.parameters
t=await this.executeRule(r,e,n,i)}else t={passed:!0,skip:!1}
break
default:t={passed:!0,skip:!1}}if(!t.passed||t.skip)return t}return{passed:!0,skip:!1}}async validateUnionRule(e,t,i){for(const s of t.rules)if((await this.validateValue(e,s,i)).passed)return{passed:!0,skip:!1}
return{passed:!1,message:"None of the union rules passed.",skip:!1}}}class f{constructor(){this.pathSegmentCache=new Map,this.arrayIndexRegex=/^([^\[]+)\[(\d+)\]$/,this.pathEndArrayRegex=/\[(\d+)\]$/,this.optionalRuleCache=new Map}resolveFields(e,t){const i=new Map
return this.resolveFieldsRecursive(e,t,"",i),i}resolveFieldsRecursive(e,t,i,s){const r=Object.entries(e)
for(let e=0;r.length>e;e++){const[n,a]=r[e],o=n.includes("*"),l=i?`${i}.${n}`:n
if(o)this.resolveWildcardPath(l,t,a,s)
else{const e=this.resolvePath(t,l)
if(void 0===e&&this.isOptionalField(a))continue
if(s.set(l,e),Array.isArray(e))for(let t=0;e.length>t;t++)s.set(`${l}[${t}]`,e[t])}}}isOptionalField(e){const t=this.optionalRuleCache.get(e)
if(void 0!==t)return t
let i=!1
if("string"==typeof e)i=-1!==e.indexOf("optional")||-1!==e.indexOf("nullable")
else if(Array.isArray(e))for(let t=0;e.length>t;t++){const s=e[t]
if("string"==typeof s&&("optional"===s||"nullable"===s||-1!==s.indexOf("optional")||-1!==s.indexOf("nullable"))){i=!0
break}}else if("object"==typeof e&&null!==e&&"t"in e&&"fluent"===e.t){const t=e.l
if(t)for(let e=0;t.length>e;e++){const s=t[e]
if("optional"===(null==s?void 0:s.type)||"nullable"===(null==s?void 0:s.type)){i=!0
break}}}else"object"==typeof e&&null!==e&&"t"in e&&"union"===e.t&&(i=!1)
return this.optionalRuleCache.set(e,i),i}resolveWildcardPath(e,t,i,s){const r=this.getPathSegments(e)
let n=-1
for(let e=0;r.length>e;e++)if("*"===r[e]){n=e
break}if(-1===n)return
const a=r.slice(0,n).join("."),o=r.slice(n+1).join("."),l=a?this.resolvePath(t,a):t
if(Array.isArray(l)){const e=l.length
for(let i=0;e>i;i++){const e=o?`${a}[${i}].${o}`:`${a}[${i}]`,r=this.resolvePath(t,e)
s.set(e,r)}}else if("object"==typeof l&&null!==l){const e=Object.keys(l)
for(let i=0;e.length>i;i++){const r=e[i],n=o?`${a}.${r}.${o}`:`${a}.${r}`,l=this.resolvePath(t,n)
s.set(n,l)}}}getPathSegments(e){const t=this.pathSegmentCache.get(e)
if(t)return t
const i=e.split(".")
return this.pathSegmentCache.set(e,i),i}resolvePath(e,t){try{const i=this.getPathSegments(t)
let s=e
for(let e=0;i.length>e;e++){if(void 0===s)return
const t=i[e],r=this.arrayIndexRegex.exec(t)
if(r){const e=r[1],t=r[2]
if(!e||!t)return
{const i=s[e]
if(!Array.isArray(i))return
s=i[parseInt(t,10)]}}else s=s[t]}return s}catch(e){return}}getParentPath(e){const t=e.lastIndexOf(".")
return t>-1?e.substring(0,t):void 0}getArrayIndex(e){const t=this.pathEndArrayRegex.exec(e)
return t&&t[1]?parseInt(t[1],10):void 0}clearCache(){this.pathSegmentCache.clear(),this.optionalRuleCache.clear()}getCacheStats(){return{pathSegments:this.pathSegmentCache.size,optionalRules:this.optionalRuleCache.size}}}class m{constructor(){this.templateCache=new Map,this.fieldNameCache=new Map,this.placeholderFormatters=new Map,this.namedPlaceholderMap=this.createNamedPlaceholderMap(),this.setupDefaultFormatters()}format(e,t){let i=this.templateCache.get(e)
if(i||(i=this.compileTemplate(e),this.templateCache.set(e,i)),0===i.placeholders.length)return e
const s=[]
let r=0
for(const n of i.placeholders){n.index>r&&s.push(e.substring(r,n.index))
const i=this.resolvePlaceholder(n,t)
s.push(i),r=e.indexOf("}",n.index)+1}return e.length>r&&s.push(e.substring(r)),s.join("")}compileTemplate(e){const t=[],i=/{([^}]+)}/g
let s
for(;null!==(s=i.exec(e));){const e=this.parsePlaceholder(s[1],s.index)
e&&t.push(e)}return{parts:[],placeholders:t}}parsePlaceholder(e,t){return"field"===e?{index:t,type:"field"}:"rule"===e?{index:t,type:"rule"}:"value"===e?{index:t,type:"value"}:/^\d+$/.test(e)?{index:t,type:"param",key:parseInt(e)}:this.placeholderFormatters.has(e)?{index:t,type:"custom",formatter:e}:{index:t,type:"named",key:e}}resolvePlaceholder(e,t){switch(e.type){case"field":return this.getFormattedFieldName(t.field)
case"rule":return t.rule
case"value":return this.formatValue(t.value)
case"param":const i=e.key
return t.parameters.length>i?this.formatValue(t.parameters[i]):""
case"named":const s=this.resolveNamedPlaceholder(e.key,t)
return"formats"===e.key?null!==s?s+"":"":null!==s?this.formatValue(s):""
case"custom":const r=this.placeholderFormatters.get(e.formatter)
return r?r(this.getCustomPlaceholderValue(e.formatter,t)):""
default:return""}}getFormattedFieldName(e){let t=this.fieldNameCache.get(e)
return void 0===t&&(t=this.formatFieldName(e),this.fieldNameCache.set(e,t)),t}formatFieldName(e){const t=e.split("."),i=[]
for(const e of t)if(/^\d+$/.test(e))i.push("item "+(parseInt(e)+1))
else if("*"===e)i.push("item")
else{let t=e
e.includes("_")&&(t=e.replace(/_/g," ")),/[a-z][A-Z]/.test(t)&&(t=t.replace(/([a-z])([A-Z])/g,"$1 $2")),i.push(t.toLowerCase())}return i.join(" ")}resolveNamedPlaceholder(e,t){if("formats"===e){const e=global.lastUnionFormats||t.parameters
return Array.isArray(e)&&e.length>0?"union.detailed"===t.rule?e[0]:e.join(" OR "):"{formats}"}const i=this.namedPlaceholderMap.get(t.rule)
if(!i)return null
const s=i.indexOf(e)
return s>=0&&t.parameters.length>s?t.parameters[s]:null}createNamedPlaceholderMap(){return new Map([["string.min",["min"]],["string.max",["max"]],["string.length",["length"]],["string.starts_with",["prefix"]],["string.ends_with",["suffix"]],["string.contains",["substring"]],["string.in",["options"]],["string.not_in",["options"]],["number.min",["min"]],["number.max",["max"]],["number.between",["min","max"]],["number.decimal",["places"]],["number.multiple_of",["divisor"]],["number.in",["options"]],["number.not_in",["options"]],["between",["min","max"]],["min",["min"]],["max",["max"]],["date.after",["date"]],["date.before",["date"]],["date.after_or_equal",["date"]],["date.before_or_equal",["date"]],["date.format",["format"]],["date.timezone",["timezone"]],["array.min",["min"]],["array.max",["max"]],["array.length",["length"]],["array.contains",["value"]],["file.max",["max"]],["file.min",["min"]],["file.between",["min","max"]],["file.size",["size"]],["file.mimes",["types"]],["file.extensions",["extensions"]],["file.width",["width"]],["file.height",["height"]],["file.minWidth",["minWidth"]],["file.minHeight",["minHeight"]],["file.maxWidth",["maxWidth"]],["file.maxHeight",["maxHeight"]],["required_if",["field","value"]],["required_with",["fields"]],["required_with_all",["fields"]],["required_without",["fields"]],["required_without_all",["fields"]],["required_unless",["field","value"]],["union",["formats"]],["union.detailed",["formats"]],["union.failed",["formats"]]])}formatValue(e){if(null===e)return"null"
if(void 0===e)return"undefined"
if(e instanceof Date)return e.toISOString().split("T")[0]
if(Array.isArray(e))return e.map(e=>"string"==typeof e?e:e+"").join(", ")
const t=typeof e
return"string"===t?e:"object"===t?JSON.stringify(e):e+""}getCustomPlaceholderValue(e,t){switch(e){case"field_value":return t.data[t.field]
case"data_keys":return Object.keys(t.data)
case"parameter_count":return t.parameters.length
case"formats":const e=global.lastUnionFormats||t.parameters
return Array.isArray(e)?e.join(" OR "):e||""
default:return t.value}}addPlaceholder(e,t){this.placeholderFormatters.set(e,t),this.templateCache.clear()}clearCaches(){this.templateCache.clear(),this.fieldNameCache.clear()}setupDefaultFormatters(){this.addPlaceholder("file_size",e=>1024>e?e+"B":1048576>e?(e/1024).toFixed(1)+"KB":1073741824>e?(e/1048576).toFixed(1)+"MB":(e/1073741824).toFixed(1)+"GB"),this.addPlaceholder("date",e=>e instanceof Date?e.toLocaleDateString():e+""),this.addPlaceholder("array",e=>Array.isArray(e)?e.map(e=>this.formatValue(e)).join(", "):e+""),this.addPlaceholder("number",e=>"number"==typeof e?e.toLocaleString():e+""),this.addPlaceholder("capitalize",e=>(e+"")[0].toUpperCase()+(e+"").slice(1)),this.templateCache.clear()}}const p={required:"The {field} field is required",nullable:"The {field} field may be null",optional:"The {field} field is optional",string:"The {field} field must be a string",number:"The {field} field must be a number",boolean:"The {field} field must be a boolean",array:"The {field} field must be an array",object:"The {field} field must be an object",date:"The {field} field must be a valid date","string.min":"The {field} field must be at least {min} characters","string.max":"The {field} field must not exceed {max} characters","string.length":"The {field} field must be exactly {length} characters","string.email":"The {field} field must be a valid email address","string.url":"The {field} field must be a valid URL","string.regex":"The {field} field format is invalid","string.alpha":"The {field} field must only contain letters","string.alpha_num":"The {field} field must only contain letters and numbers","string.alpha_num_dash":"The {field} field must only contain letters, numbers, dashes, and underscores","string.uuid":"The {field} field must be a valid UUID","string.json":"The {field} field must be valid JSON","string.starts_with":"The {field} field must start with {prefix}","string.ends_with":"The {field} field must end with {suffix}","string.contains":"The {field} field must contain {substring}","string.in":"The {field} field must be one of: {options}","string.not_in":"The {field} field must not be one of: {options}","string.hex":"The {field} field must be a valid hexadecimal color","string.credit_card":"The {field} field must be a valid credit card number","string.alpha_space":"The {field} field must only contain letters and spaces","number.min":"The {field} field must be at least {min}","number.size":"The {field} field must equal {0}","number.max":"The {field} field must not exceed {max}","number.numeric":"The {field} field must be numeric","number.between":"The {field} field must be between {min} and {max}","number.positive":"The {field} field must be positive","number.negative":"The {field} field must be negative","number.integer":"The {field} field must be an integer","number.decimal":"The {field} field must have at most {places} decimal places","number.multiple_of":"The {field} field must be a multiple of {divisor}","number.in":"The {field} field must be one of: {options}","number.not_in":"The {field} field must not be one of: {options}","boolean.true":"The {field} field must be true","boolean.accepted":"The {field} field must be accepted","boolean.false":"The {field} field must be false","date.after":"The {field} field must be after {date}","date.before":"The {field} field must be before {date}","date.after_or_equal":"The {field} field must be after or equal to {date}","date.before_or_equal":"The {field} field must be before or equal to {date}","date.format":"The {field} field must match format {format}","date.timezone":"The {field} field must be in timezone {timezone}","date.weekday":"The {field} field must be a weekday","date.weekend":"The {field} field must be a weekend","date.iso":"The {field} field must be a valid ISO date","array.min":"The {field} field must contain at least {min} items","array.max":"The {field} field must not contain more than {max} items","array.length":"The {field} field must contain exactly {length} items","array.unique":"The {field} field must contain unique items","array.contains":"The {field} field must contain {value}","object.shape":"The {field} field contains invalid shape","object.strict":"The {field} field contains invalid properties","object.keys":"The {field} field contains invalid keys","file.max":"The {field} field must not exceed {max}KB","file.min":"The {field} field must be at least {min}KB","file.width":"The {field} field must be {width} pixels wide","file.height":"The {field} field must be {height} pixels high","file.minWidth":"The {field} field must be at least {minWidth} pixels wide","file.minHeight":"The {field} field must be at least {minHeight} pixels high","file.maxWidth":"The {field} field must not exceed {maxWidth} pixels wide","file.maxHeight":"The {field} field must not exceed {maxHeight} pixels high","file.extensions":"The {field} field must have extension: {extensions}","file.image":"The {field} field must be an image","file.dimensions":"The {field} field dimensions are invalid","file.between":"The {field} field must be between {min}KB and {max}KB","file.size":"The {field} field must be exactly {size}KB",required_if:"The {field} field is required when {field} is {value}",required_with:"The {field} field is required when {fields} is present",required_with_all:"The {field} field is required when all of {fields} are present",required_without:"The {field} field is required when {fields} is not present",required_without_all:"The {field} field is required when none of {fields} are present",required_unless:"The {field} field is required unless {field} is {value}",union:"The {field} field must match one of these formats: {formats}","union.failed":"The {field} field must match at least one of the specified formats","union.detailed":"The {field} field must match one of these formats: {formats}",invalid:"The {field} field is invalid",type_error:"The {field} field must be of type {type}",custom_rule:"The {field} field failed custom validation"},g={required:"El campo {field} es obligatorio",nullable:"El campo {field} puede ser nulo",optional:"El campo {field} es opcional",string:"El campo {field} debe ser una cadena de texto",number:"El campo {field} debe ser un número",boolean:"El campo {field} debe ser un booleano",array:"El campo {field} debe ser un arreglo",object:"El campo {field} debe ser un objeto",date:"El campo {field} debe ser una fecha válida","string.min":"El campo {field} debe tener al menos {min} caracteres","string.max":"El campo {field} no debe exceder de {max} caracteres","string.length":"El campo {field} debe tener exactamente {length} caracteres","string.email":"El campo {field} debe ser un correo electrónico válido","string.url":"El campo {field} debe ser una URL válida","string.regex":"El formato del campo {field} no es válido","string.alpha":"El campo {field} solo debe contener letras","string.alpha_num":"El campo {field} solo debe contener letras y números","string.alpha_num_dash":"El campo {field} solo debe contener letras, números, guiones y guiones bajos","string.uuid":"El campo {field} debe ser un UUID válido","string.json":"El campo {field} debe ser un JSON válido","string.starts_with":"El campo {field} debe comenzar con {prefix}","string.ends_with":"El campo {field} debe terminar con {suffix}","string.contains":"El campo {field} debe contener {substring}","string.in":"El campo {field} debe ser uno de: {options}","string.not_in":"El campo {field} no debe ser uno de: {options}","string.hex":"El campo {field} debe ser un color hexadecimal válido","string.credit_card":"El campo {field} debe ser un número de tarjeta de crédito válido","string.alpha_space":"El campo {field} solo debe contener letras y espacios","number.min":"El campo {field} debe ser al menos {min}","number.size":"El campo {field} debe ser igual a {0}","number.max":"El campo {field} no debe exceder de {max}","number.numeric":"El campo {field} debe ser numérico","number.between":"El campo {field} debe estar entre {min} y {max}","number.positive":"El campo {field} debe ser positivo","number.negative":"El campo {field} debe ser negativo","number.integer":"El campo {field} debe ser un número entero","number.decimal":"El campo {field} debe tener como máximo {places} decimales","number.multiple_of":"El campo {field} debe ser múltiplo de {divisor}","number.in":"El campo {field} debe ser uno de: {options}","number.not_in":"El campo {field} no debe ser uno de: {options}","boolean.true":"El campo {field} debe ser verdadero","boolean.accepted":"El campo {field} debe ser aceptado","boolean.false":"El campo {field} debe ser falso","date.after":"El campo {field} debe ser posterior a {date}","date.before":"El campo {field} debe ser anterior a {date}","date.after_or_equal":"El campo {field} debe ser posterior o igual a {date}","date.before_or_equal":"El campo {field} debe ser anterior o igual a {date}","date.format":"El campo {field} debe coincidir con el formato {format}","date.timezone":"El campo {field} debe estar en la zona horaria {timezone}","date.weekday":"El campo {field} debe ser un día laborable","date.weekend":"El campo {field} debe ser un fin de semana","date.iso":"El campo {field} debe ser una fecha ISO válida","array.min":"El campo {field} debe contener al menos {min} elementos","array.max":"El campo {field} no debe contener más de {max} elementos","array.length":"El campo {field} debe contener exactamente {length} elementos","array.unique":"El campo {field} debe contener elementos únicos","array.contains":"El campo {field} debe contener {value}","object.shape":"El campo {field} tiene una estructura inválida","object.strict":"El campo {field} contiene propiedades no válidas","object.keys":"El campo {field} contiene claves inválidas","file.max":"El campo {field} no debe exceder de {max}KB","file.min":"El campo {field} debe tener al menos {min}KB","file.width":"El campo {field} debe tener {width} píxeles de ancho","file.height":"El campo {field} debe tener {height} píxeles de alto","file.minWidth":"El campo {field} debe tener al menos {minWidth} píxeles de ancho","file.minHeight":"El campo {field} debe tener al menos {minHeight} píxeles de alto","file.maxWidth":"El campo {field} no debe exceder de {maxWidth} píxeles de ancho","file.maxHeight":"El campo {field} no debe exceder de {maxHeight} píxeles de alto","file.extensions":"El campo {field} debe tener la extensión: {extensions}","file.image":"El campo {field} debe ser una imagen","file.dimensions":"Las dimensiones del campo {field} son inválidas","file.between":"El campo {field} debe estar entre {min}KB y {max}KB","file.size":"El campo {field} debe tener exactamente {size}KB",required_if:"El campo {field} es obligatorio cuando {field} es {value}",required_with:"El campo {field} es obligatorio cuando {fields} está presente",required_with_all:"El campo {field} es obligatorio cuando todos los campos {fields} están presentes",required_without:"El campo {field} es obligatorio cuando {fields} no está presente",required_without_all:"El campo {field} es obligatorio cuando ninguno de los campos {fields} está presente",required_unless:"El campo {field} es obligatorio a menos que {field} sea {value}",union:"El campo {field} debe coincidir con uno de los siguientes formatos: {formats}","union.failed":"El campo {field} debe coincidir con al menos uno de los formatos especificados","union.detailed":"El campo {field} debe coincidir con uno de los siguientes formatos: {formats}",invalid:"El campo {field} no es válido",type_error:"El campo {field} debe ser del tipo {type}",custom_rule:"El campo {field} no pasó la validación personalizada"},b={required:"Le champ {field} est requis",nullable:"Le champ {field} peut être nul",optional:"Le champ {field} est facultatif",string:"Le champ {field} doit être une chaîne de caractères",number:"Le champ {field} doit être un nombre",boolean:"Le champ {field} doit être un booléen",array:"Le champ {field} doit être un tableau",object:"Le champ {field} doit être un objet",date:"Le champ {field} doit être une date valide","string.min":"Le champ {field} doit comporter au moins {min} caractères","string.max":"Le champ {field} ne doit pas dépasser {max} caractères","string.length":"Le champ {field} doit comporter exactement {length} caractères","string.email":"Le champ {field} doit être une adresse e-mail valide","string.url":"Le champ {field} doit être une URL valide","string.regex":"Le format du champ {field} est invalide","string.alpha":"Le champ {field} ne doit contenir que des lettres","string.alpha_num":"Le champ {field} ne doit contenir que des lettres et des chiffres","string.alpha_num_dash":"Le champ {field} ne doit contenir que des lettres, des chiffres, des tirets et des underscores","string.uuid":"Le champ {field} doit être un UUID valide","string.json":"Le champ {field} doit être un JSON valide","string.starts_with":"Le champ {field} doit commencer par {prefix}","string.ends_with":"Le champ {field} doit se terminer par {suffix}","string.contains":"Le champ {field} doit contenir {substring}","string.in":"Le champ {field} doit être l’un des suivants : {options}","string.not_in":"Le champ {field} ne doit pas être l’un des suivants : {options}","string.hex":"Le champ {field} doit être une couleur hexadécimale valide","string.credit_card":"Le champ {field} doit être un numéro de carte bancaire valide","string.alpha_space":"Le champ {field} ne doit contenir que des lettres et des espaces","number.min":"Le champ {field} doit être au moins {min}","number.size":"Le champ {field} doit être égal à {0}","number.max":"Le champ {field} ne doit pas dépasser {max}","number.numeric":"Le champ {field} doit être numérique","number.between":"Le champ {field} doit être entre {min} et {max}","number.positive":"Le champ {field} doit être positif","number.negative":"Le champ {field} doit être négatif","number.integer":"Le champ {field} doit être un entier","number.decimal":"Le champ {field} doit avoir au plus {places} décimales","number.multiple_of":"Le champ {field} doit être un multiple de {divisor}","number.in":"Le champ {field} doit être l’un des suivants : {options}","number.not_in":"Le champ {field} ne doit pas être l’un des suivants : {options}","boolean.true":"Le champ {field} doit être vrai","boolean.accepted":"Le champ {field} doit être accepté","boolean.false":"Le champ {field} doit être faux","date.after":"Le champ {field} doit être postérieur à {date}","date.before":"Le champ {field} doit être antérieur à {date}","date.after_or_equal":"Le champ {field} doit être postérieur ou égal à {date}","date.before_or_equal":"Le champ {field} doit être antérieur ou égal à {date}","date.format":"Le champ {field} doit correspondre au format {format}","date.timezone":"Le champ {field} doit être dans le fuseau horaire {timezone}","date.weekday":"Le champ {field} doit être un jour ouvrable","date.weekend":"Le champ {field} doit être un jour de week-end","date.iso":"Le champ {field} doit être une date ISO valide","array.min":"Le champ {field} doit contenir au moins {min} éléments","array.max":"Le champ {field} ne doit pas contenir plus de {max} éléments","array.length":"Le champ {field} doit contenir exactement {length} éléments","array.unique":"Le champ {field} doit contenir des éléments uniques","array.contains":"Le champ {field} doit contenir {value}","object.shape":"Le champ {field} a une structure invalide","object.strict":"Le champ {field} contient des propriétés non valides","object.keys":"Le champ {field} contient des clés non valides","file.max":"Le champ {field} ne doit pas dépasser {max}KB","file.min":"Le champ {field} doit être d’au moins {min}KB","file.width":"Le champ {field} doit avoir une largeur de {width} pixels","file.height":"Le champ {field} doit avoir une hauteur de {height} pixels","file.minWidth":"Le champ {field} doit avoir une largeur minimale de {minWidth} pixels","file.minHeight":"Le champ {field} doit avoir une hauteur minimale de {minHeight} pixels","file.maxWidth":"Le champ {field} ne doit pas dépasser {maxWidth} pixels de large","file.maxHeight":"Le champ {field} ne doit pas dépasser {maxHeight} pixels de haut","file.extensions":"Le champ {field} doit avoir l’extension : {extensions}","file.image":"Le champ {field} doit être une image","file.dimensions":"Les dimensions du champ {field} sont invalides","file.between":"Le champ {field} doit être entre {min}KB et {max}KB","file.size":"Le champ {field} doit être exactement de {size}KB",required_if:"Le champ {field} est requis lorsque {field} est {value}",required_with:"Le champ {field} est requis lorsque {fields} est présent",required_with_all:"Le champ {field} est requis lorsque tous les champs {fields} sont présents",required_without:"Le champ {field} est requis lorsque {fields} est absent",required_without_all:"Le champ {field} est requis lorsque aucun des champs {fields} n’est présent",required_unless:"Le champ {field} est requis sauf si {field} est {value}",union:"Le champ {field} doit correspondre à l’un des formats suivants : {formats}","union.failed":"Le champ {field} doit correspondre à au moins un des formats spécifiés","union.detailed":"Le champ {field} doit correspondre à l’un des formats suivants : {formats}",invalid:"Le champ {field} est invalide",type_error:"Le champ {field} doit être de type {type}",custom_rule:"Le champ {field} a échoué à la validation personnalisée"}
class y{constructor(e={}){this.messageCache=new Map,this.wildcardPatternCache=new Map,this.fieldSegmentCache=new Map,this.currentLanguagePack=null,this.currentLanguage="",this.bridge=null,this.enLanguagePack=null,this.config={language:"en",messages:{},fieldMessages:{},customLanguages:{},...e},this.formatter=new m,this.languagePacks=new Map,this.loadDefaultLanguages(),this.updateCurrentLanguagePack(),this.bridge=n,this.enLanguagePack=this.languagePacks.get("en")||null}resolve(e){const t=`${e.field}:${e.rule}:${this.currentLanguage}`
let i=this.messageCache.get(t)
return void 0===i&&(i=this.findMessage(e),this.messageCache.set(t,i)),this.formatter.format(i,e)}findMessage(e){const{field:t,rule:i}=e,{fieldMessages:s,messages:r}=this.config,n=s[`${t}.${i}`]
if(n)return n
const a=this.findWildcardMessageOptimized(t,i,s)
if(a)return a
const o=r[i]
if(o)return o
if(this.currentLanguagePack){const e=this.currentLanguagePack[i]
if(e)return e}if(this.bridge){const e=this.bridge.getCustomRuleMessage(i)
if(e)return e}if("en"!==this.currentLanguage&&this.enLanguagePack){const e=this.enLanguagePack[i]
if(e)return e}return`The ${t} field is invalid`}findWildcardMessageOptimized(e,t,i){var s
let r=this.wildcardPatternCache.get(e)
r||(r=this.generateWildcardPatterns(e),this.wildcardPatternCache.set(e,r))
for(let e=0;r.length>e;e++){const n=i[`${null===(s=null==r?void 0:r[e])||void 0===s?void 0:s.pattern}.${t}`]
if(n)return n}return null}generateWildcardPatterns(e){const t=this.getFieldSegments(e),i=[]
i.length=t.length
for(let e=t.length-1;e>=0;e--){const s=t.slice()
s[e]="*",i[t.length-1-e]={pattern:s.join("."),segments:s}}return i}getFieldSegments(e){let t=this.fieldSegmentCache.get(e)
return t||(t=e.split("."),this.fieldSegmentCache.set(e,t)),t}updateCurrentLanguagePack(){this.currentLanguage!==this.config.language&&(this.currentLanguage=this.config.language,this.currentLanguagePack=this.getLanguagePack(this.config.language))}getLanguagePack(e){let t=this.languagePacks.get(e)
if(!t){const i=this.config.customLanguages[e]
i?(this.languagePacks.set(e,i),t=i):(t={},this.languagePacks.set(e,t))}return t}loadDefaultLanguages(){this.languagePacks.set("en",p),this.languagePacks.set("es",g),this.languagePacks.set("fr",b)}addLanguage(e,t){this.languagePacks.set(e,t),this.config.customLanguages[e]=t,"en"===e&&(this.enLanguagePack=t),this.clearLanguageRelatedCaches()}updateConfig(e){const t=this.config.language
this.config={...this.config,...e},(t!==this.config.language||e.fieldMessages||e.messages)&&this.clearCaches(),this.updateCurrentLanguagePack()}setLanguage(e){this.config.language!==e&&(this.config.language=e,this.updateCurrentLanguagePack(),this.messageCache.clear())}getLanguage(){return this.config.language}getAvailableLanguages(){return Array.from(this.languagePacks.keys())}clearCaches(){this.messageCache.clear(),this.wildcardPatternCache.clear(),this.fieldSegmentCache.clear(),this.updateCurrentLanguagePack()}clearLanguageRelatedCaches(){this.messageCache.clear(),this.updateCurrentLanguagePack()}getCacheStats(){return{messageCache:this.messageCache.size,wildcardPatternCache:this.wildcardPatternCache.size,fieldSegmentCache:this.fieldSegmentCache.size,languagePacks:this.languagePacks.size}}}class w{static async validateBatch(e,t,i){const s=[]
for(let r=0;e.length>r;r+=50){const n=e.slice(r,r+50),a=t.slice(r,r+50),o=i.slice(r,r+50),l=await Promise.all(n.map((e,t)=>{const i=a[t]
if(!i)return{passed:!1,message:"No validation rule provided"}
const s=o[t]
return s?this.validateSingle(e,i,s):{passed:!1,message:"No validation context provided"}}))
s.push(...l)}return s}static async validateSingle(e,t,i){try{const s=await this.ruleEngine.validateValue(e,t,i)
if(!s.passed&&!s.message){let r="unknown"
"string"==typeof t?r=t.split(":")[0]||"unknown":Array.isArray(t)?r="array_rule":"t"in t&&(r="fluent"===t.t?t.i:"union"),s.message=this.messageResolver.resolve({...i,rule:r,value:e,parameters:i.parameters||[]})}return s}catch(t){return{passed:!1,message:this.messageResolver.resolve({...i,rule:"validation_failed",value:e,parameters:i.parameters||[]})||"Validation failed: "+t.message}}}static async validateWithWorkers(e,t,i,s=4){const r=Math.ceil(e.length/s),n=[]
for(let s=0;e.length>s;s+=r)n.push({values:e.slice(s,s+r),rules:t.slice(s,s+r),contexts:i.slice(s,s+r)})
return(await Promise.all(n.map(e=>this.validateBatch(e.values,e.rules,e.contexts)))).flat()}static async validateWithTimeout(e,t,i,s=5e3){const r=new AbortController,n=setTimeout(()=>r.abort(),s)
try{const s=this.validateSingle(e,t,i),a=await Promise.race([s,new Promise((e,t)=>{r.signal.addEventListener("abort",()=>{t(Error("Validation timed out"))})})])
return clearTimeout(n),a}catch(e){return clearTimeout(n),{passed:!1,message:"Validation failed: "+e.message}}}}w.ruleEngine=new c,w.messageResolver=new y({language:"en"})
class v{constructor(e,t={}){this.ruleEngine=e,this.options=t,this.messageResolver=new y({language:"en"})}async validate(e,t,i){const s=[]
if(this.options.parallelValidation){const r=t.rules.map(()=>({...i})),n=t.rules.map(()=>e)
s.push(...await w.validateBatch(n,t.rules,r))}else for(const r of t.rules){const n=await this.ruleEngine.validateValue(e,r,i)
if(s.push(n),n.passed&&t.stopOnFirstPass)return n}if(s.some(e=>e.passed))return{passed:!0}
const r=s.map(e=>e.message).filter(Boolean)
return{passed:!1,message:this.messageResolver.resolve({...i,rule:"union.failed",value:e,parameters:[r.join(", ")]})||r.join(" OR ")}}}class x{constructor(e){this.messageResolver=e,this.batchSize=50}async validateTasks(e){if(0===e.length)return[]
const t=[]
for(let i=0;e.length>i;i+=this.batchSize){const s=e.slice(i,i+this.batchSize),r=await this.processBatch(s)
t.push(...r)}return t}async processBatch(e){const t=await Promise.allSettled(e.map(e=>this.executeTask(e))),i=[]
return t.forEach((t,s)=>{var r
if("fulfilled"===t.status){const e=t.value
!e.passed&&e.message&&i.push(this.createValidationError(e))}else{const n=e[s]
i.push({field:n.context.field,rule:n.rule,message:"Task execution failed: "+((null===(r=t.reason)||void 0===r?void 0:r.message)||"Unknown error"),value:n.value,parameters:n.context.parameters||[]})}}),i}async executeTask(e){try{const t=await e.validator(e.value,e.context)
return{passed:t.passed,message:t.message||(t.passed?"invalid":this.resolveMessage(e)),context:e.context,ruleName:e.rule,value:e.value}}catch(t){return{passed:!1,message:this.resolveMessage(e)||"Validation failed: "+t.message,context:e.context,ruleName:e.rule,value:e.value}}}resolveMessage(e){return this.messageResolver.resolve({...e.context,rule:e.rule,value:e.value,parameters:e.context.parameters||[]})}createValidationError(e){return{field:e.context.field,rule:e.ruleName,message:e.message,value:e.value,parameters:e.context.parameters||[]}}setBatchSize(e){if(0>=e)throw Error("Batch size must be greater than 0")
this.batchSize=e}getBatchSize(){return this.batchSize}}const _=new Set(["string","number","boolean","date","file","array","object"]),E=new Set(["required","optional","nullable","required_with","required_unless","required_with_all","required_without","required_if","prohibited_if","prohibited_unless","prohibited","same","present","confirmed","different"])
class q{constructor(){this.priority=2}canParse(e){if(!Array.isArray(e))return!1
for(let t=0;e.length>t;t++){const i=e[t]
if("string"!=typeof i){if(!Array.isArray(i))return!1
for(let e=0;i.length>e;e++)if("string"!=typeof i[e])return!1}}return!0}parse(e){if(!this.canParse(e))throw Error("Invalid array schema")
const t=e
if(t.length>0&&Array.isArray(t[0])){const e=[]
e.length=t.length
for(let i=0;t.length>i;i++)e[i]=this.parseRuleSet(t[i])
return e}return this.parseRuleSet(t)}parseRuleSet(e){let t
for(let i=0;e.length>i;i++){const[s]=this.parseRule(e[i])
if(_.has(s)){t=s
break}}t||(t="string")
const i=[]
i.length=e.length
for(let s=0;e.length>s;s++){const[r,n]=this.parseRule(e[s])
_.has(r)?(t=r,i[s]={name:r,parameters:[],modifiers:[],dataType:t}):i[s]=E.has(r)?{name:r,parameters:this.convertParameters(n),modifiers:[],isModifier:!0}:o.isCustomRule(r)?{name:r,parameters:this.convertParameters(n),modifiers:[],dataType:"custom"}:{name:`${t}.${r}`,parameters:this.convertParameters(n),modifiers:[],dataType:t}}retur