UNPKG

validlyjs

Version:

A high-performance Laravel-inspired validation library for TypeScript/JavaScript

250 lines 77.4 kB
"use strict" 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 r=new Date(i.getFullYear(),i.getMonth(),i.getDate()) return r.setDate(r.getDate()-1),r case"now":return new Date default:const s=t.match(/^([+-]?\d+)\s*(day|days|week|weeks|month|months|year|years)$/) if(s){const e=parseInt(s[1]),t=s[2],r=new Date(i.getFullYear(),i.getMonth(),i.getDate()) switch(t){case"day":case"days":r.setDate(r.getDate()+e) break case"week":case"weeks":r.setDate(r.getDate()+7*e) break case"month":case"months":r.setMonth(r.getMonth()+e) break case"year":case"years":r.setFullYear(r.getFullYear()+e)}return r}}const r=e.length if(r>=19&&"-"===e[4]&&"-"===e[7]&&"T"===e[10]&&"Z"===e[r-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&&T.test(e)){const t=new Date(e) return isNaN(t.getTime())?null:t}}if(r>=4&&11>=r&&-1!==e.indexOf(":")&&L.test(e))return j(e)?e:null let s=-1 for(let t=0;r>t;t++)if(" "===e[t]){s=t break}const n=-1===s?e:e.substring(0,s),a=-1===s?null:e.substring(s+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,c=0,h=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?(h=f,c=m,u=p):(u=f,c=m,h=p),1>c||c>12||1>u||u>31||1>h)return null const g=2===c&&(e=>!(3&e||!(e%100)&&e%400))(h)?29:k[c-1] if(u>g)return null let b=0,y=0,w=0 if(a){const e=j(a) if(!e)return null;({hours:b,minutes:y,seconds:w}=e)}const v=new Date(Date.UTC(h,c-1,u,b,y,w)) return isNaN(v.getTime())?null:v}let t=null var i class r{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,r,s 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!==(r=t.async)&&void 0!==r&&r,priority:null!==(s=t.priority)&&void 0!==s?s: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,r]=await Promise.all([Promise.resolve().then(function(){return require("./required-DiadzJZd.js")}),Promise.resolve().then(function(){return require("./union-Mx6YWGWM.js")}),Promise.resolve().then(function(){return require("./conditional-kRtsUIBJ.js")}),Promise.resolve().then(function(){return require("./type-checking-Bhwdob3X.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",r.stringRule],["number",r.numberRule],["integer",r.integerRule],["boolean",r.booleanRule],["array",r.arrayRule],["object",r.objectRule],["date",r.dateRule],["file",r.fileRule],["numeric",r.numericRule],["scalar",r.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 Promise.resolve().then(function(){return require("./index-DyrwNILO.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 Promise.resolve().then(function(){return require("./index-DDEelnlm.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 Promise.resolve().then(function(){return require("./index-CFShhj8R.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 Promise.resolve().then(function(){return require("./index-m0ye0X0i.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([Promise.resolve().then(function(){return require("./size-DyoYAZ4g.js")}),Promise.resolve().then(function(){return require("./content-CK7CjvBv.js")}),Promise.resolve().then(function(){return require("./each-D3uXuu7i.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 Promise.resolve().then(function(){return require("./index-CAwhX_lm.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,r]=await Promise.all([Promise.resolve().then(function(){return require("./size-DBEB7Lg8.js")}),Promise.resolve().then(function(){return require("./type-B_GpD7OX.js")}),Promise.resolve().then(function(){return require("./image-DLTGmMdW.js")}),Promise.resolve().then(function(){return require("./dimensions-Dr73dDT8.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",r.fileWidthRule],["file.height",r.fileHeightRule],["file.min_width",r.fileMinWidthRule],["file.max_width",r.fileMaxWidthRule],["file.min_height",r.fileMinHeightRule],["file.max_height",r.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([Promise.resolve().then(function(){return require("./port-Nvur2DHK.js")}),Promise.resolve().then(function(){return require("./domain-BZTZUwnJ.js")})]);[["network.port",e.portRule],["network.domain",t.domainRule]].forEach(([e,t])=>this.register(e,t)),this.loadedModules.add("network")}catch(e){}}}i=r,r.rules=new Map,r.defaultMessages=new Map,r.customRules=new Map,r.loadedModules=new Set,t={getCustomRuleMessage:e=>i.defaultMessages.get(e)} class s{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 n{constructor(){this.cache=new Map,this.maxSize=1e3,this.accessOrder=[],this.stats=new s}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 a{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 o{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=[],r=[] let s=null for(const e of t)try{const t=this.parseRule(e) if(this.isUnionRule(t,e))return this.handleUnionRule(e,t,r) const n=this.processRule(t,s) n.isModifier?r.push(n):(n.dataType&&o.DATA_TYPES.has(n.dataType)&&(s=n.dataType),i.push(n))}catch(t){throw Error(`Error parsing rule '${e}': ${t.message}`)}return[...r,...i]}isUnionRule(e,t){return"union"===e[0]||t.startsWith("union:")}handleUnionRule(e,t,i){var r if(!this.unionParser)throw Error("Union parser not available") const s=e.startsWith("union:")?e:"union:"+((null===(r=t[1])||void 0===r?void 0:r.join(","))||""),n=this.unionParser.parse(s) return i.length>0?[...i,...n]:n}processRule(e,t){const[i,s]=e return o.DATA_TYPES.has(i)?{name:i,parameters:s||[],modifiers:[],dataType:i}:o.MODIFIERS.has(i)?{name:i,parameters:s||[],modifiers:[],isModifier:!0}:r.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="",r={inParameters:!1,bracketDepth:0,inQuotes:!1,quoteChar:""} for(let s=0;e.length>s;s++){const n=e[s] this.handleQuotes(n,r)?i+=n:this.handleSpecialCharacters(n,r,i,t,s,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,r,s,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,s+1);-1!==e&&/[a-zA-Z]/.test(n[e])&&(t.inParameters=!1)}if(!t.inParameters)return r.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(),r=e.substring(t+1) return r?"union"===i?[i,[r]]:o.LITERAL_PARAMETER_RULES.has(i)?[i,[r.trim()]]:[i,this.parseParameters(r)]:[i,null]}parseParameters(e){const t=[] let i="",r=!1,s="" for(const n of e)this.handleParameterQuotes(n,{inQuotes:r,quoteChar:s},i,t)?({inQuotes:r,quoteChar:s}={inQuotes:r,quoteChar:s}):","!==n||r?i+=n:(t.push(this.convertParameter(i.trim())),i="") return i.trim()&&t.push(this.convertParameter(i.trim())),t}handleParameterQuotes(e,t,i,r){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 o.LITERAL_PARAMETER_RULES)if(e.startsWith(t+":"))return t.length return e.indexOf(":")}}o.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"]),o.DATA_TYPES=new Set(["string","number","boolean","date","array","object","file"]),o.LITERAL_PARAMETER_RULES=new Set(["format","regex","pattern"]) class l{constructor(){this.cache=new n,this.stringParser=new o,r.loadBuiltInRules()}registerRule(e){r.register(e.name,e)}registerCustomRule(e){r.registerCustomRule(e.name,e)}getRule(e){return r.get(e)}getAllRules(){return Array.from(r.getAll().values())}hasRule(e){return r.has(e)}async executeRule(e,t,i,r){const s=`${e}:${r.field}:${JSON.stringify(i)}:${JSON.stringify(t)}`,n=this.cache.get(s) 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,r.field,r.data),n={passed:e,skip:!1,...!e&&a.message&&{message:a.message}} return this.cache.set(s,n),n}catch(t){const i={passed:!1,message:`Rule "${e}" execution failed: ${t.message}`,skip:!1} return this.cache.set(s,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 r of t){const t=await this.validateValue(e,r,i) if(!t.passed||t.skip)return t}return{passed:!0,skip:!1}}async validateStringRule(e,t,i){try{const r=this.stringParser.parse(t) for(const t of r){const r=await this.executeRule(t.name,e,t.parameters||[],i) if(!r.passed||r.skip)return r}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 r=await this.processModifiers(e,t.l,i) if(!r.passed||r.skip)return r}for(const r of t.o){const t=await this.executeRule(r.name,e,r.parameters||[],i) if(!t.passed||t.skip)return t}return{passed:!0,skip:!1}}async processModifiers(e,t,i){for(const r of t){let t switch(r.type){case"required":t=await this.executeRule("required",e,[],i) break case"nullable":t=await this.executeRule("nullable",e,[],i) break case"conditional":if(r.parameters){const[s,...n]=r.parameters t=await this.executeRule(s,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 r of t.rules)if((await this.validateValue(e,r,i)).passed)return{passed:!0,skip:!1} return{passed:!1,message:"None of the union rules passed.",skip:!1}}}class d{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,r){const s=Object.entries(e) for(let e=0;s.length>e;e++){const[n,a]=s[e],o=n.includes("*"),l=i?`${i}.${n}`:n if(o)this.resolveWildcardPath(l,t,a,r) else{const e=this.resolvePath(t,l) if(void 0===e&&this.isOptionalField(a))continue if(r.set(l,e),Array.isArray(e))for(let t=0;e.length>t;t++)r.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 r=e[t] if("string"==typeof r&&("optional"===r||"nullable"===r||-1!==r.indexOf("optional")||-1!==r.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 r=t[e] if("optional"===(null==r?void 0:r.type)||"nullable"===(null==r?void 0:r.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,r){const s=this.getPathSegments(e) let n=-1 for(let e=0;s.length>e;e++)if("*"===s[e]){n=e break}if(-1===n)return const a=s.slice(0,n).join("."),o=s.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}]`,s=this.resolvePath(t,e) r.set(e,s)}}else if("object"==typeof l&&null!==l){const e=Object.keys(l) for(let i=0;e.length>i;i++){const s=e[i],n=o?`${a}.${s}.${o}`:`${a}.${s}`,l=this.resolvePath(t,n) r.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 r=e for(let e=0;i.length>e;e++){if(void 0===r)return const t=i[e],s=this.arrayIndexRegex.exec(t) if(s){const e=s[1],t=s[2] if(!e||!t)return {const i=r[e] if(!Array.isArray(i))return r=i[parseInt(t,10)]}}else r=r[t]}return r}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 u{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 r=[] let s=0 for(const n of i.placeholders){n.index>s&&r.push(e.substring(s,n.index)) const i=this.resolvePlaceholder(n,t) r.push(i),s=e.indexOf("}",n.index)+1}return e.length>s&&r.push(e.substring(s)),r.join("")}compileTemplate(e){const t=[],i=/{([^}]+)}/g let r for(;null!==(r=i.exec(e));){const e=this.parsePlaceholder(r[1],r.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 r=this.resolveNamedPlaceholder(e.key,t) return"formats"===e.key?null!==r?r+"":"":null!==r?this.formatValue(r):"" case"custom":const s=this.placeholderFormatters.get(e.formatter) return s?s(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 r=i.indexOf(e) return r>=0&&t.parameters.length>r?t.parameters[r]: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 c={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"},h={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"},f={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 m{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 u,this.languagePacks=new Map,this.loadDefaultLanguages(),this.updateCurrentLanguagePack(),this.bridge=t,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:r,messages:s}=this.config,n=r[`${t}.${i}`] if(n)return n const a=this.findWildcardMessageOptimized(t,i,r) if(a)return a const o=s[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 r let s=this.wildcardPatternCache.get(e) s||(s=this.generateWildcardPatterns(e),this.wildcardPatternCache.set(e,s)) for(let e=0;s.length>e;e++){const n=i[`${null===(r=null==s?void 0:s[e])||void 0===r?void 0:r.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 r=t.slice() r[e]="*",i[t.length-1-e]={pattern:r.join("."),segments:r}}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",c),this.languagePacks.set("es",h),this.languagePacks.set("fr",f)}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 p{static async validateBatch(e,t,i){const r=[] for(let s=0;e.length>s;s+=50){const n=e.slice(s,s+50),a=t.slice(s,s+50),o=i.slice(s,s+50),l=await Promise.all(n.map((e,t)=>{const i=a[t] if(!i)return{passed:!1,message:"No validation rule provided"} const r=o[t] return r?this.validateSingle(e,i,r):{passed:!1,message:"No validation context provided"}})) r.push(...l)}return r}static async validateSingle(e,t,i){try{const r=await this.ruleEngine.validateValue(e,t,i) if(!r.passed&&!r.message){let s="unknown" "string"==typeof t?s=t.split(":")[0]||"unknown":Array.isArray(t)?s="array_rule":"t"in t&&(s="fluent"===t.t?t.i:"union"),r.message=this.messageResolver.resolve({...i,rule:s,value:e,parameters:i.parameters||[]})}return r}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,r=4){const s=Math.ceil(e.length/r),n=[] for(let r=0;e.length>r;r+=s)n.push({values:e.slice(r,r+s),rules:t.slice(r,r+s),contexts:i.slice(r,r+s)}) return(await Promise.all(n.map(e=>this.validateBatch(e.values,e.rules,e.contexts)))).flat()}static async validateWithTimeout(e,t,i,r=5e3){const s=new AbortController,n=setTimeout(()=>s.abort(),r) try{const r=this.validateSingle(e,t,i),a=await Promise.race([r,new Promise((e,t)=>{s.signal.addEventListener("abort",()=>{t(Error("Validation timed out"))})})]) return clearTimeout(n),a}catch(e){return clearTimeout(n),{passed:!1,message:"Validation failed: "+e.message}}}}p.ruleEngine=new l,p.messageResolver=new m({language:"en"}) class g{constructor(e,t={}){this.ruleEngine=e,this.options=t,this.messageResolver=new m({language:"en"})}async validate(e,t,i){const r=[] if(this.options.parallelValidation){const s=t.rules.map(()=>({...i})),n=t.rules.map(()=>e) r.push(...await p.validateBatch(n,t.rules,s))}else for(const s of t.rules){const n=await this.ruleEngine.validateValue(e,s,i) if(r.push(n),n.passed&&t.stopOnFirstPass)return n}if(r.some(e=>e.passed))return{passed:!0} const s=r.map(e=>e.message).filter(Boolean) return{passed:!1,message:this.messageResolver.resolve({...i,rule:"union.failed",value:e,parameters:[s.join(", ")]})||s.join(" OR ")}}}class b{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 r=e.slice(i,i+this.batchSize),s=await this.processBatch(r) t.push(...s)}return t}async processBatch(e){const t=await Promise.allSettled(e.map(e=>this.executeTask(e))),i=[] return t.forEach((t,r)=>{var s if("fulfilled"===t.status){const e=t.value !e.passed&&e.message&&i.push(this.createValidationError(e))}else{const n=e[r] i.push({field:n.context.field,rule:n.rule,message:"Task execution failed: "+((null===(s=t.reason)||void 0===s?void 0:s.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 y=new Set(["string","number","boolean","date","file","array","object"]),w=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 v{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