@warlock.js/seal 5.5.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/cjs/index.cjs +20 -14
- package/cjs/index.cjs.map +1 -1
- package/esm/factory/validate.mjs.map +1 -1
- package/esm/factory/validators.mjs.map +1 -1
- package/esm/helpers/validation-helpers.mjs +7 -1
- package/esm/helpers/validation-helpers.mjs.map +1 -1
- package/esm/rules/date/date-period-rules.d.mts.map +1 -1
- package/esm/rules/date/date-period-rules.mjs +2 -0
- package/esm/rules/date/date-period-rules.mjs.map +1 -1
- package/esm/rules/string/credit-card.mjs +1 -1
- package/esm/rules/string/credit-card.mjs.map +1 -1
- package/esm/validators/base-validator.mjs +2 -2
- package/esm/validators/base-validator.mjs.map +1 -1
- package/esm/validators/object-validator.d.mts.map +1 -1
- package/esm/validators/object-validator.mjs +8 -10
- package/esm/validators/object-validator.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.mjs","names":[],"sources":["../../../../../../../seal/src/factory/validate.ts"],"sourcesContent":["import { getSealConfig } from \"../config\";\r\nimport type { SchemaContext, ValidationResult } from \"../types\";\r\nimport type { BaseValidator } from \"../validators\";\r\nimport {
|
|
1
|
+
{"version":3,"file":"validate.mjs","names":[],"sources":["../../../../../../../seal/src/factory/validate.ts"],"sourcesContent":["import { getSealConfig } from \"../config\";\r\nimport type { SchemaContext, ValidationResult } from \"../types\";\r\nimport type { BaseValidator } from \"../validators\";\r\nimport type { ValidateOptions } from \"./validators\";\r\n\r\n/**\r\n * Validate data against a schema\r\n */\r\nexport const validate = async <T extends BaseValidator>(\r\n schema: T,\r\n data: any, // Temporarily use any - will fix type inference\r\n { context: extendedContext, ...configurations }: ValidateOptions = getSealConfig() || {},\r\n): Promise<ValidationResult> => {\r\n const context: SchemaContext = {\r\n allValues: data,\r\n parent: null,\r\n value: data,\r\n key: \"\",\r\n path: \"\",\r\n context: extendedContext,\r\n rootContext: extendedContext,\r\n translateRule(ruleTranslation) {\r\n return configurations.translateRule?.(ruleTranslation) ?? \"\";\r\n },\r\n translateAttribute(attributeTranslation) {\r\n return configurations.translateAttribute?.(attributeTranslation) ?? \"\";\r\n },\r\n configurations,\r\n };\r\n\r\n const result = await schema.validate(data, context);\r\n\r\n // A failed validation never hands back the input it just rejected.\r\n //\r\n // `object` used to return the raw input on failure while `discriminatedUnion`\r\n // returned `undefined` — the same call shape with two different contracts.\r\n // The object behaviour was the dangerous one: validating an outbound DTO\r\n // specifically to keep internal fields out of a response, then doing the\r\n // natural `const { data } = await v.validate(dto, record); reply.send(data)`,\r\n // shipped every field the schema existed to exclude. A guard that returns the\r\n // unsafe value on failure reads as safe and isn't.\r\n if (!result.isValid) {\r\n return { ...result, data: undefined };\r\n }\r\n\r\n return result;\r\n};\r\n"],"mappings":";;;;;;AAQA,MAAa,WAAW,OACtB,QACA,MACA,EAAE,SAAS,iBAAiB,GAAG,mBAAoC,cAAc,KAAK,CAAC,MACzD;CAC9B,MAAM,UAAyB;EAC7B,WAAW;EACX,QAAQ;EACR,OAAO;EACP,KAAK;EACL,MAAM;EACN,SAAS;EACT,aAAa;EACb,cAAc,iBAAiB;GAC7B,OAAO,eAAe,gBAAgB,eAAe,KAAK;EAC5D;EACA,mBAAmB,sBAAsB;GACvC,OAAO,eAAe,qBAAqB,oBAAoB,KAAK;EACtE;EACA;CACF;CAEA,MAAM,SAAS,MAAM,OAAO,SAAS,MAAM,OAAO;CAWlD,IAAI,CAAC,OAAO,SACV,OAAO;EAAE,GAAG;EAAQ,MAAM;CAAU;CAGtC,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.mjs","names":["validateFunction"],"sources":["../../../../../../../seal/src/factory/validators.ts"],"sourcesContent":["import { type SealConfig } from \"../config\";\nimport type { StandardSchemaV1 } from \"../standard-schema/types\";\nimport type { Schema, SchemaContext, ValidationResult } from \"../types\";\nimport type { Infer } from \"../types/inference-types\";\nimport { AnyValidator } from \"../validators/any-validator\";\nimport { ArrayValidator } from \"../validators/array-validator\";\nimport type { BaseValidator } from \"../validators/base-validator\";\nimport { BooleanValidator } from \"../validators/boolean-validator\";\nimport { ComputedValidator } from \"../validators/computed-validator\";\nimport { DateValidator } from \"../validators/date-validator\";\nimport { DiscriminatedUnionValidator } from \"../validators/discriminated-union-validator\";\nimport { FloatValidator } from \"../validators/float-validator\";\nimport { InstanceOfValidator } from \"../validators/instanceof-validator\";\nimport { IntValidator } from \"../validators/int-validator\";\nimport { LazyValidator } from \"../validators/lazy-validator\";\nimport { LiteralValidator } from \"../validators/literal-validator\";\nimport { ManagedValidator } from \"../validators/managed-validator\";\nimport { NumberValidator } from \"../validators/number-validator\";\nimport { NumericValidator } from \"../validators/numeric-validator\";\nimport { ObjectValidator } from \"../validators/object-validator\";\nimport { RecordValidator } from \"../validators/record-validator\";\nimport { ScalarValidator } from \"../validators/scalar-validator\";\nimport { StringValidator } from \"../validators/string-validator\";\nimport { TupleValidator } from \"../validators/tuple-validator\";\nimport { UnionValidator } from \"../validators/union-validator\";\n// BaseValidator prototype augmentations — side-effect imports so the `v`\n// factory always exposes the chain methods (.required, .requiredIf, .sameAs,\n// .present, .forbidden, .when, …) regardless of which entry path loaded it.\n// The package barrel (src/index.ts) loads these via the validators barrel, but\n// importing the factory leaf directly would otherwise yield a half-built `v`.\nimport \"../validators/methods/equality-conditional-methods\";\nimport \"../validators/methods/forbidden-methods\";\nimport \"../validators/methods/present-methods\";\nimport \"../validators/methods/required-methods\";\nimport { validate as validateFunction } from \"./validate\";\n\n/**\n * Seal factory object - creates instances of validators\n *\n * Use 'v' to create validation schemas (seals) for your data\n */\nexport const v: ValidatorV = {\n /** Create an object validator */\n object: <T extends Schema>(schema: T, errorMessage?: string) =>\n new ObjectValidator<T>(schema, errorMessage) as ObjectValidator<T> &\n StandardSchemaV1<Infer<ObjectValidator<T>>>,\n\n /** Create an any validator */\n any: () => new AnyValidator() as AnyValidator & StandardSchemaV1<any>,\n\n /** Create an array validator */\n array: <T extends BaseValidator>(validator: T, errorMessage?: string) =>\n new ArrayValidator(validator, errorMessage) as ArrayValidator & {\n validator: T;\n } & StandardSchemaV1<Array<Infer<T>>>,\n\n /** Create a record validator - object with dynamic keys and consistent value types */\n record: <T extends BaseValidator>(validator?: T, errorMessage?: string) =>\n new RecordValidator(validator || v.any(), errorMessage) as RecordValidator & {\n valueValidator: T;\n } & StandardSchemaV1<Record<string, Infer<T>>>,\n\n /** Create a tuple validator - fixed-length array with position-specific types */\n tuple: <T extends BaseValidator[]>(validators: T, errorMessage?: string) =>\n new TupleValidator(validators, errorMessage) as TupleValidator & {\n validators: T;\n } & StandardSchemaV1<{ [K in keyof T]: Infer<T[K]> }>,\n\n /** Create a date validator */\n date: (errorMessage?: string) =>\n new DateValidator(errorMessage) as DateValidator & StandardSchemaV1<Date>,\n\n /**\n * Create a literal validator — narrows to the union of given literal values\n *\n * @example\n * v.literal(\"items\") // type: \"items\"\n * v.literal(\"draft\", \"published\") // type: \"draft\" | \"published\"\n * v.literal(1, 2, 3) // type: 1 | 2 | 3\n */\n literal: <T extends readonly [string | number | boolean, ...(string | number | boolean)[]]>(\n ...values: T\n ) =>\n new LiteralValidator<T>(values) as LiteralValidator<T> & StandardSchemaV1<T[number]>,\n\n /**\n * Create an instanceof validator — value must be `instanceof` the constructor\n *\n * @example\n * v.instanceof(File) // type: File\n * v.instanceof(Buffer) // type: Buffer\n * v.instanceof(MyClass) // type: MyClass\n */\n instanceof: <T>(ctor: new (...args: any[]) => T, errorMessage?: string) =>\n new InstanceOfValidator<T>(ctor, errorMessage) as InstanceOfValidator<T> &\n StandardSchemaV1<T>,\n\n /**\n * Create a lazy validator — defers resolution of the inner validator until\n * validate-time. Use for recursive or forward-referenced schemas.\n *\n * @example\n * type Category = { name: string; children: Category[] };\n *\n * const category: ObjectValidator<...> = v.object({\n * name: v.string(),\n * children: v.array(v.lazy(() => category)),\n * });\n */\n lazy: <T extends BaseValidator>(thunk: () => T) =>\n new LazyValidator(thunk) as LazyValidator<T> & StandardSchemaV1<Infer<T>>,\n\n /** Create a string validator */\n string: (errorMessage?: string) =>\n new StringValidator(errorMessage) as StringValidator & StandardSchemaV1<string>,\n\n /** Create an email validator */\n email: (emailErrorMessage?: string, errorMessage?: string) =>\n new StringValidator(errorMessage).email(emailErrorMessage) as StringValidator &\n StandardSchemaV1<string>,\n\n /**\n * Create an enum validator — preserves the literal union of accepted\n * values in the inferred Standard Schema output.\n *\n * Two input shapes:\n * - Tuple of literals: `v.enum([\"draft\", \"published\"])` →\n * `StandardSchemaV1<\"draft\" | \"published\">`\n * - TypeScript enum object: `v.enum(Status)` →\n * `StandardSchemaV1<Status[keyof Status]>`\n *\n * Implementation is loosely typed; the public `ValidatorV.enum`\n * surface declares the precise overloads.\n */\n enum: ((values: any, errorMessage?: string) =>\n Array.isArray(values)\n ? new StringValidator().oneOf(values, errorMessage)\n : new ScalarValidator().enum(values, errorMessage)) as ValidatorV[\"enum\"],\n\n /** Create a number validator */\n number: (errorMessage?: string) =>\n new NumberValidator(errorMessage) as NumberValidator & StandardSchemaV1<number>,\n\n /** Create a numeric validator */\n numeric: (errorMessage?: string) =>\n new NumericValidator(errorMessage) as NumericValidator & StandardSchemaV1<number>,\n\n /** Create an integer validator */\n int: (errorMessage?: string) =>\n new IntValidator(errorMessage) as IntValidator & StandardSchemaV1<number>,\n\n /** Create a float validator */\n float: (errorMessage?: string) =>\n new FloatValidator(errorMessage) as FloatValidator & StandardSchemaV1<number>,\n\n /** Create a boolean validator */\n boolean: (errorMessage?: string) =>\n new BooleanValidator(errorMessage) as BooleanValidator & StandardSchemaV1<boolean>,\n\n /** Create a scalar validator */\n scalar: (errorMessage?: string) =>\n new ScalarValidator(errorMessage) as ScalarValidator &\n StandardSchemaV1<string | number | boolean>,\n\n /** Create a union validator - validates against multiple types */\n union: <T extends BaseValidator[]>(validators: T, errorMessage?: string) =>\n new UnionValidator().union(validators, errorMessage) as UnionValidator &\n StandardSchemaV1<Infer<T[number]>>,\n\n /**\n * Create a discriminated union — routes payloads by a shared literal\n * discriminator field. Each branch must be a `v.object(...)` with the\n * discriminator typed as `v.literal(...)`.\n *\n * @example\n * const email = v.object({ type: v.literal(\"email\"), email: v.string().email() });\n * const sms = v.object({ type: v.literal(\"sms\"), phone: v.string() });\n * const notif = v.discriminatedUnion(\"type\", [email, sms]);\n * // type T = Infer<typeof notif>;\n * // → { type: \"email\", email: string } | { type: \"sms\", phone: string }\n */\n discriminatedUnion: <\n K extends string,\n Branches extends ReadonlyArray<ObjectValidator<any>>,\n >(\n discriminator: K,\n validators: Branches,\n ) =>\n new DiscriminatedUnionValidator(discriminator, validators) as DiscriminatedUnionValidator<\n K,\n Branches\n > &\n StandardSchemaV1<Infer<Branches[number]>>,\n\n /** Create a computed field validator - derives value from other validated fields */\n computed: <TResult = any>(\n callback: (data: any, context: SchemaContext) => TResult | Promise<TResult>,\n resultValidator?: BaseValidator,\n ) =>\n new ComputedValidator<TResult>(callback, resultValidator) as ComputedValidator<TResult> &\n StandardSchemaV1<TResult>,\n\n /** Create a managed field validator - framework-injected value */\n managed: <TResult = any>(\n callback: (context: SchemaContext) => TResult | Promise<TResult>,\n resultValidator?: BaseValidator,\n ) =>\n new ManagedValidator<TResult>(callback, resultValidator) as ManagedValidator<TResult> &\n StandardSchemaV1<TResult>,\n\n /** Validate data against a schema */\n validate: validateFunction,\n} as unknown as ValidatorV;\n\nexport type ValidateOptions = {\n context?: Record<string, any>;\n} & SealConfig;\n\nexport interface ValidatorV {\n object: <T extends Schema>(\n schema: T,\n errorMessage?: string,\n ) => ObjectValidator<T> & StandardSchemaV1<Infer<ObjectValidator<T>>>;\n any: () => AnyValidator & StandardSchemaV1<any>;\n array: <T extends BaseValidator>(\n validator: T,\n errorMessage?: string,\n ) => ArrayValidator & {\n validator: T;\n } & StandardSchemaV1<Array<Infer<T>>>;\n record: <T extends BaseValidator>(\n validator?: T,\n errorMessage?: string,\n ) => RecordValidator & {\n valueValidator: T;\n } & StandardSchemaV1<Record<string, Infer<T>>>;\n tuple: <T extends BaseValidator[]>(\n validators: T,\n errorMessage?: string,\n ) => TupleValidator & {\n validators: T;\n } & StandardSchemaV1<{ [K in keyof T]: Infer<T[K]> }>;\n date: (errorMessage?: string) => DateValidator & StandardSchemaV1<Date>;\n literal: <T extends readonly [string | number | boolean, ...(string | number | boolean)[]]>(\n ...values: T\n ) => LiteralValidator<T> & StandardSchemaV1<T[number]>;\n instanceof: <T>(\n ctor: new (...args: any[]) => T,\n errorMessage?: string,\n ) => InstanceOfValidator<T> & StandardSchemaV1<T>;\n lazy: <T extends BaseValidator>(\n thunk: () => T,\n ) => LazyValidator<T> & StandardSchemaV1<Infer<T>>;\n string: (errorMessage?: string) => StringValidator & StandardSchemaV1<string>;\n email: (errorMessage?: string) => StringValidator & StandardSchemaV1<string>;\n enum: {\n <const T extends readonly (string | number | boolean)[]>(\n values: T,\n errorMessage?: string,\n ): ScalarValidator & StandardSchemaV1<T[number]>;\n <const T extends Record<string, string | number>>(\n values: T,\n errorMessage?: string,\n ): ScalarValidator & StandardSchemaV1<T[keyof T]>;\n };\n number: (errorMessage?: string) => NumberValidator & StandardSchemaV1<number>;\n numeric: (errorMessage?: string) => NumericValidator & StandardSchemaV1<number>;\n int: (errorMessage?: string) => IntValidator & StandardSchemaV1<number>;\n float: (errorMessage?: string) => FloatValidator & StandardSchemaV1<number>;\n boolean: (errorMessage?: string) => BooleanValidator & StandardSchemaV1<boolean>;\n scalar: (\n errorMessage?: string,\n ) => ScalarValidator & StandardSchemaV1<string | number | boolean>;\n union: <T extends BaseValidator[]>(\n validators: T,\n errorMessage?: string,\n ) => UnionValidator & StandardSchemaV1<Infer<T[number]>>;\n discriminatedUnion: <\n K extends string,\n Branches extends ReadonlyArray<ObjectValidator<any>>,\n >(\n discriminator: K,\n validators: Branches,\n ) => DiscriminatedUnionValidator<K, Branches> & StandardSchemaV1<Infer<Branches[number]>>;\n computed: <TResult = any>(\n callback: (data: any, context: SchemaContext) => TResult | Promise<TResult>,\n resultValidator?: BaseValidator,\n ) => ComputedValidator<TResult> & StandardSchemaV1<TResult>;\n managed: <TResult = any>(\n callback?: (context: SchemaContext) => TResult | Promise<TResult>,\n resultValidator?: BaseValidator,\n ) => ManagedValidator<TResult> & StandardSchemaV1<TResult>;\n validate: <T extends BaseValidator>(\n schema: T,\n data: any,\n options?: ValidateOptions,\n ) => Promise<ValidationResult>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,IAAgB;;CAE3B,SAA2B,QAAW,iBACpC,IAAI,gBAAmB,QAAQ,YAAY;;CAI7C,WAAW,IAAI,aAAa;;CAG5B,QAAiC,WAAc,iBAC7C,IAAI,eAAe,WAAW,YAAY;;CAK5C,SAAkC,WAAe,iBAC/C,IAAI,gBAAgB,aAAa,EAAE,IAAI,GAAG,YAAY;;CAKxD,QAAmC,YAAe,iBAChD,IAAI,eAAe,YAAY,YAAY;;CAK7C,OAAO,iBACL,IAAI,cAAc,YAAY;;;;;;;;;CAUhC,UACE,GAAG,WAEH,IAAI,iBAAoB,MAAM;;;;;;;;;CAUhC,aAAgB,MAAiC,iBAC/C,IAAI,oBAAuB,MAAM,YAAY;;;;;;;;;;;;;CAe/C,OAAgC,UAC9B,IAAI,cAAc,KAAK;;CAGzB,SAAS,iBACP,IAAI,gBAAgB,YAAY;;CAGlC,QAAQ,mBAA4B,iBAClC,IAAI,gBAAgB,YAAY,CAAC,CAAC,MAAM,iBAAiB;;;;;;;;;;;;;;CAgB3D,QAAQ,QAAa,iBACnB,MAAM,QAAQ,MAAM,IAChB,IAAI,gBAAgB,CAAC,CAAC,MAAM,QAAQ,YAAY,IAChD,IAAI,gBAAgB,CAAC,CAAC,KAAK,QAAQ,YAAY;;CAGrD,SAAS,iBACP,IAAI,gBAAgB,YAAY;;CAGlC,UAAU,iBACR,IAAI,iBAAiB,YAAY;;CAGnC,MAAM,iBACJ,IAAI,aAAa,YAAY;;CAG/B,QAAQ,iBACN,IAAI,eAAe,YAAY;;CAGjC,UAAU,iBACR,IAAI,iBAAiB,YAAY;;CAGnC,SAAS,iBACP,IAAI,gBAAgB,YAAY;;CAIlC,QAAmC,YAAe,iBAChD,IAAI,eAAe,CAAC,CAAC,MAAM,YAAY,YAAY;;;;;;;;;;;;;CAerD,qBAIE,eACA,eAEA,IAAI,4BAA4B,eAAe,UAAU;;CAO3D,WACE,UACA,oBAEA,IAAI,kBAA2B,UAAU,eAAe;;CAI1D,UACE,UACA,oBAEA,IAAI,iBAA0B,UAAU,eAAe;;CAI/CA;AACZ"}
|
|
1
|
+
{"version":3,"file":"validators.mjs","names":["validateFunction"],"sources":["../../../../../../../seal/src/factory/validators.ts"],"sourcesContent":["import type { SealConfig } from \"../config\";\r\nimport type { StandardSchemaV1 } from \"../standard-schema/types\";\r\nimport type { Schema, SchemaContext, ValidationResult } from \"../types\";\r\nimport type { Infer } from \"../types/inference-types\";\r\nimport { AnyValidator } from \"../validators/any-validator\";\r\nimport { ArrayValidator } from \"../validators/array-validator\";\r\nimport type { BaseValidator } from \"../validators/base-validator\";\r\nimport { BooleanValidator } from \"../validators/boolean-validator\";\r\nimport { ComputedValidator } from \"../validators/computed-validator\";\r\nimport { DateValidator } from \"../validators/date-validator\";\r\nimport { DiscriminatedUnionValidator } from \"../validators/discriminated-union-validator\";\r\nimport { FloatValidator } from \"../validators/float-validator\";\r\nimport { InstanceOfValidator } from \"../validators/instanceof-validator\";\r\nimport { IntValidator } from \"../validators/int-validator\";\r\nimport { LazyValidator } from \"../validators/lazy-validator\";\r\nimport { LiteralValidator } from \"../validators/literal-validator\";\r\nimport { ManagedValidator } from \"../validators/managed-validator\";\r\nimport { NumberValidator } from \"../validators/number-validator\";\r\nimport { NumericValidator } from \"../validators/numeric-validator\";\r\nimport { ObjectValidator } from \"../validators/object-validator\";\r\nimport { RecordValidator } from \"../validators/record-validator\";\r\nimport { ScalarValidator } from \"../validators/scalar-validator\";\r\nimport { StringValidator } from \"../validators/string-validator\";\r\nimport { TupleValidator } from \"../validators/tuple-validator\";\r\nimport { UnionValidator } from \"../validators/union-validator\";\r\n// BaseValidator prototype augmentations — side-effect imports so the `v`\r\n// factory always exposes the chain methods (.required, .requiredIf, .sameAs,\r\n// .present, .forbidden, .when, …) regardless of which entry path loaded it.\r\n// The package barrel (src/index.ts) loads these via the validators barrel, but\r\n// importing the factory leaf directly would otherwise yield a half-built `v`.\r\nimport \"../validators/methods/equality-conditional-methods\";\r\nimport \"../validators/methods/forbidden-methods\";\r\nimport \"../validators/methods/present-methods\";\r\nimport \"../validators/methods/required-methods\";\r\nimport { validate as validateFunction } from \"./validate\";\r\n\r\n/**\r\n * Seal factory object - creates instances of validators\r\n *\r\n * Use 'v' to create validation schemas (seals) for your data\r\n */\r\nexport const v: ValidatorV = {\r\n /** Create an object validator */\r\n object: <T extends Schema>(schema: T, errorMessage?: string) =>\r\n new ObjectValidator<T>(schema, errorMessage) as ObjectValidator<T> &\r\n StandardSchemaV1<Infer<ObjectValidator<T>>>,\r\n\r\n /** Create an any validator */\r\n any: () => new AnyValidator() as AnyValidator & StandardSchemaV1<any>,\r\n\r\n /** Create an array validator */\r\n array: <T extends BaseValidator>(validator: T, errorMessage?: string) =>\r\n new ArrayValidator(validator, errorMessage) as ArrayValidator & {\r\n validator: T;\r\n } & StandardSchemaV1<Array<Infer<T>>>,\r\n\r\n /** Create a record validator - object with dynamic keys and consistent value types */\r\n record: <T extends BaseValidator>(validator?: T, errorMessage?: string) =>\r\n new RecordValidator(validator || v.any(), errorMessage) as RecordValidator & {\r\n valueValidator: T;\r\n } & StandardSchemaV1<Record<string, Infer<T>>>,\r\n\r\n /** Create a tuple validator - fixed-length array with position-specific types */\r\n tuple: <T extends BaseValidator[]>(validators: T, errorMessage?: string) =>\r\n new TupleValidator(validators, errorMessage) as TupleValidator & {\r\n validators: T;\r\n } & StandardSchemaV1<{ [K in keyof T]: Infer<T[K]> }>,\r\n\r\n /** Create a date validator */\r\n date: (errorMessage?: string) =>\r\n new DateValidator(errorMessage) as DateValidator & StandardSchemaV1<Date>,\r\n\r\n /**\r\n * Create a literal validator — narrows to the union of given literal values\r\n *\r\n * @example\r\n * v.literal(\"items\") // type: \"items\"\r\n * v.literal(\"draft\", \"published\") // type: \"draft\" | \"published\"\r\n * v.literal(1, 2, 3) // type: 1 | 2 | 3\r\n */\r\n literal: <T extends readonly [string | number | boolean, ...(string | number | boolean)[]]>(\r\n ...values: T\r\n ) =>\r\n new LiteralValidator<T>(values) as LiteralValidator<T> & StandardSchemaV1<T[number]>,\r\n\r\n /**\r\n * Create an instanceof validator — value must be `instanceof` the constructor\r\n *\r\n * @example\r\n * v.instanceof(File) // type: File\r\n * v.instanceof(Buffer) // type: Buffer\r\n * v.instanceof(MyClass) // type: MyClass\r\n */\r\n instanceof: <T>(ctor: new (...args: any[]) => T, errorMessage?: string) =>\r\n new InstanceOfValidator<T>(ctor, errorMessage) as InstanceOfValidator<T> &\r\n StandardSchemaV1<T>,\r\n\r\n /**\r\n * Create a lazy validator — defers resolution of the inner validator until\r\n * validate-time. Use for recursive or forward-referenced schemas.\r\n *\r\n * @example\r\n * type Category = { name: string; children: Category[] };\r\n *\r\n * const category: ObjectValidator<...> = v.object({\r\n * name: v.string(),\r\n * children: v.array(v.lazy(() => category)),\r\n * });\r\n */\r\n lazy: <T extends BaseValidator>(thunk: () => T) =>\r\n new LazyValidator(thunk) as LazyValidator<T> & StandardSchemaV1<Infer<T>>,\r\n\r\n /** Create a string validator */\r\n string: (errorMessage?: string) =>\r\n new StringValidator(errorMessage) as StringValidator & StandardSchemaV1<string>,\r\n\r\n /** Create an email validator */\r\n email: (emailErrorMessage?: string, errorMessage?: string) =>\r\n new StringValidator(errorMessage).email(emailErrorMessage) as StringValidator &\r\n StandardSchemaV1<string>,\r\n\r\n /**\r\n * Create an enum validator — preserves the literal union of accepted\r\n * values in the inferred Standard Schema output.\r\n *\r\n * Two input shapes:\r\n * - Tuple of literals: `v.enum([\"draft\", \"published\"])` →\r\n * `StandardSchemaV1<\"draft\" | \"published\">`\r\n * - TypeScript enum object: `v.enum(Status)` →\r\n * `StandardSchemaV1<Status[keyof Status]>`\r\n *\r\n * Implementation is loosely typed; the public `ValidatorV.enum`\r\n * surface declares the precise overloads.\r\n */\r\n enum: ((values: any, errorMessage?: string) =>\r\n Array.isArray(values)\r\n ? new StringValidator().oneOf(values, errorMessage)\r\n : new ScalarValidator().enum(values, errorMessage)) as ValidatorV[\"enum\"],\r\n\r\n /** Create a number validator */\r\n number: (errorMessage?: string) =>\r\n new NumberValidator(errorMessage) as NumberValidator & StandardSchemaV1<number>,\r\n\r\n /** Create a numeric validator */\r\n numeric: (errorMessage?: string) =>\r\n new NumericValidator(errorMessage) as NumericValidator & StandardSchemaV1<number>,\r\n\r\n /** Create an integer validator */\r\n int: (errorMessage?: string) =>\r\n new IntValidator(errorMessage) as IntValidator & StandardSchemaV1<number>,\r\n\r\n /** Create a float validator */\r\n float: (errorMessage?: string) =>\r\n new FloatValidator(errorMessage) as FloatValidator & StandardSchemaV1<number>,\r\n\r\n /** Create a boolean validator */\r\n boolean: (errorMessage?: string) =>\r\n new BooleanValidator(errorMessage) as BooleanValidator & StandardSchemaV1<boolean>,\r\n\r\n /** Create a scalar validator */\r\n scalar: (errorMessage?: string) =>\r\n new ScalarValidator(errorMessage) as ScalarValidator &\r\n StandardSchemaV1<string | number | boolean>,\r\n\r\n /** Create a union validator - validates against multiple types */\r\n union: <T extends BaseValidator[]>(validators: T, errorMessage?: string) =>\r\n new UnionValidator().union(validators, errorMessage) as UnionValidator &\r\n StandardSchemaV1<Infer<T[number]>>,\r\n\r\n /**\r\n * Create a discriminated union — routes payloads by a shared literal\r\n * discriminator field. Each branch must be a `v.object(...)` with the\r\n * discriminator typed as `v.literal(...)`.\r\n *\r\n * @example\r\n * const email = v.object({ type: v.literal(\"email\"), email: v.string().email() });\r\n * const sms = v.object({ type: v.literal(\"sms\"), phone: v.string() });\r\n * const notif = v.discriminatedUnion(\"type\", [email, sms]);\r\n * // type T = Infer<typeof notif>;\r\n * // → { type: \"email\", email: string } | { type: \"sms\", phone: string }\r\n */\r\n discriminatedUnion: <\r\n K extends string,\r\n Branches extends ReadonlyArray<ObjectValidator<any>>,\r\n >(\r\n discriminator: K,\r\n validators: Branches,\r\n ) =>\r\n new DiscriminatedUnionValidator(discriminator, validators) as DiscriminatedUnionValidator<\r\n K,\r\n Branches\r\n > &\r\n StandardSchemaV1<Infer<Branches[number]>>,\r\n\r\n /** Create a computed field validator - derives value from other validated fields */\r\n computed: <TResult = any>(\r\n callback: (data: any, context: SchemaContext) => TResult | Promise<TResult>,\r\n resultValidator?: BaseValidator,\r\n ) =>\r\n new ComputedValidator<TResult>(callback, resultValidator) as ComputedValidator<TResult> &\r\n StandardSchemaV1<TResult>,\r\n\r\n /** Create a managed field validator - framework-injected value */\r\n managed: <TResult = any>(\r\n callback: (context: SchemaContext) => TResult | Promise<TResult>,\r\n resultValidator?: BaseValidator,\r\n ) =>\r\n new ManagedValidator<TResult>(callback, resultValidator) as ManagedValidator<TResult> &\r\n StandardSchemaV1<TResult>,\r\n\r\n /** Validate data against a schema */\r\n validate: validateFunction,\r\n} as unknown as ValidatorV;\r\n\r\nexport type ValidateOptions = {\r\n context?: Record<string, any>;\r\n} & SealConfig;\r\n\r\nexport interface ValidatorV {\r\n object: <T extends Schema>(\r\n schema: T,\r\n errorMessage?: string,\r\n ) => ObjectValidator<T> & StandardSchemaV1<Infer<ObjectValidator<T>>>;\r\n any: () => AnyValidator & StandardSchemaV1<any>;\r\n array: <T extends BaseValidator>(\r\n validator: T,\r\n errorMessage?: string,\r\n ) => ArrayValidator & {\r\n validator: T;\r\n } & StandardSchemaV1<Array<Infer<T>>>;\r\n record: <T extends BaseValidator>(\r\n validator?: T,\r\n errorMessage?: string,\r\n ) => RecordValidator & {\r\n valueValidator: T;\r\n } & StandardSchemaV1<Record<string, Infer<T>>>;\r\n tuple: <T extends BaseValidator[]>(\r\n validators: T,\r\n errorMessage?: string,\r\n ) => TupleValidator & {\r\n validators: T;\r\n } & StandardSchemaV1<{ [K in keyof T]: Infer<T[K]> }>;\r\n date: (errorMessage?: string) => DateValidator & StandardSchemaV1<Date>;\r\n literal: <T extends readonly [string | number | boolean, ...(string | number | boolean)[]]>(\r\n ...values: T\r\n ) => LiteralValidator<T> & StandardSchemaV1<T[number]>;\r\n instanceof: <T>(\r\n ctor: new (...args: any[]) => T,\r\n errorMessage?: string,\r\n ) => InstanceOfValidator<T> & StandardSchemaV1<T>;\r\n lazy: <T extends BaseValidator>(\r\n thunk: () => T,\r\n ) => LazyValidator<T> & StandardSchemaV1<Infer<T>>;\r\n string: (errorMessage?: string) => StringValidator & StandardSchemaV1<string>;\r\n email: (errorMessage?: string) => StringValidator & StandardSchemaV1<string>;\r\n enum: {\r\n <const T extends readonly (string | number | boolean)[]>(\r\n values: T,\r\n errorMessage?: string,\r\n ): ScalarValidator & StandardSchemaV1<T[number]>;\r\n <const T extends Record<string, string | number>>(\r\n values: T,\r\n errorMessage?: string,\r\n ): ScalarValidator & StandardSchemaV1<T[keyof T]>;\r\n };\r\n number: (errorMessage?: string) => NumberValidator & StandardSchemaV1<number>;\r\n numeric: (errorMessage?: string) => NumericValidator & StandardSchemaV1<number>;\r\n int: (errorMessage?: string) => IntValidator & StandardSchemaV1<number>;\r\n float: (errorMessage?: string) => FloatValidator & StandardSchemaV1<number>;\r\n boolean: (errorMessage?: string) => BooleanValidator & StandardSchemaV1<boolean>;\r\n scalar: (\r\n errorMessage?: string,\r\n ) => ScalarValidator & StandardSchemaV1<string | number | boolean>;\r\n union: <T extends BaseValidator[]>(\r\n validators: T,\r\n errorMessage?: string,\r\n ) => UnionValidator & StandardSchemaV1<Infer<T[number]>>;\r\n discriminatedUnion: <\r\n K extends string,\r\n Branches extends ReadonlyArray<ObjectValidator<any>>,\r\n >(\r\n discriminator: K,\r\n validators: Branches,\r\n ) => DiscriminatedUnionValidator<K, Branches> & StandardSchemaV1<Infer<Branches[number]>>;\r\n computed: <TResult = any>(\r\n callback: (data: any, context: SchemaContext) => TResult | Promise<TResult>,\r\n resultValidator?: BaseValidator,\r\n ) => ComputedValidator<TResult> & StandardSchemaV1<TResult>;\r\n managed: <TResult = any>(\r\n callback?: (context: SchemaContext) => TResult | Promise<TResult>,\r\n resultValidator?: BaseValidator,\r\n ) => ManagedValidator<TResult> & StandardSchemaV1<TResult>;\r\n validate: <T extends BaseValidator>(\r\n schema: T,\r\n data: any,\r\n options?: ValidateOptions,\r\n ) => Promise<ValidationResult>;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,IAAgB;;CAE3B,SAA2B,QAAW,iBACpC,IAAI,gBAAmB,QAAQ,YAAY;;CAI7C,WAAW,IAAI,aAAa;;CAG5B,QAAiC,WAAc,iBAC7C,IAAI,eAAe,WAAW,YAAY;;CAK5C,SAAkC,WAAe,iBAC/C,IAAI,gBAAgB,aAAa,EAAE,IAAI,GAAG,YAAY;;CAKxD,QAAmC,YAAe,iBAChD,IAAI,eAAe,YAAY,YAAY;;CAK7C,OAAO,iBACL,IAAI,cAAc,YAAY;;;;;;;;;CAUhC,UACE,GAAG,WAEH,IAAI,iBAAoB,MAAM;;;;;;;;;CAUhC,aAAgB,MAAiC,iBAC/C,IAAI,oBAAuB,MAAM,YAAY;;;;;;;;;;;;;CAe/C,OAAgC,UAC9B,IAAI,cAAc,KAAK;;CAGzB,SAAS,iBACP,IAAI,gBAAgB,YAAY;;CAGlC,QAAQ,mBAA4B,iBAClC,IAAI,gBAAgB,YAAY,CAAC,CAAC,MAAM,iBAAiB;;;;;;;;;;;;;;CAgB3D,QAAQ,QAAa,iBACnB,MAAM,QAAQ,MAAM,IAChB,IAAI,gBAAgB,CAAC,CAAC,MAAM,QAAQ,YAAY,IAChD,IAAI,gBAAgB,CAAC,CAAC,KAAK,QAAQ,YAAY;;CAGrD,SAAS,iBACP,IAAI,gBAAgB,YAAY;;CAGlC,UAAU,iBACR,IAAI,iBAAiB,YAAY;;CAGnC,MAAM,iBACJ,IAAI,aAAa,YAAY;;CAG/B,QAAQ,iBACN,IAAI,eAAe,YAAY;;CAGjC,UAAU,iBACR,IAAI,iBAAiB,YAAY;;CAGnC,SAAS,iBACP,IAAI,gBAAgB,YAAY;;CAIlC,QAAmC,YAAe,iBAChD,IAAI,eAAe,CAAC,CAAC,MAAM,YAAY,YAAY;;;;;;;;;;;;;CAerD,qBAIE,eACA,eAEA,IAAI,4BAA4B,eAAe,UAAU;;CAO3D,WACE,UACA,oBAEA,IAAI,kBAA2B,UAAU,eAAe;;CAI1D,UACE,UACA,oBAEA,IAAI,iBAA0B,UAAU,eAAe;;CAI/CA;AACZ"}
|
|
@@ -47,13 +47,19 @@ const invalidRule = (rule, context) => {
|
|
|
47
47
|
rule,
|
|
48
48
|
context
|
|
49
49
|
})]));
|
|
50
|
+
const input = resolveAttribute({
|
|
51
|
+
key: "input",
|
|
52
|
+
rawValue: translatableWithInput.input ?? "schema",
|
|
53
|
+
rule,
|
|
54
|
+
context
|
|
55
|
+
});
|
|
50
56
|
const attributes = {
|
|
51
57
|
path: context.path,
|
|
52
58
|
key: context.key,
|
|
53
59
|
value: context.value,
|
|
54
60
|
...rule.context.translationParams,
|
|
55
61
|
...resolvedParams,
|
|
56
|
-
input
|
|
62
|
+
input
|
|
57
63
|
};
|
|
58
64
|
return {
|
|
59
65
|
isValid: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-helpers.mjs","names":[],"sources":["../../../../../../../seal/src/helpers/validation-helpers.ts"],"sourcesContent":["import { getSealConfig } from \"../config\";\nimport type { ContextualSchemaRule, RuleResult, RuleTranslation, SchemaContext } from \"../types\";\n\nexport const VALID_RULE: RuleResult = {\n isValid: true,\n};\n/**\n * Resolve a single attribute value through the full translation priority chain:\n * 1. attributesList[key] — developer direct text override (highest priority)\n * 2. translatedAttributes[key] — developer explicit translation key\n * 3. translator(rawValue) — auto-translate the raw value (fallback)\n *\n * Use this in rule bodies when you need per-item translation\n * (e.g. translating each enum value before joining them).\n *\n * @example\n * // Translate each enum value individually then join\n * const enumList = enumValues\n * .map(v => resolveTranslation(String(v), String(v), this, context))\n * .join(\", \");\n * this.context.translationParams.enumList = enumList;\n */\nexport const resolveTranslation = ({\n key,\n rawValue,\n rule,\n context,\n}: {\n key: string;\n rawValue: any;\n rule: ContextualSchemaRule;\n context: SchemaContext;\n}): string => {\n const translator = getSealConfig().translateAttribute;\n\n // 1. Direct text override wins\n const direct = rule.context.attributesList?.[key];\n if (direct && typeof direct === \"string\") return direct;\n\n if (!translator) return String(rawValue ?? key);\n\n // 2. Explicit translation key\n const transKey = rule.context.translatedAttributes?.[key];\n if (transKey) return translator({ attribute: transKey, context, rule });\n\n // 3. Auto-translate the raw value (fallback)\n return translator({ attribute: String(rawValue ?? key), context, rule });\n};\n\n// Internal alias — invalidRule uses the same function without re-importing config\nconst resolveAttribute = resolveTranslation;\n\nexport const invalidRule = (rule: ContextualSchemaRule, context: SchemaContext): RuleResult => {\n // `input` is always translatable — rules may add more (e.g., field references in sameAs)\n // Rule-defined translatableParams override the default input if the key matches\n const translatableWithInput: Record<string, string> = {\n // Fall back to \"schema\" when validating at the root level (no key)\n input: context.key || \"schema\",\n ...rule.context.translatableParams,\n };\n\n // Resolve all translatable params through the full priority chain\n const resolvedParams = Object.fromEntries(\n Object.entries(translatableWithInput).map(([key, rawValue]) => [\n key,\n resolveAttribute({ key, rawValue, rule, context }),\n ]),\n );\n\n const attributes: RuleTranslation[\"attributes\"] = {\n path: context.path,\n key: context.key,\n value: context.value,\n // Raw placeholders (:enumList, :min, :max, etc.) — no translation\n ...rule.context.translationParams,\n // Translated placeholders (:input, :field, etc.) — override raws if key collides\n ...resolvedParams,\n // Satisfy TypeScript's required field (always present via resolvedParams)\n input
|
|
1
|
+
{"version":3,"file":"validation-helpers.mjs","names":[],"sources":["../../../../../../../seal/src/helpers/validation-helpers.ts"],"sourcesContent":["import { getSealConfig } from \"../config\";\nimport type { ContextualSchemaRule, RuleResult, RuleTranslation, SchemaContext } from \"../types\";\n\nexport const VALID_RULE: RuleResult = {\n isValid: true,\n};\n/**\n * Resolve a single attribute value through the full translation priority chain:\n * 1. attributesList[key] — developer direct text override (highest priority)\n * 2. translatedAttributes[key] — developer explicit translation key\n * 3. translator(rawValue) — auto-translate the raw value (fallback)\n *\n * Use this in rule bodies when you need per-item translation\n * (e.g. translating each enum value before joining them).\n *\n * @example\n * // Translate each enum value individually then join\n * const enumList = enumValues\n * .map(v => resolveTranslation(String(v), String(v), this, context))\n * .join(\", \");\n * this.context.translationParams.enumList = enumList;\n */\nexport const resolveTranslation = ({\n key,\n rawValue,\n rule,\n context,\n}: {\n key: string;\n rawValue: any;\n rule: ContextualSchemaRule;\n context: SchemaContext;\n}): string => {\n const translator = getSealConfig().translateAttribute;\n\n // 1. Direct text override wins\n const direct = rule.context.attributesList?.[key];\n if (direct && typeof direct === \"string\") return direct;\n\n if (!translator) return String(rawValue ?? key);\n\n // 2. Explicit translation key\n const transKey = rule.context.translatedAttributes?.[key];\n if (transKey) return translator({ attribute: transKey, context, rule });\n\n // 3. Auto-translate the raw value (fallback)\n return translator({ attribute: String(rawValue ?? key), context, rule });\n};\n\n// Internal alias — invalidRule uses the same function without re-importing config\nconst resolveAttribute = resolveTranslation;\n\nexport const invalidRule = (rule: ContextualSchemaRule, context: SchemaContext): RuleResult => {\n // `input` is always translatable — rules may add more (e.g., field references in sameAs)\n // Rule-defined translatableParams override the default input if the key matches\n const translatableWithInput: Record<string, string> = {\n // Fall back to \"schema\" when validating at the root level (no key)\n input: context.key || \"schema\",\n ...rule.context.translatableParams,\n };\n\n // Resolve all translatable params through the full priority chain\n const resolvedParams = Object.fromEntries(\n Object.entries(translatableWithInput).map(([key, rawValue]) => [\n key,\n resolveAttribute({ key, rawValue, rule, context }),\n ]),\n );\n const input = resolveAttribute({\n key: \"input\",\n rawValue: translatableWithInput.input ?? \"schema\",\n rule,\n context,\n });\n\n const attributes: RuleTranslation[\"attributes\"] = {\n path: context.path,\n key: context.key,\n value: context.value,\n // Raw placeholders (:enumList, :min, :max, etc.) — no translation\n ...rule.context.translationParams,\n // Translated placeholders (:input, :field, etc.) — override raws if key collides\n ...resolvedParams,\n // Satisfy TypeScript's required field (always present via resolvedParams)\n input,\n };\n\n const rawError =\n rule.context.errorMessage ||\n rule.errorMessage ||\n context.translateRule?.({ rule, context, attributes }) ||\n rule.defaultErrorMessage!;\n\n // Fallback interpolation: replace :placeholder patterns from attributes\n // This kicks in when translateRule is absent or returns \"\" (not configured)\n const error = rawError.replace(/:([a-zA-Z_]+)/g, (match, key) =>\n key in attributes ? String(attributes[key as keyof typeof attributes]) : match,\n );\n\n return {\n isValid: false,\n error,\n input: attributes.input, // use resolved input, not raw context.key (may be \"\")\n path: context.path,\n };\n};\n"],"mappings":";;;AAGA,MAAa,aAAyB,EACpC,SAAS,KACX;;;;;;;;;;;;;;;;;AAiBA,MAAa,sBAAsB,EACjC,KACA,UACA,MACA,cAMY;CACZ,MAAM,aAAa,cAAc,CAAC,CAAC;CAGnC,MAAM,SAAS,KAAK,QAAQ,iBAAiB;CAC7C,IAAI,UAAU,OAAO,WAAW,UAAU,OAAO;CAEjD,IAAI,CAAC,YAAY,OAAO,OAAO,YAAY,GAAG;CAG9C,MAAM,WAAW,KAAK,QAAQ,uBAAuB;CACrD,IAAI,UAAU,OAAO,WAAW;EAAE,WAAW;EAAU;EAAS;CAAK,CAAC;CAGtE,OAAO,WAAW;EAAE,WAAW,OAAO,YAAY,GAAG;EAAG;EAAS;CAAK,CAAC;AACzE;AAGA,MAAM,mBAAmB;AAEzB,MAAa,eAAe,MAA4B,YAAuC;CAG7F,MAAM,wBAAgD;EAEpD,OAAO,QAAQ,OAAO;EACtB,GAAG,KAAK,QAAQ;CAClB;CAGA,MAAM,iBAAiB,OAAO,YAC5B,OAAO,QAAQ,qBAAqB,CAAC,CAAC,KAAK,CAAC,KAAK,cAAc,CAC7D,KACA,iBAAiB;EAAE;EAAK;EAAU;EAAM;CAAQ,CAAC,CACnD,CAAC,CACH;CACA,MAAM,QAAQ,iBAAiB;EAC7B,KAAK;EACL,UAAU,sBAAsB,SAAS;EACzC;EACA;CACF,CAAC;CAED,MAAM,aAA4C;EAChD,MAAM,QAAQ;EACd,KAAK,QAAQ;EACb,OAAO,QAAQ;EAEf,GAAG,KAAK,QAAQ;EAEhB,GAAG;EAEH;CACF;CAcA,OAAO;EACL,SAAS;EACT,QAbA,KAAK,QAAQ,gBACb,KAAK,gBACL,QAAQ,gBAAgB;GAAE;GAAM;GAAS;EAAW,CAAC,KACrD,KAAK,oBAIe,CAAC,QAAQ,mBAAmB,OAAO,QACvD,OAAO,aAAa,OAAO,WAAW,IAA+B,IAAI,KAKrE;EACJ,OAAO,WAAW;EAClB,MAAM,QAAQ;CAChB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"date-period-rules.d.mts","names":[],"sources":["../../../../../../../../seal/src/rules/date/date-period-rules.ts"],"mappings":";;;cAIM,MAAA;;;;;;;;;;;;;;KAeM,KAAA,gBAAqB,MAAM;;;;cAK1B,SAAA,EAAW,UAAU;EAAG,KAAA,EAAO,KAAA;AAAA;;;;cAoB/B,QAAA,EAAU,UAAU;EAAG,IAAI;AAAA;;;;;cAoB3B,gBAAA,EAAkB,UAAU;EACvC,SAAA;EACA,OAAA;EACA,KAAA;AAAA;;;AAvBsC;AAoBxC;cA8Ea,iBAAA,EAAmB,UAAA;EAC9B,UAAA,EAAY,KAAA;EACZ,QAAA,EAAU,KAAA;EACV,KAAA;AAAA;;;;AA9EK;cA6JM,eAAA,EAAiB,UAAU;EACtC,QAAA;EACA,MAAA;EACA,KAAA;AAAA;;;;cA0EW,WAAA,EAAa,UAAU;EAAG,OAAO;AAAA;;;;cAoBjC,gBAAA,EAAkB,UAAU;EACvC,SAAA;EACA,OAAA;AAAA;;;;;;
|
|
1
|
+
{"version":3,"file":"date-period-rules.d.mts","names":[],"sources":["../../../../../../../../seal/src/rules/date/date-period-rules.ts"],"mappings":";;;cAIM,MAAA;;;;;;;;;;;;;;KAeM,KAAA,gBAAqB,MAAM;;;;cAK1B,SAAA,EAAW,UAAU;EAAG,KAAA,EAAO,KAAA;AAAA;;;;cAoB/B,QAAA,EAAU,UAAU;EAAG,IAAI;AAAA;;;;;cAoB3B,gBAAA,EAAkB,UAAU;EACvC,SAAA;EACA,OAAA;EACA,KAAA;AAAA;;;AAvBsC;AAoBxC;cA8Ea,iBAAA,EAAmB,UAAA;EAC9B,UAAA,EAAY,KAAA;EACZ,QAAA,EAAU,KAAA;EACV,KAAA;AAAA;;;;AA9EK;cA6JM,eAAA,EAAiB,UAAU;EACtC,QAAA;EACA,MAAA;EACA,KAAA;AAAA;;;;cA0EW,WAAA,EAAa,UAAU;EAAG,OAAO;AAAA;;;;cAoBjC,gBAAA,EAAkB,UAAU;EACvC,SAAA;EACA,OAAA;AAAA;;;;;;cAyCW,WAAA,EAAa,UAAU;EAClC,WAAA;EACA,KAAA;AAAA;;;;AAjE4C;AAoB9C;cAmGa,WAAA,EAAa,UAAU;EAClC,WAAA;EACA,KAAA;AAAA;;;;AAnGO;AAyCT;cAgHa,YAAA,EAAc,UAAU;EACnC,YAAA;EACA,KAAA;AAAA;;;;AAhHK;AAsDP;cA+Ga,YAAA,EAAc,UAAU;EACnC,YAAA,EAAc,KAAA;EACd,KAAA;AAAA;;;;AA/GK;AAsDP;cA+Ga,UAAA,EAAY,UAAU;EACjC,UAAA;EACA,KAAA;AAAA;;;;AA/GK;AAqDP;cA+Ga,UAAA,EAAY,UAAU;EACjC,UAAA;EACA,KAAA;AAAA"}
|
|
@@ -197,8 +197,10 @@ const betweenTimesRule = {
|
|
|
197
197
|
const inputTimeInMinutes = inputHour * 60 + inputMinute;
|
|
198
198
|
const { startTime, endTime } = this.context.options;
|
|
199
199
|
const [startHour, startMinute] = startTime.split(":").map(Number);
|
|
200
|
+
if (startHour === void 0 || startMinute === void 0) return invalidRule(this, context);
|
|
200
201
|
const startTimeInMinutes = startHour * 60 + startMinute;
|
|
201
202
|
const [endHour, endMinute] = endTime.split(":").map(Number);
|
|
203
|
+
if (endHour === void 0 || endMinute === void 0) return invalidRule(this, context);
|
|
202
204
|
const endTimeInMinutes = endHour * 60 + endMinute;
|
|
203
205
|
if (inputTimeInMinutes >= startTimeInMinutes && inputTimeInMinutes <= endTimeInMinutes) return VALID_RULE;
|
|
204
206
|
this.context.translationParams.startTime = startTime;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"date-period-rules.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/date/date-period-rules.ts"],"sourcesContent":["import { get } from \"@mongez/reinforcements\";\r\nimport { invalidRule, VALID_RULE } from \"../../helpers\";\r\nimport type { SchemaRule } from \"../../types\";\r\n\r\nconst MONTHS = {\r\n 1: \"january\",\r\n 2: \"february\",\r\n 3: \"march\",\r\n 4: \"april\",\r\n 5: \"may\",\r\n 6: \"june\",\r\n 7: \"july\",\r\n 8: \"august\",\r\n 9: \"september\",\r\n 10: \"october\",\r\n 11: \"november\",\r\n 12: \"december\",\r\n};\r\n\r\nexport type Month = keyof typeof MONTHS;\r\n\r\n/**\r\n * Month rule - date must be in specific month (1-12)\r\n */\r\nexport const monthRule: SchemaRule<{ month: Month }> = {\r\n name: \"month\",\r\n defaultErrorMessage: \"The :input must be in month :month\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const month = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n if (month === this.context.options.month) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.month =\r\n MONTHS[this.context.options.month as keyof typeof MONTHS];\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Year rule - date must be in specific year\r\n */\r\nexport const yearRule: SchemaRule<{ year: number }> = {\r\n name: \"year\",\r\n defaultErrorMessage: \"The :input must be in year :year\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const year = inputDate.getFullYear();\r\n\r\n if (year === this.context.options.year) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.year = this.context.options.year;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between years rule - date must be between start and end years\r\n * Supports field names with sibling scope\r\n */\r\nexport const betweenYearsRule: SchemaRule<{\r\n startYear: number | string;\r\n endYear: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"betweenYears\",\r\n defaultErrorMessage: \"The :input must be between :startYear and :endYear\",\r\n async validate(value: Date, context) {\r\n const { startYear, endYear, scope = \"global\" } = this.context.options;\r\n const inputDate = new Date(value);\r\n const inputYear = inputDate.getFullYear();\r\n\r\n // Extract start year\r\n let compareStartYear: number;\r\n if (typeof startYear === \"number\") {\r\n compareStartYear = startYear;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, startYear);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareStartYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareStartYear = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareStartYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n // Extract end year\r\n let compareEndYear: number;\r\n if (typeof endYear === \"number\") {\r\n compareEndYear = endYear;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, endYear);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareEndYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareEndYear = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareEndYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n if (inputYear >= compareStartYear && inputYear <= compareEndYear) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.startYear = compareStartYear;\r\n this.context.translationParams.endYear = compareEndYear;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between months rule - date must be between start and end months (1-12)\r\n * Supports field names with sibling scope\r\n */\r\nexport const betweenMonthsRule: SchemaRule<{\r\n startMonth: Month | string;\r\n endMonth: Month | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"betweenMonths\",\r\n defaultErrorMessage: \"The :input must be between month :startMonth and :endMonth\",\r\n async validate(value: Date, context) {\r\n const { startMonth, endMonth, scope = \"global\" } = this.context.options;\r\n const inputDate = new Date(value);\r\n const inputMonth = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n // Extract start month\r\n let compareStartMonth: number;\r\n if (typeof startMonth === \"number\") {\r\n compareStartMonth = startMonth;\r\n this.context.translatableParams.startMonth = MONTHS[compareStartMonth as keyof typeof MONTHS];\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, startMonth);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.startMonth = startMonth;\r\n\r\n if (fieldValue instanceof Date) {\r\n compareStartMonth = fieldValue.getMonth() + 1;\r\n } else if (typeof fieldValue === \"number\") {\r\n compareStartMonth = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareStartMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n // Extract end month\r\n let compareEndMonth: number;\r\n if (typeof endMonth === \"number\") {\r\n compareEndMonth = endMonth;\r\n this.context.translatableParams.endMonth = MONTHS[compareEndMonth as keyof typeof MONTHS];\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, endMonth);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.endMonth = endMonth;\r\n\r\n if (fieldValue instanceof Date) {\r\n compareEndMonth = fieldValue.getMonth() + 1;\r\n } else if (typeof fieldValue === \"number\") {\r\n compareEndMonth = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareEndMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n if (inputMonth >= compareStartMonth && inputMonth <= compareEndMonth) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between days rule - date must be between start and end days (1-31)\r\n * Supports field names with sibling scope\r\n */\r\nexport const betweenDaysRule: SchemaRule<{\r\n startDay: number | string;\r\n endDay: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"betweenDays\",\r\n defaultErrorMessage: \"The :input must be between day :startDay and :endDay\",\r\n async validate(value: Date, context) {\r\n const { startDay, endDay, scope = \"global\" } = this.context.options;\r\n const inputDate = new Date(value);\r\n const inputDay = inputDate.getDate();\r\n\r\n // Extract start day\r\n let compareStartDay: number;\r\n if (typeof startDay === \"number\") {\r\n compareStartDay = startDay;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, startDay);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareStartDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareStartDay = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareStartDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n // Extract end day\r\n let compareEndDay: number;\r\n if (typeof endDay === \"number\") {\r\n compareEndDay = endDay;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, endDay);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareEndDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareEndDay = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareEndDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n if (inputDay >= compareStartDay && inputDay <= compareEndDay) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.startDay = compareStartDay;\r\n this.context.translationParams.endDay = compareEndDay;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Quarter rule - date must be in specific quarter (1-4)\r\n */\r\nexport const quarterRule: SchemaRule<{ quarter: 1 | 2 | 3 | 4 }> = {\r\n name: \"quarter\",\r\n defaultErrorMessage: \"The :input must be in quarter :quarter\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const month = inputDate.getMonth() + 1;\r\n const quarter = Math.ceil(month / 3);\r\n\r\n if (quarter === this.context.options.quarter) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.quarter = this.context.options.quarter;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between times rule - time must be between start and end times (HH:MM format)\r\n */\r\nexport const betweenTimesRule: SchemaRule<{\r\n startTime: string;\r\n endTime: string;\r\n}> = {\r\n name: \"betweenTimes\",\r\n defaultErrorMessage: \"The :input must be between :startTime and :endTime\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const inputHour = inputDate.getHours();\r\n const inputMinute = inputDate.getMinutes();\r\n const inputTimeInMinutes = inputHour * 60 + inputMinute;\r\n\r\n const { startTime, endTime } = this.context.options;\r\n\r\n // Parse start time\r\n const [startHour, startMinute] = startTime.split(\":\").map(Number);\r\n const startTimeInMinutes = startHour * 60 + startMinute;\r\n\r\n // Parse end time\r\n const [endHour, endMinute] = endTime.split(\":\").map(Number);\r\n const endTimeInMinutes = endHour * 60 + endMinute;\r\n\r\n if (inputTimeInMinutes >= startTimeInMinutes && inputTimeInMinutes <= endTimeInMinutes) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.startTime = startTime;\r\n this.context.translationParams.endTime = endTime;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Min year rule - year must be >= given year or field\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const minYearRule: SchemaRule<{\r\n yearOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"minYear\",\r\n description: \"The date year must be at least the given year or field\",\r\n defaultErrorMessage: \"The :input year must be higher than :yearOrField\",\r\n async validate(value: Date, context) {\r\n const { yearOrField, scope = \"global\" } = this.context.options;\r\n let compareYear: number;\r\n\r\n if (typeof yearOrField === \"number\") {\r\n compareYear = yearOrField;\r\n this.context.translationParams.yearOrField = yearOrField;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, yearOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.yearOrField = yearOrField;\r\n\r\n // If field contains a date, extract the year\r\n if (fieldValue instanceof Date) {\r\n compareYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareYear = fieldValue;\r\n } else {\r\n // Try to parse as date and extract year\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputYear = inputDate.getFullYear();\r\n\r\n if (inputYear >= compareYear) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Max year rule - year must be <= given year or field\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const maxYearRule: SchemaRule<{\r\n yearOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"maxYear\",\r\n description: \"The date year must be at most the given year or field\",\r\n defaultErrorMessage: \"The :input year must be at most :yearOrField\",\r\n async validate(value: Date, context) {\r\n const { yearOrField, scope = \"global\" } = this.context.options;\r\n let compareYear: number;\r\n\r\n if (typeof yearOrField === \"number\") {\r\n compareYear = yearOrField;\r\n this.context.translationParams.yearOrField = compareYear;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, yearOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.yearOrField = yearOrField;\r\n\r\n // If field contains a date, extract the year\r\n if (fieldValue instanceof Date) {\r\n compareYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareYear = fieldValue;\r\n } else {\r\n // Try to parse as date and extract year\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputYear = inputDate.getFullYear();\r\n\r\n if (inputYear <= compareYear) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Min month rule - month must be >= given month or field (1-12)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const minMonthRule: SchemaRule<{\r\n monthOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"minMonth\",\r\n description: \"The date month must be at least the given month or field\",\r\n defaultErrorMessage: \"The :input month must be at least :monthOrField\",\r\n async validate(value: Date, context) {\r\n const { monthOrField, scope = \"global\" } = this.context.options;\r\n let compareMonth: number;\r\n\r\n if (typeof monthOrField === \"number\") {\r\n compareMonth = monthOrField;\r\n this.context.translationParams.monthOrField = compareMonth;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, monthOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.monthOrField = monthOrField;\r\n\r\n // If field contains a date, extract the month\r\n if (fieldValue instanceof Date) {\r\n compareMonth = fieldValue.getMonth() + 1; // getMonth() returns 0-11\r\n } else if (typeof fieldValue === \"number\") {\r\n compareMonth = fieldValue;\r\n } else {\r\n // Try to parse as date and extract month\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputMonth = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n if (inputMonth >= compareMonth) {\r\n return VALID_RULE;\r\n }\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Max month rule - month must be <= given month or field (1-12)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const maxMonthRule: SchemaRule<{\r\n monthOrField: Month | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"maxMonth\",\r\n description: \"The date month must be at most the given month or field\",\r\n defaultErrorMessage: \"The :input month must be at most :monthOrField\",\r\n async validate(value: Date, context) {\r\n const { monthOrField, scope = \"global\" } = this.context.options;\r\n let compareMonth: number;\r\n\r\n if (typeof monthOrField === \"number\") {\r\n compareMonth = monthOrField;\r\n this.context.translatableParams.monthOrField = MONTHS[monthOrField];\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, monthOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.monthOrField = monthOrField;\r\n\r\n // If field contains a date, extract the month\r\n if (fieldValue instanceof Date) {\r\n compareMonth = fieldValue.getMonth() + 1; // getMonth() returns 0-11\r\n } else if (typeof fieldValue === \"number\") {\r\n compareMonth = fieldValue;\r\n } else {\r\n // Try to parse as date and extract month\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputMonth = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n if (inputMonth <= compareMonth) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Min day rule - day must be >= given day or field (1-31)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const minDayRule: SchemaRule<{\r\n dayOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"minDay\",\r\n description: \"The date day must be at least the given day or field\",\r\n defaultErrorMessage: \"The :input day must be higher than :dayOrField\",\r\n async validate(value: Date, context) {\r\n const { dayOrField, scope = \"global\" } = this.context.options;\r\n let compareDay: number;\r\n\r\n if (typeof dayOrField === \"number\") {\r\n compareDay = dayOrField;\r\n this.context.translationParams.dayOrField = dayOrField;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, dayOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.dayOrField = dayOrField;\r\n\r\n // If field contains a date, extract the day\r\n if (fieldValue instanceof Date) {\r\n compareDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareDay = fieldValue;\r\n } else {\r\n // Try to parse as date and extract day\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputDay = inputDate.getDate();\r\n\r\n if (inputDay >= compareDay) {\r\n return VALID_RULE;\r\n }\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Max day rule - day must be <= given day or field (1-31)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const maxDayRule: SchemaRule<{\r\n dayOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"maxDay\",\r\n description: \"The date day must be at most the given day or field\",\r\n defaultErrorMessage: \"The :input day must be at most :dayOrField\",\r\n async validate(value: Date, context) {\r\n const { dayOrField, scope = \"global\" } = this.context.options;\r\n let compareDay: number;\r\n\r\n if (typeof dayOrField === \"number\") {\r\n compareDay = dayOrField;\r\n this.context.translationParams.dayOrField = dayOrField;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, dayOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.dayOrField = dayOrField;\r\n\r\n // If field contains a date, extract the day\r\n if (fieldValue instanceof Date) {\r\n compareDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareDay = fieldValue;\r\n } else {\r\n // Try to parse as date and extract day\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputDay = inputDate.getDate();\r\n\r\n if (inputDay <= compareDay) {\r\n return VALID_RULE;\r\n }\r\n return invalidRule(this, context);\r\n },\r\n};\r\n"],"mappings":";;;;;AAIA,MAAM,SAAS;CACb,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;;;;AAOA,MAAa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;GACb,KAAK,QAAQ,kBAAkB,aAAa;EAC9C,OAAO;GAEL,MAAM,aAAa,IADJ,UAAU,YAAY,QAAQ,SAAS,QAAQ,WAC/B,UAAU;GAEzC,IAAI,eAAe,QACjB,OAAO;GAGT,KAAK,QAAQ,mBAAmB,aAAa;GAG7C,IAAI,sBAAsB,MACxB,aAAa,WAAW,QAAQ;QAC3B,IAAI,OAAO,eAAe,UAC/B,aAAa;QACR;IAEL,MAAM,OAAO,IAAI,KAAK,UAAU;IAChC,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,GACvB,aAAa,KAAK,QAAQ;SAE1B,OAAO;GAEX;EACF;EAKA,IAFiB,IADK,KAAK,KACF,CAAC,CAAC,QAEhB,KAAK,YACd,OAAO;EAET,OAAO,YAAY,MAAM,OAAO;CAClC;AACF"}
|
|
1
|
+
{"version":3,"file":"date-period-rules.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/date/date-period-rules.ts"],"sourcesContent":["import { get } from \"@mongez/reinforcements\";\r\nimport { invalidRule, VALID_RULE } from \"../../helpers\";\r\nimport type { SchemaRule } from \"../../types\";\r\n\r\nconst MONTHS = {\r\n 1: \"january\",\r\n 2: \"february\",\r\n 3: \"march\",\r\n 4: \"april\",\r\n 5: \"may\",\r\n 6: \"june\",\r\n 7: \"july\",\r\n 8: \"august\",\r\n 9: \"september\",\r\n 10: \"october\",\r\n 11: \"november\",\r\n 12: \"december\",\r\n};\r\n\r\nexport type Month = keyof typeof MONTHS;\r\n\r\n/**\r\n * Month rule - date must be in specific month (1-12)\r\n */\r\nexport const monthRule: SchemaRule<{ month: Month }> = {\r\n name: \"month\",\r\n defaultErrorMessage: \"The :input must be in month :month\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const month = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n if (month === this.context.options.month) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.month =\r\n MONTHS[this.context.options.month as keyof typeof MONTHS];\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Year rule - date must be in specific year\r\n */\r\nexport const yearRule: SchemaRule<{ year: number }> = {\r\n name: \"year\",\r\n defaultErrorMessage: \"The :input must be in year :year\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const year = inputDate.getFullYear();\r\n\r\n if (year === this.context.options.year) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.year = this.context.options.year;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between years rule - date must be between start and end years\r\n * Supports field names with sibling scope\r\n */\r\nexport const betweenYearsRule: SchemaRule<{\r\n startYear: number | string;\r\n endYear: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"betweenYears\",\r\n defaultErrorMessage: \"The :input must be between :startYear and :endYear\",\r\n async validate(value: Date, context) {\r\n const { startYear, endYear, scope = \"global\" } = this.context.options;\r\n const inputDate = new Date(value);\r\n const inputYear = inputDate.getFullYear();\r\n\r\n // Extract start year\r\n let compareStartYear: number;\r\n if (typeof startYear === \"number\") {\r\n compareStartYear = startYear;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, startYear);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareStartYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareStartYear = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareStartYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n // Extract end year\r\n let compareEndYear: number;\r\n if (typeof endYear === \"number\") {\r\n compareEndYear = endYear;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, endYear);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareEndYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareEndYear = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareEndYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n if (inputYear >= compareStartYear && inputYear <= compareEndYear) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.startYear = compareStartYear;\r\n this.context.translationParams.endYear = compareEndYear;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between months rule - date must be between start and end months (1-12)\r\n * Supports field names with sibling scope\r\n */\r\nexport const betweenMonthsRule: SchemaRule<{\r\n startMonth: Month | string;\r\n endMonth: Month | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"betweenMonths\",\r\n defaultErrorMessage: \"The :input must be between month :startMonth and :endMonth\",\r\n async validate(value: Date, context) {\r\n const { startMonth, endMonth, scope = \"global\" } = this.context.options;\r\n const inputDate = new Date(value);\r\n const inputMonth = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n // Extract start month\r\n let compareStartMonth: number;\r\n if (typeof startMonth === \"number\") {\r\n compareStartMonth = startMonth;\r\n this.context.translatableParams.startMonth = MONTHS[compareStartMonth as keyof typeof MONTHS];\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, startMonth);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.startMonth = startMonth;\r\n\r\n if (fieldValue instanceof Date) {\r\n compareStartMonth = fieldValue.getMonth() + 1;\r\n } else if (typeof fieldValue === \"number\") {\r\n compareStartMonth = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareStartMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n // Extract end month\r\n let compareEndMonth: number;\r\n if (typeof endMonth === \"number\") {\r\n compareEndMonth = endMonth;\r\n this.context.translatableParams.endMonth = MONTHS[compareEndMonth as keyof typeof MONTHS];\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, endMonth);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.endMonth = endMonth;\r\n\r\n if (fieldValue instanceof Date) {\r\n compareEndMonth = fieldValue.getMonth() + 1;\r\n } else if (typeof fieldValue === \"number\") {\r\n compareEndMonth = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareEndMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n if (inputMonth >= compareStartMonth && inputMonth <= compareEndMonth) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between days rule - date must be between start and end days (1-31)\r\n * Supports field names with sibling scope\r\n */\r\nexport const betweenDaysRule: SchemaRule<{\r\n startDay: number | string;\r\n endDay: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"betweenDays\",\r\n defaultErrorMessage: \"The :input must be between day :startDay and :endDay\",\r\n async validate(value: Date, context) {\r\n const { startDay, endDay, scope = \"global\" } = this.context.options;\r\n const inputDate = new Date(value);\r\n const inputDay = inputDate.getDate();\r\n\r\n // Extract start day\r\n let compareStartDay: number;\r\n if (typeof startDay === \"number\") {\r\n compareStartDay = startDay;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, startDay);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareStartDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareStartDay = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareStartDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n // Extract end day\r\n let compareEndDay: number;\r\n if (typeof endDay === \"number\") {\r\n compareEndDay = endDay;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, endDay);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n if (fieldValue instanceof Date) {\r\n compareEndDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareEndDay = fieldValue;\r\n } else {\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareEndDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n if (inputDay >= compareStartDay && inputDay <= compareEndDay) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.startDay = compareStartDay;\r\n this.context.translationParams.endDay = compareEndDay;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Quarter rule - date must be in specific quarter (1-4)\r\n */\r\nexport const quarterRule: SchemaRule<{ quarter: 1 | 2 | 3 | 4 }> = {\r\n name: \"quarter\",\r\n defaultErrorMessage: \"The :input must be in quarter :quarter\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const month = inputDate.getMonth() + 1;\r\n const quarter = Math.ceil(month / 3);\r\n\r\n if (quarter === this.context.options.quarter) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.quarter = this.context.options.quarter;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Between times rule - time must be between start and end times (HH:MM format)\r\n */\r\nexport const betweenTimesRule: SchemaRule<{\r\n startTime: string;\r\n endTime: string;\r\n}> = {\r\n name: \"betweenTimes\",\r\n defaultErrorMessage: \"The :input must be between :startTime and :endTime\",\r\n async validate(value: Date, context) {\r\n const inputDate = new Date(value);\r\n const inputHour = inputDate.getHours();\r\n const inputMinute = inputDate.getMinutes();\r\n const inputTimeInMinutes = inputHour * 60 + inputMinute;\r\n\r\n const { startTime, endTime } = this.context.options;\r\n\r\n // Parse start time\r\n const [startHour, startMinute] = startTime.split(\":\").map(Number);\n if (startHour === undefined || startMinute === undefined) {\n return invalidRule(this, context);\n }\n const startTimeInMinutes = startHour * 60 + startMinute;\r\n\r\n // Parse end time\r\n const [endHour, endMinute] = endTime.split(\":\").map(Number);\n if (endHour === undefined || endMinute === undefined) {\n return invalidRule(this, context);\n }\n const endTimeInMinutes = endHour * 60 + endMinute;\r\n\r\n if (inputTimeInMinutes >= startTimeInMinutes && inputTimeInMinutes <= endTimeInMinutes) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translationParams.startTime = startTime;\r\n this.context.translationParams.endTime = endTime;\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Min year rule - year must be >= given year or field\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const minYearRule: SchemaRule<{\r\n yearOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"minYear\",\r\n description: \"The date year must be at least the given year or field\",\r\n defaultErrorMessage: \"The :input year must be higher than :yearOrField\",\r\n async validate(value: Date, context) {\r\n const { yearOrField, scope = \"global\" } = this.context.options;\r\n let compareYear: number;\r\n\r\n if (typeof yearOrField === \"number\") {\r\n compareYear = yearOrField;\r\n this.context.translationParams.yearOrField = yearOrField;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, yearOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.yearOrField = yearOrField;\r\n\r\n // If field contains a date, extract the year\r\n if (fieldValue instanceof Date) {\r\n compareYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareYear = fieldValue;\r\n } else {\r\n // Try to parse as date and extract year\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputYear = inputDate.getFullYear();\r\n\r\n if (inputYear >= compareYear) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Max year rule - year must be <= given year or field\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const maxYearRule: SchemaRule<{\r\n yearOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"maxYear\",\r\n description: \"The date year must be at most the given year or field\",\r\n defaultErrorMessage: \"The :input year must be at most :yearOrField\",\r\n async validate(value: Date, context) {\r\n const { yearOrField, scope = \"global\" } = this.context.options;\r\n let compareYear: number;\r\n\r\n if (typeof yearOrField === \"number\") {\r\n compareYear = yearOrField;\r\n this.context.translationParams.yearOrField = compareYear;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, yearOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.yearOrField = yearOrField;\r\n\r\n // If field contains a date, extract the year\r\n if (fieldValue instanceof Date) {\r\n compareYear = fieldValue.getFullYear();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareYear = fieldValue;\r\n } else {\r\n // Try to parse as date and extract year\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareYear = date.getFullYear();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputYear = inputDate.getFullYear();\r\n\r\n if (inputYear <= compareYear) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Min month rule - month must be >= given month or field (1-12)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const minMonthRule: SchemaRule<{\r\n monthOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"minMonth\",\r\n description: \"The date month must be at least the given month or field\",\r\n defaultErrorMessage: \"The :input month must be at least :monthOrField\",\r\n async validate(value: Date, context) {\r\n const { monthOrField, scope = \"global\" } = this.context.options;\r\n let compareMonth: number;\r\n\r\n if (typeof monthOrField === \"number\") {\r\n compareMonth = monthOrField;\r\n this.context.translationParams.monthOrField = compareMonth;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, monthOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.monthOrField = monthOrField;\r\n\r\n // If field contains a date, extract the month\r\n if (fieldValue instanceof Date) {\r\n compareMonth = fieldValue.getMonth() + 1; // getMonth() returns 0-11\r\n } else if (typeof fieldValue === \"number\") {\r\n compareMonth = fieldValue;\r\n } else {\r\n // Try to parse as date and extract month\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputMonth = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n if (inputMonth >= compareMonth) {\r\n return VALID_RULE;\r\n }\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Max month rule - month must be <= given month or field (1-12)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const maxMonthRule: SchemaRule<{\r\n monthOrField: Month | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"maxMonth\",\r\n description: \"The date month must be at most the given month or field\",\r\n defaultErrorMessage: \"The :input month must be at most :monthOrField\",\r\n async validate(value: Date, context) {\r\n const { monthOrField, scope = \"global\" } = this.context.options;\r\n let compareMonth: number;\r\n\r\n if (typeof monthOrField === \"number\") {\r\n compareMonth = monthOrField;\r\n this.context.translatableParams.monthOrField = MONTHS[monthOrField];\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, monthOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.monthOrField = monthOrField;\r\n\r\n // If field contains a date, extract the month\r\n if (fieldValue instanceof Date) {\r\n compareMonth = fieldValue.getMonth() + 1; // getMonth() returns 0-11\r\n } else if (typeof fieldValue === \"number\") {\r\n compareMonth = fieldValue;\r\n } else {\r\n // Try to parse as date and extract month\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareMonth = date.getMonth() + 1;\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputMonth = inputDate.getMonth() + 1; // getMonth() returns 0-11\r\n\r\n if (inputMonth <= compareMonth) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Min day rule - day must be >= given day or field (1-31)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const minDayRule: SchemaRule<{\r\n dayOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"minDay\",\r\n description: \"The date day must be at least the given day or field\",\r\n defaultErrorMessage: \"The :input day must be higher than :dayOrField\",\r\n async validate(value: Date, context) {\r\n const { dayOrField, scope = \"global\" } = this.context.options;\r\n let compareDay: number;\r\n\r\n if (typeof dayOrField === \"number\") {\r\n compareDay = dayOrField;\r\n this.context.translationParams.dayOrField = dayOrField;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, dayOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.dayOrField = dayOrField;\r\n\r\n // If field contains a date, extract the day\r\n if (fieldValue instanceof Date) {\r\n compareDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareDay = fieldValue;\r\n } else {\r\n // Try to parse as date and extract day\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputDay = inputDate.getDate();\r\n\r\n if (inputDay >= compareDay) {\r\n return VALID_RULE;\r\n }\r\n return invalidRule(this, context);\r\n },\r\n};\r\n\r\n/**\r\n * Max day rule - day must be <= given day or field (1-31)\r\n * Smart detection: number or field name\r\n * Supports both global and sibling scope\r\n */\r\nexport const maxDayRule: SchemaRule<{\r\n dayOrField: number | string;\r\n scope?: \"global\" | \"sibling\";\r\n}> = {\r\n name: \"maxDay\",\r\n description: \"The date day must be at most the given day or field\",\r\n defaultErrorMessage: \"The :input day must be at most :dayOrField\",\r\n async validate(value: Date, context) {\r\n const { dayOrField, scope = \"global\" } = this.context.options;\r\n let compareDay: number;\r\n\r\n if (typeof dayOrField === \"number\") {\r\n compareDay = dayOrField;\r\n this.context.translationParams.dayOrField = dayOrField;\r\n } else {\r\n const source = scope === \"sibling\" ? context.parent : context.allValues;\r\n const fieldValue = get(source, dayOrField);\r\n\r\n if (fieldValue === undefined) {\r\n return VALID_RULE;\r\n }\r\n\r\n this.context.translatableParams.dayOrField = dayOrField;\r\n\r\n // If field contains a date, extract the day\r\n if (fieldValue instanceof Date) {\r\n compareDay = fieldValue.getDate();\r\n } else if (typeof fieldValue === \"number\") {\r\n compareDay = fieldValue;\r\n } else {\r\n // Try to parse as date and extract day\r\n const date = new Date(fieldValue);\r\n if (!isNaN(date.getTime())) {\r\n compareDay = date.getDate();\r\n } else {\r\n return VALID_RULE;\r\n }\r\n }\r\n }\r\n\r\n const inputDate = new Date(value);\r\n const inputDay = inputDate.getDate();\r\n\r\n if (inputDay <= compareDay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KAAK,QAAQ,CAAC,GACvB,aAAa,KAAK,QAAQ;SAE1B,OAAO;GAEX;EACF;EAKA,IAFiB,IADK,KAAK,KACF,CAAC,CAAC,QAEhB,KAAK,YACd,OAAO;EAET,OAAO,YAAY,MAAM,OAAO;CAClC;AACF;;;;;;AAOA,MAAa,aAGR;CACH,MAAM;CACN,aAAa;CACb,qBAAqB;CACrB,MAAM,SAAS,OAAa,SAAS;EACnC,MAAM,EAAE,YAAY,QAAQ,aAAa,KAAK,QAAQ;EACtD,IAAI;EAEJ,IAAI,OAAO,eAAe,UAAU;GAClC,aAAa;GACb,KAAK,QAAQ,kBAAkB,aAAa;EAC9C,OAAO;GAEL,MAAM,aAAa,IADJ,UAAU,YAAY,QAAQ,SAAS,QAAQ,WAC/B,UAAU;GAEzC,IAAI,eAAe,QACjB,OAAO;GAGT,KAAK,QAAQ,mBAAmB,aAAa;GAG7C,IAAI,sBAAsB,MACxB,aAAa,WAAW,QAAQ;QAC3B,IAAI,OAAO,eAAe,UAC/B,aAAa;QACR;IAEL,MAAM,OAAO,IAAI,KAAK,UAAU;IAChC,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,GACvB,aAAa,KAAK,QAAQ;SAE1B,OAAO;GAEX;EACF;EAKA,IAFiB,IADK,KAAK,KACF,CAAC,CAAC,QAEhB,KAAK,YACd,OAAO;EAET,OAAO,YAAY,MAAM,OAAO;CAClC;AACF"}
|
|
@@ -14,7 +14,7 @@ const isCreditCardRule = {
|
|
|
14
14
|
let sum = 0;
|
|
15
15
|
let isEven = false;
|
|
16
16
|
for (let i = cardNumber.length - 1; i >= 0; i--) {
|
|
17
|
-
let digit = parseInt(cardNumber
|
|
17
|
+
let digit = parseInt(cardNumber.charAt(i), 10);
|
|
18
18
|
if (isEven) {
|
|
19
19
|
digit *= 2;
|
|
20
20
|
if (digit > 9) digit -= 9;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credit-card.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/credit-card.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\r\nimport type { SchemaRule } from \"../../types\";\r\n\r\n/**\r\n * Credit card rule - validates credit card number\r\n */\r\nexport const isCreditCardRule: SchemaRule = {\r\n name: \"creditCard\",\r\n defaultErrorMessage: \"The :input must be a valid credit card number\",\r\n async validate(value: any, context) {\r\n // Luhn algorithm for credit card validation\r\n const cardNumber = String(value).replace(/\\s/g, \"\");\r\n\r\n if (!/^\\d+$/.test(cardNumber)) {\r\n return invalidRule(this, context);\r\n }\r\n\r\n let sum = 0;\r\n let isEven = false;\r\n\r\n for (let i = cardNumber.length - 1; i >= 0; i--) {\r\n let digit = parseInt(cardNumber
|
|
1
|
+
{"version":3,"file":"credit-card.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/credit-card.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\r\nimport type { SchemaRule } from \"../../types\";\r\n\r\n/**\r\n * Credit card rule - validates credit card number\r\n */\r\nexport const isCreditCardRule: SchemaRule = {\r\n name: \"creditCard\",\r\n defaultErrorMessage: \"The :input must be a valid credit card number\",\r\n async validate(value: any, context) {\r\n // Luhn algorithm for credit card validation\r\n const cardNumber = String(value).replace(/\\s/g, \"\");\r\n\r\n if (!/^\\d+$/.test(cardNumber)) {\r\n return invalidRule(this, context);\r\n }\r\n\r\n let sum = 0;\r\n let isEven = false;\r\n\r\n for (let i = cardNumber.length - 1; i >= 0; i--) {\r\n let digit = parseInt(cardNumber.charAt(i), 10);\n\r\n if (isEven) {\r\n digit *= 2;\r\n if (digit > 9) {\r\n digit -= 9;\r\n }\r\n }\r\n\r\n sum += digit;\r\n isEven = !isEven;\r\n }\r\n\r\n if (sum % 10 === 0) {\r\n return VALID_RULE;\r\n }\r\n\r\n return invalidRule(this, context);\r\n },\r\n};\r\n"],"mappings":";;;;;;;AAMA,MAAa,mBAA+B;CAC1C,MAAM;CACN,qBAAqB;CACrB,MAAM,SAAS,OAAY,SAAS;EAElC,MAAM,aAAa,OAAO,KAAK,CAAC,CAAC,QAAQ,OAAO,EAAE;EAElD,IAAI,CAAC,QAAQ,KAAK,UAAU,GAC1B,OAAO,YAAY,MAAM,OAAO;EAGlC,IAAI,MAAM;EACV,IAAI,SAAS;EAEb,KAAK,IAAI,IAAI,WAAW,SAAS,GAAG,KAAK,GAAG,KAAK;GAC/C,IAAI,QAAQ,SAAS,WAAW,OAAO,CAAC,GAAG,EAAE;GAE7C,IAAI,QAAQ;IACV,SAAS;IACT,IAAI,QAAQ,GACV,SAAS;GAEb;GAEA,OAAO;GACP,SAAS,CAAC;EACZ;EAEA,IAAI,MAAM,OAAO,GACf,OAAO;EAGT,OAAO,YAAY,MAAM,OAAO;CAClC;AACF"}
|
|
@@ -205,7 +205,7 @@ var BaseValidator = class {
|
|
|
205
205
|
*/
|
|
206
206
|
attributes(attributes) {
|
|
207
207
|
const instance = this.instance;
|
|
208
|
-
for (const key
|
|
208
|
+
for (const [key, value] of Object.entries(attributes)) instance.attributesText[key] = value;
|
|
209
209
|
return instance;
|
|
210
210
|
}
|
|
211
211
|
/**
|
|
@@ -213,7 +213,7 @@ var BaseValidator = class {
|
|
|
213
213
|
*/
|
|
214
214
|
transAttributes(attributes) {
|
|
215
215
|
const instance = this.instance;
|
|
216
|
-
for (const key
|
|
216
|
+
for (const [key, value] of Object.entries(attributes)) instance.translatedAttributes[key] = value;
|
|
217
217
|
return instance;
|
|
218
218
|
}
|
|
219
219
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-validator.mjs","names":["defaultRequiredRule"],"sources":["../../../../../../../seal/src/validators/base-validator.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { validate } from \"../factory/validate\";\nimport { VALID_RULE, invalidRule } from \"../helpers\";\nimport { isEmptyValue } from \"../helpers/is-empty-value\";\nimport { requiredRule as defaultRequiredRule } from \"../rules/core/required\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { mapToStandardResult } from \"../standard-schema/map-result\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"../standard-schema/types\";\nimport type {\n ContextualSchemaRule,\n ContextualizedMutator,\n ContextualizedTransformer,\n Mutator,\n SchemaContext,\n SchemaRule,\n SchemaRuleOptions,\n SimpleTransformerCallback,\n TransformerCallback,\n ValidationAttributesList,\n ValidationResult,\n} from \"../types\";\n\n/**\n * Base validator class - foundation for all validators\n */\nexport class BaseValidator<TInput = unknown, TOutput = TInput> {\n public rules: ContextualSchemaRule[] = [];\n public mutators: ContextualizedMutator[] = [];\n protected defaultValue: any | (() => any);\n protected description?: string;\n protected shouldOmit = false;\n protected isNullable = false;\n protected isMutable = false;\n\n /**\n * Catch state — when `hasCatch` is true and validation fails, `catchValue`\n * (or its callback result) substitutes for the failed value, and the public\n * result reports `isValid: true` with no errors.\n *\n * See `.catch()` for semantics and the v1 scope (leaf-only).\n */\n protected catchValue:\n | any\n | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>);\n protected hasCatch = false;\n\n /**\n * Whether the field is optional.\n * - false (default): field is required unless a requiredRule governs the condition.\n * - true: field can be absent or empty — set by calling .optional().\n *\n * Also used as a TypeScript literal brand via the optional() return type.\n */\n public isOptional = false;\n\n /**\n * The single required-condition rule for this field.\n * - null: field uses strict default (always required when not optional).\n * - set: the rule governs when the field is required (e.g., requiredIf).\n *\n * Stored separately from rules[] and prepended at validate() time.\n */\n public requiredRule: ContextualSchemaRule | null = this.createRule(defaultRequiredRule);\n\n /**\n * Pipeline to transform the mutated/original data before returning it\n */\n protected dataTransformers: ContextualizedTransformer[] = [];\n\n /**\n * Attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n */\n protected attributesText: ValidationAttributesList = {};\n\n /**\n * Attributed that will be always using the attribute translator\n */\n protected translatedAttributes: Record<string, string> = {};\n\n /**\n * Mark the validator as mutable\n */\n public get mutable() {\n this.isMutable = true;\n return this;\n }\n\n /**\n * Mark the validator as immutable\n */\n public get immutable() {\n this.isMutable = false;\n return this;\n }\n\n /**\n * Get the instance to apply changes to.\n * By default (immutable), returns a clone so the original is unchanged.\n * When `.mutable` is set, returns `this` to mutate in place.\n */\n protected get instance(): this {\n return this.isMutable ? this : this.clone();\n }\n\n /**\n * Get the default value\n * Supports lazy evaluation via callbacks\n */\n public getDefaultValue(): any {\n return typeof this.defaultValue === \"function\" ? this.defaultValue() : this.defaultValue;\n }\n\n /**\n * Allow null as a valid value.\n *\n * Brands the return type with `{ isNullable: true }` so `Infer<>` widens\n * the inferred output to include `| null`.\n */\n public nullable(): this & { isNullable: true } {\n const instance = this.instance;\n instance.isNullable = true;\n return instance as this & { isNullable: true };\n }\n\n /**\n * Explicitly disallow null values after calling nullable.\n *\n * Brands the return type with `{ isNullable: false }` to cancel any prior\n * `.nullable()` at the type level.\n */\n public notNullable(): this & { isNullable: false } {\n const instance = this.instance;\n instance.isNullable = false;\n return instance as this & { isNullable: false };\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addTransformer(transform: TransformerCallback, options: any = {}) {\n const instance = this.instance;\n instance.addMutableTransformer(transform, options);\n\n return instance;\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addMutableTransformer(transform: TransformerCallback, options: any = {}) {\n this.dataTransformers.push({\n transform,\n options,\n });\n }\n\n /**\n * Transform the output value - simple one-time transformation\n *\n * @param callback - Simple callback receiving data and context\n *\n * @example\n * ```ts\n * // Simple transformation\n * v.string().outputAs(data => data.toUpperCase())\n *\n * // With context\n * v.string().outputAs((data, context) => {\n * console.log(`Transforming ${context.path}`);\n * return data.toLowerCase();\n * })\n * ```\n */\n public outputAs(callback: SimpleTransformerCallback) {\n return this.addTransformer((data, { context }) => callback(data, context));\n }\n\n /**\n * Transform output to JSON string\n *\n * Works with any validator type (string, number, date, object, array, etc.)\n *\n * @param indent - Optional indentation for pretty printing (default: 0 for compact)\n *\n * @example\n * ```ts\n * // Compact JSON\n * v.object({ name: v.string() }).toJSON()\n * // Output: '{\"name\":\"John\"}'\n *\n * // Pretty-printed JSON\n * v.array(v.object({...})).toJSON(2)\n * // Output:\n * // [\n * // {\n * // \"name\": \"John\"\n * // }\n * // ]\n *\n * // Works with any type\n * v.string().toJSON() // '\"hello\"'\n * v.number().toJSON() // '42'\n * v.date().toJSON() // '\"2024-10-26T00:00:00.000Z\"'\n * ```\n *\n * @category Transformer\n */\n public toJSON(indent?: number) {\n return this.addTransformer((data, { options }) => JSON.stringify(data, null, options.indent), {\n indent: indent ?? 0,\n });\n }\n\n /**\n * Start data transformation pipeline\n * Context is passed at runtime, not stored\n */\n public async startTransformationPipeline(data: any, context: SchemaContext) {\n for (const transformer of this.dataTransformers) {\n data = await transformer.transform(data, {\n options: transformer.options,\n context,\n });\n }\n\n return data;\n }\n\n /**\n * Set attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n *\n * @example\n * v.string().attributes({\n * name: \"Name\",\n * email: \"Email\",\n * });\n * // Example 2: Add custom attributes for matches\n * v.string().matches(\"confirmPassword\").attributes({\n * matches: {\n * confirmPassword: \"Confirm Password\",\n * },\n * });\n */\n public attributes(attributes: Record<string, string | Record<string, string>>) {\n const instance = this.instance;\n for (const key in attributes) {\n instance.attributesText[key] = attributes[key];\n }\n\n return instance;\n }\n\n /**\n * Define a lazy getter property for each attribute in the given object and use the config attribute translator\n */\n public transAttributes(attributes: Record<string, string>) {\n const instance = this.instance;\n for (const key in attributes) {\n instance.translatedAttributes[key] = attributes[key];\n }\n\n return instance;\n }\n\n /**\n * Add description to the validator\n */\n public describe(description: string) {\n const instance = this.instance;\n instance.description = description;\n return instance;\n }\n\n /**\n * Check if this validator can handle the given value's type\n * Override this in specific validators to enable type-based routing in union validators\n *\n * Default: returns true (validator will attempt to validate any type)\n *\n * @param value - The value to check\n * @returns True if this validator can handle this type\n *\n * @example\n * ```ts\n * // StringValidator\n * public matchesType(value: any): boolean {\n * return typeof value === 'string';\n * }\n *\n * // Custom FileValidator\n * public matchesType(value: any): boolean {\n * return value instanceof UploadedFile;\n * }\n * ```\n */\n public matchesType(_value: any): boolean {\n return true; // Default: permissive, attempt to validate any type\n }\n\n /**\n * Create a copy of this validator with the same configuration\n * Copies all rules, mutators, transformers, default values, and settings\n *\n * @returns A new validator instance with copied configuration\n *\n * @example\n * ```ts\n * // Create reusable validator templates\n * const baseString = v.string().required().trim().min(3);\n * const emailField = baseString.clone().email();\n * const usernameField = baseString.clone().alphanumeric().max(20);\n *\n * // Works with all validators\n * const positiveInt = v.int().positive().required();\n * const ageField = positiveInt.clone().min(18).max(120);\n * ```\n */\n public clone(): this {\n // Create a new instance using Object.create to preserve the prototype chain\n const Constructor = this.constructor as new (...args: any[]) => this;\n const cloned = Object.create(Constructor.prototype);\n\n // Copy all BaseValidator properties\n cloned.rules = [...this.rules];\n cloned.mutators = [...this.mutators];\n cloned.dataTransformers = [...this.dataTransformers];\n cloned.defaultValue = this.defaultValue;\n cloned.shouldOmit = this.shouldOmit;\n cloned.description = this.description;\n cloned.attributesText = { ...this.attributesText };\n cloned.isNullable = this.isNullable;\n cloned.isOptional = this.isOptional;\n cloned.requiredRule = this.requiredRule; // same reference is fine — rule is treated as immutable\n cloned.catchValue = this.catchValue;\n cloned.hasCatch = this.hasCatch;\n\n return cloned;\n }\n\n /**\n * @deprecated This method is no longer needed and does nothing.\n * Empty values are now automatically skipped for validation rules by default.\n * Only presence validators (required, present, etc.) will check empty values.\n * You can safely remove this call from your code.\n */\n public ignoreEmptyValue(_ignoreEmptyValue = true) {\n // No-op for backward compatibility\n return this;\n }\n\n /**\n * Omit this field from the validated data output\n *\n * Field will still be validated but not included in the final result.\n * Useful for confirmation fields, captcha, terms acceptance, etc.\n *\n * @example\n * ```ts\n * v.object({\n * password: v.string().required(),\n * confirmPassword: v.string().required().sameAs(\"password\").omit(),\n * acceptTerms: v.boolean().required().omit(),\n * });\n * // Output: { password: \"...\" }\n * // confirmPassword and acceptTerms validated but omitted\n * ```\n */\n public omit() {\n const instance = this.instance;\n instance.shouldOmit = true;\n return instance;\n }\n\n /**\n * @alias omit\n */\n public exclude() {\n return this.omit();\n }\n\n /**\n * Check if this field should be omitted from the output\n */\n public isOmitted(): boolean {\n return this.shouldOmit;\n }\n\n /**\n * Add rule to the validator\n */\n public addRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.addMutableRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Set the required-condition rule for this field.\n *\n * Unlike addRule(), this does NOT push to rules[]. The rule is stored in the\n * dedicated `requiredRule` slot and is prepended to the validation pipeline\n * at runtime. Only one required rule can be active per field — this replaces\n * any previously set required rule.\n *\n * Also marks the field as not optional (isOptional = false).\n *\n * @example\n * ```ts\n * // Used internally by required(), requiredIf(), requiredWith(), etc.\n * BaseValidator.prototype.required = function(msg) {\n * return this.setRequiredRule(requiredRule, msg);\n * };\n * ```\n */\n public setRequiredRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.isOptional = false;\n instance.requiredRule = instance.createRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Add mutable rule\n */\n public addMutableRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = this.createRule(rule, errorMessage, options);\n\n this.rules.push(newRule);\n\n return newRule;\n }\n\n /**\n * Create new rule\n */\n protected createRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = {\n ...(clone(rule) as ContextualSchemaRule<T>),\n context: {\n errorMessage,\n options,\n attributesList: this.attributesText,\n translatedAttributes: this.translatedAttributes,\n translationParams: {},\n translatableParams: {},\n },\n };\n\n if (errorMessage) {\n newRule.errorMessage = errorMessage;\n }\n\n if (rule.sortOrder === undefined) {\n newRule.sortOrder = this.rules.length + 1;\n }\n\n return newRule;\n }\n\n /**\n * Use a custom or pre-built validation rule\n *\n * @param rule - The validation rule to apply\n * @param options - Rule options including errorMessage and any rule-specific options\n *\n * @example\n * ```ts\n * import { hexColorRule } from \"@warlock.js/seal\";\n *\n * v.string().useRule(hexColorRule, { errorMessage: \"Invalid color\" });\n * ```\n *\n * @example\n * ```ts\n * // With rule options\n * v.string().useRule(myCustomRule, {\n * customOption: true,\n * errorMessage: \"Custom validation failed\"\n * });\n * ```\n */\n public useRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n options?: T & { errorMessage?: string },\n ) {\n const { errorMessage, ...ruleOptions } = options || ({} as any);\n return this.addRule(rule, errorMessage, ruleOptions);\n }\n\n /**\n * Define custom rule\n */\n public refine(\n callback: (\n value: any,\n context: SchemaContext,\n ) => Promise<string | undefined> | string | undefined,\n ) {\n return this.addRule({\n name: \"custom\",\n async validate(value, context) {\n const result = await callback(value, context);\n if (result) {\n this.context.errorMessage = result;\n return invalidRule(this, context);\n }\n return VALID_RULE;\n },\n });\n }\n\n /**\n * Add mutator to the validator\n */\n public addMutator(mutator: Mutator, options: any = {}) {\n const instance = this.instance;\n instance.addMutableMutator(mutator, options);\n return instance;\n }\n\n /**\n * Add mutable mutator\n */\n public addMutableMutator(mutator: Mutator, options: any = {}) {\n this.mutators.push({\n mutate: mutator,\n context: {\n options,\n ctx: {} as any,\n },\n });\n }\n\n /**\n * Set default value for the field. The default is used when the input is\n * absent (`undefined`); it then flows through the rule pipeline.\n *\n * Brands the return type with `{ hasDefault: true }` so `Infer<>` treats\n * the field as guaranteed-present even when chained with `.optional()`.\n */\n public default(value: any): this & { hasDefault: true } {\n const instance = this.instance;\n instance.defaultValue = value;\n return instance as this & { hasDefault: true };\n }\n\n /**\n * Fallback to a value when validation fails.\n *\n * Complementary to `.default()`: `.default(x)` fires when input is **absent**,\n * `.catch(y)` fires when input is **present but invalid**. Combine them when\n * you want both behaviours: `.optional().default(x).catch(y)`.\n *\n * The fallback can be a value or a callback `(errors, originalInput) => fallback`.\n * The callback variant is the only side-channel for the swallowed errors —\n * use it to log/alert before the fallback substitutes.\n *\n * Brands the return type with `{ hasCatch: true }` so `Infer<>` treats the\n * field as guaranteed-present (the catch ensures a value will always exist).\n *\n * **Scope (v1).** Catch is honoured for **leaf validators** (string, number,\n * boolean, date, …) and for fields inside containers. It is a **no-op on\n * container validators themselves** (`v.object`, `v.array`, `v.record`,\n * `v.tuple`, `v.discriminatedUnion`) — those use their own iteration logic\n * that bypasses the catch hook in `BaseValidator.validate()`.\n *\n * @example\n * ```ts\n * v.int().min(0).catch(3) // bad number → 3\n * v.string().in([\"us\", \"eu\"]).catch(\"us\") // unknown enum → \"us\"\n * v.string().catch((errors, input) => {\n * console.warn(`bad user value: ${JSON.stringify(input)}`, errors);\n * return \"anonymous\";\n * })\n * ```\n */\n public catch(\n fallback:\n | any\n | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>),\n ): this & { hasCatch: true } {\n const instance = this.instance;\n\n instance.catchValue = fallback;\n instance.hasCatch = true;\n\n return instance as this & { hasCatch: true };\n }\n\n /**\n * Mutate the data\n */\n public async mutate(data: any, context: SchemaContext) {\n let mutatedData = data;\n\n for (const mutator of this.mutators) {\n mutator.context.ctx = context;\n mutatedData = await mutator.mutate(mutatedData, mutator.context);\n }\n\n return mutatedData;\n }\n\n /**\n * Set the label for the validator that will be matching the :input attribute\n */\n public label(label: string) {\n const instance = this.instance;\n instance.attributesText.input = label;\n return instance;\n }\n\n /**\n * Validate the data\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n if (data === null && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const valueForRules = data ?? this.getDefaultValue();\n const mutatedData = await this.mutate(valueForRules, context);\n\n const errors: ValidationResult[\"errors\"] = [];\n let isValid = true;\n const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;\n\n const isEmpty = isEmptyValue(valueForRules);\n\n // D8 fix (design/core-defects-found.md): for an optional field, only a\n // truly ABSENT value (`valueForRules === undefined` — the key was\n // missing, or was `null`/`undefined` and got coalesced above) may skip\n // the value rules. A PRESENT-but-empty value (e.g. `\"\"` from `?page=`)\n // must still run them, so `v.int().optional()` given `\"\"` fails instead\n // of silently handing back a string that `Infer.Output`'s\n // `number | undefined` forbids. Non-optional fields are unaffected —\n // their `requiredRule` (not nulled out by `.optional()`) already rejects\n // `\"\"` before these rules matter.\n const skipEmptyRules = this.isOptional ? valueForRules === undefined : isEmpty;\n\n // Prepend the required-condition rule if set, so it always runs first.\n // requiredRule has requiresValue = false so it runs even on empty values.\n const rulesToRun = this.requiredRule ? [this.requiredRule, ...this.rules] : this.rules;\n\n for (const rule of rulesToRun) {\n if ((rule.requiresValue ?? true) && skipEmptyRules) continue;\n\n this.setRuleAttributesList(rule);\n\n const result = await rule.validate(mutatedData, context);\n\n if (result.isValid === false) {\n isValid = false;\n errors.push({\n type: rule.name,\n error: result.error,\n input: result.path ?? context.path,\n });\n\n if (isFirstErrorOnly) {\n break;\n }\n }\n }\n\n const result: ValidationResult = {\n isValid,\n errors,\n data:\n mutatedData !== undefined\n ? await this.startTransformationPipeline(mutatedData, context)\n : undefined,\n };\n\n // Catch fallback — only on the leaf path. Container validators override\n // validate() and don't run this hook on their own outcome, so catching\n // a whole object/array/record is a no-op in v1.\n if (result.isValid === false && this.hasCatch) {\n const fallback =\n typeof this.catchValue === \"function\"\n ? await this.catchValue(result.errors, data)\n : this.catchValue;\n\n return { isValid: true, errors: [], data: fallback };\n }\n\n return result;\n }\n\n /**\n * Set rule attributes list\n */\n protected setRuleAttributesList(rule: ContextualSchemaRule) {\n rule.context.attributesList =\n typeof this.attributesText[rule.name] === \"object\"\n ? (this.attributesText[rule.name] as ValidationAttributesList)\n : this.attributesText;\n }\n\n /**\n * Standard Schema V1 compliance.\n *\n * Allows this validator to be used with any Standard Schema-aware library\n * (OpenAI structured outputs, LangGraph, TanStack Form, Conform, Valibot adapters, etc.)\n * without extra adapters.\n *\n * Delegates to the `validate()` factory so all `configureSeal()` options\n * (translations, firstErrorOnly) are picked up automatically at call time.\n *\n * Includes Standard JSON Schema support via `jsonSchema.input()` / `jsonSchema.output()`.\n *\n * ## How Standard Schema libraries consume this\n *\n * You pass the **schema object itself** to the library — they internally read\n * `schema[\"~standard\"]`. Do NOT pass `schema[\"~standard\"]` directly.\n *\n * @example\n * ```ts\n * const schema = v.object({ name: v.string().required() });\n *\n * // TanStack Form — pass schema, library reads [\"~standard\"] internally\n * const form = useForm({ validators: { onChange: schema } });\n *\n * // Conform (Remix) — same pattern\n * const [form] = useForm({ onValidate({ formData }) {\n * return parseWithStandardSchema(formData, { schema });\n * }});\n *\n * // Direct validation (lower level — most apps don't need this)\n * const result = await schema[\"~standard\"].validate({ name: \"Hasan\" });\n * // → { value: { name: \"Hasan\" } } on success\n * // → { issues: [{ message: \"...\", path: [{ key: \"name\" }] }] } on failure\n *\n * // JSON Schema for OpenAI / LangChain tool calling\n * const parameters = schema[\"~standard\"].jsonSchema.input({ target: \"openai-strict\" });\n * // → { type: \"object\", properties: {...}, required: [...], additionalProperties: false }\n * ```\n *\n * @note Cross-field rules (sameAs, requiredIf, requiredWith) rely on sibling values\n * available in the full validation context. When called on a standalone scalar validator,\n * sibling data is absent and those rules will not evaluate correctly.\n * Always call on the parent ObjectValidator for full-payload validation.\n */\n get [\"~standard\"](): StandardJSONSchemaV1.Props<TInput, TOutput> {\n return {\n version: 1,\n vendor: \"seal\",\n types: undefined as unknown as StandardSchemaV1.Types<TInput, TOutput>,\n validate: async (value: unknown) => {\n const result = await validate(this, value);\n return mapToStandardResult(result) as StandardSchemaV1.Result<TOutput>;\n },\n jsonSchema: {\n input: (options) => this.toJsonSchema(options.target),\n output: (options) => this.toJsonSchema(options.target),\n },\n };\n }\n\n /**\n * Generate a JSON Schema representation of this validator.\n *\n * Supports targets: `\"draft-2020-12\"` (default), `\"draft-07\"`, `\"openapi-3.0\"`.\n *\n * Subclasses override this to describe their specific constraints.\n * The base implementation returns `{}` (permissive — accepts anything),\n * which is correct for validators with no representable JSON Schema constraints.\n *\n * @note Rules that cannot be expressed in JSON Schema are silently omitted:\n * - Cross-field rules: sameAs, requiredIf, requiredWith, requiredWithout\n * - Custom callbacks: refine()\n * - Framework-specific runtime rules (core/cascade plugins)\n * These rules still run normally at validation time — only absent from JSON Schema.\n *\n * @example\n * ```ts\n * v.string().min(3).max(50).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"string\", minLength: 3, maxLength: 50 }\n *\n * v.object({ name: v.string().required(), age: v.int().optional() })\n * .toJsonSchema(\"draft-07\")\n * // → { type: \"object\", properties: { name: { type: \"string\" }, age: { type: \"integer\" } }, required: [\"name\"] }\n * ```\n */\n public toJsonSchema(_target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA+D;;eACtB,CAAC;kBACG,CAAC;oBAGrB;oBACA;mBACD;kBAYD;oBASD;sBAS+B,KAAK,WAAWA,YAAmB;0BAK5B,CAAC;wBAON,C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,MAAM,KAAK,SAAS,aAAa,OAAO;GAEvD,IAAI,OAAO,YAAY,OAAO;IAC5B,UAAU;IACV,OAAO,KAAK;KACV,MAAM,KAAK;KACX,OAAO,OAAO;KACd,OAAO,OAAO,QAAQ,QAAQ;IAChC,CAAC;IAED,IAAI,kBACF;GAEJ;EACF;EAEA,MAAM,SAA2B;GAC/B;GACA;GACA,MACE,gBAAgB,SACZ,MAAM,KAAK,4BAA4B,aAAa,OAAO,IAC3D;EACR;EAKA,IAAI,OAAO,YAAY,SAAS,KAAK,UAMnC,OAAO;GAAE,SAAS;GAAM,QAAQ,CAAC;GAAG,MAJlC,OAAO,KAAK,eAAe,aACvB,MAAM,KAAK,WAAW,OAAO,QAAQ,IAAI,IACzC,KAAK;EAEwC;EAGrD,OAAO;CACT;;;;CAKA,AAAU,sBAAsB,MAA4B;EAC1D,KAAK,QAAQ,iBACX,OAAO,KAAK,eAAe,KAAK,UAAU,WACrC,KAAK,eAAe,KAAK,QAC1B,KAAK;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CA,KAAK,eAA4D;EAC/D,OAAO;GACL,SAAS;GACT,QAAQ;GACR,OAAO;GACP,UAAU,OAAO,UAAmB;IAElC,OAAO,oBAAoB,MADN,SAAS,MAAM,KAAK,CACR;GACnC;GACA,YAAY;IACV,QAAQ,YAAY,KAAK,aAAa,QAAQ,MAAM;IACpD,SAAS,YAAY,KAAK,aAAa,QAAQ,MAAM;GACvD;EACF;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,aAAa,UAA4B,iBAAmC;EACjF,OAAO,CAAC;CACV;AACF"}
|
|
1
|
+
{"version":3,"file":"base-validator.mjs","names":["defaultRequiredRule"],"sources":["../../../../../../../seal/src/validators/base-validator.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { validate } from \"../factory/validate\";\nimport { VALID_RULE, invalidRule } from \"../helpers\";\nimport { isEmptyValue } from \"../helpers/is-empty-value\";\nimport { requiredRule as defaultRequiredRule } from \"../rules/core/required\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { mapToStandardResult } from \"../standard-schema/map-result\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"../standard-schema/types\";\nimport type {\n ContextualSchemaRule,\n ContextualizedMutator,\n ContextualizedTransformer,\n Mutator,\n SchemaContext,\n SchemaRule,\n SchemaRuleOptions,\n SimpleTransformerCallback,\n TransformerCallback,\n ValidationAttributesList,\n ValidationResult,\n} from \"../types\";\n\n/**\n * Base validator class - foundation for all validators\n */\nexport class BaseValidator<TInput = unknown, TOutput = TInput> {\n public rules: ContextualSchemaRule[] = [];\n public mutators: ContextualizedMutator[] = [];\n protected defaultValue: any | (() => any);\n protected description?: string;\n protected shouldOmit = false;\n protected isNullable = false;\n protected isMutable = false;\n\n /**\n * Catch state — when `hasCatch` is true and validation fails, `catchValue`\n * (or its callback result) substitutes for the failed value, and the public\n * result reports `isValid: true` with no errors.\n *\n * See `.catch()` for semantics and the v1 scope (leaf-only).\n */\n protected catchValue:\n | any\n | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>);\n protected hasCatch = false;\n\n /**\n * Whether the field is optional.\n * - false (default): field is required unless a requiredRule governs the condition.\n * - true: field can be absent or empty — set by calling .optional().\n *\n * Also used as a TypeScript literal brand via the optional() return type.\n */\n public isOptional = false;\n\n /**\n * The single required-condition rule for this field.\n * - null: field uses strict default (always required when not optional).\n * - set: the rule governs when the field is required (e.g., requiredIf).\n *\n * Stored separately from rules[] and prepended at validate() time.\n */\n public requiredRule: ContextualSchemaRule | null = this.createRule(defaultRequiredRule);\n\n /**\n * Pipeline to transform the mutated/original data before returning it\n */\n protected dataTransformers: ContextualizedTransformer[] = [];\n\n /**\n * Attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n */\n protected attributesText: ValidationAttributesList = {};\n\n /**\n * Attributed that will be always using the attribute translator\n */\n protected translatedAttributes: Record<string, string> = {};\n\n /**\n * Mark the validator as mutable\n */\n public get mutable() {\n this.isMutable = true;\n return this;\n }\n\n /**\n * Mark the validator as immutable\n */\n public get immutable() {\n this.isMutable = false;\n return this;\n }\n\n /**\n * Get the instance to apply changes to.\n * By default (immutable), returns a clone so the original is unchanged.\n * When `.mutable` is set, returns `this` to mutate in place.\n */\n protected get instance(): this {\n return this.isMutable ? this : this.clone();\n }\n\n /**\n * Get the default value\n * Supports lazy evaluation via callbacks\n */\n public getDefaultValue(): any {\n return typeof this.defaultValue === \"function\" ? this.defaultValue() : this.defaultValue;\n }\n\n /**\n * Allow null as a valid value.\n *\n * Brands the return type with `{ isNullable: true }` so `Infer<>` widens\n * the inferred output to include `| null`.\n */\n public nullable(): this & { isNullable: true } {\n const instance = this.instance;\n instance.isNullable = true;\n return instance as this & { isNullable: true };\n }\n\n /**\n * Explicitly disallow null values after calling nullable.\n *\n * Brands the return type with `{ isNullable: false }` to cancel any prior\n * `.nullable()` at the type level.\n */\n public notNullable(): this & { isNullable: false } {\n const instance = this.instance;\n instance.isNullable = false;\n return instance as this & { isNullable: false };\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addTransformer(transform: TransformerCallback, options: any = {}) {\n const instance = this.instance;\n instance.addMutableTransformer(transform, options);\n\n return instance;\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addMutableTransformer(transform: TransformerCallback, options: any = {}) {\n this.dataTransformers.push({\n transform,\n options,\n });\n }\n\n /**\n * Transform the output value - simple one-time transformation\n *\n * @param callback - Simple callback receiving data and context\n *\n * @example\n * ```ts\n * // Simple transformation\n * v.string().outputAs(data => data.toUpperCase())\n *\n * // With context\n * v.string().outputAs((data, context) => {\n * console.log(`Transforming ${context.path}`);\n * return data.toLowerCase();\n * })\n * ```\n */\n public outputAs(callback: SimpleTransformerCallback) {\n return this.addTransformer((data, { context }) => callback(data, context));\n }\n\n /**\n * Transform output to JSON string\n *\n * Works with any validator type (string, number, date, object, array, etc.)\n *\n * @param indent - Optional indentation for pretty printing (default: 0 for compact)\n *\n * @example\n * ```ts\n * // Compact JSON\n * v.object({ name: v.string() }).toJSON()\n * // Output: '{\"name\":\"John\"}'\n *\n * // Pretty-printed JSON\n * v.array(v.object({...})).toJSON(2)\n * // Output:\n * // [\n * // {\n * // \"name\": \"John\"\n * // }\n * // ]\n *\n * // Works with any type\n * v.string().toJSON() // '\"hello\"'\n * v.number().toJSON() // '42'\n * v.date().toJSON() // '\"2024-10-26T00:00:00.000Z\"'\n * ```\n *\n * @category Transformer\n */\n public toJSON(indent?: number) {\n return this.addTransformer((data, { options }) => JSON.stringify(data, null, options.indent), {\n indent: indent ?? 0,\n });\n }\n\n /**\n * Start data transformation pipeline\n * Context is passed at runtime, not stored\n */\n public async startTransformationPipeline(data: any, context: SchemaContext) {\n for (const transformer of this.dataTransformers) {\n data = await transformer.transform(data, {\n options: transformer.options,\n context,\n });\n }\n\n return data;\n }\n\n /**\n * Set attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n *\n * @example\n * v.string().attributes({\n * name: \"Name\",\n * email: \"Email\",\n * });\n * // Example 2: Add custom attributes for matches\n * v.string().matches(\"confirmPassword\").attributes({\n * matches: {\n * confirmPassword: \"Confirm Password\",\n * },\n * });\n */\n public attributes(attributes: Record<string, string | Record<string, string>>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.attributesText[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Define a lazy getter property for each attribute in the given object and use the config attribute translator\n */\n public transAttributes(attributes: Record<string, string>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.translatedAttributes[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Add description to the validator\n */\n public describe(description: string) {\n const instance = this.instance;\n instance.description = description;\n return instance;\n }\n\n /**\n * Check if this validator can handle the given value's type\n * Override this in specific validators to enable type-based routing in union validators\n *\n * Default: returns true (validator will attempt to validate any type)\n *\n * @param value - The value to check\n * @returns True if this validator can handle this type\n *\n * @example\n * ```ts\n * // StringValidator\n * public matchesType(value: any): boolean {\n * return typeof value === 'string';\n * }\n *\n * // Custom FileValidator\n * public matchesType(value: any): boolean {\n * return value instanceof UploadedFile;\n * }\n * ```\n */\n public matchesType(_value: any): boolean {\n return true; // Default: permissive, attempt to validate any type\n }\n\n /**\n * Create a copy of this validator with the same configuration\n * Copies all rules, mutators, transformers, default values, and settings\n *\n * @returns A new validator instance with copied configuration\n *\n * @example\n * ```ts\n * // Create reusable validator templates\n * const baseString = v.string().required().trim().min(3);\n * const emailField = baseString.clone().email();\n * const usernameField = baseString.clone().alphanumeric().max(20);\n *\n * // Works with all validators\n * const positiveInt = v.int().positive().required();\n * const ageField = positiveInt.clone().min(18).max(120);\n * ```\n */\n public clone(): this {\n // Create a new instance using Object.create to preserve the prototype chain\n const Constructor = this.constructor as new (...args: any[]) => this;\n const cloned = Object.create(Constructor.prototype);\n\n // Copy all BaseValidator properties\n cloned.rules = [...this.rules];\n cloned.mutators = [...this.mutators];\n cloned.dataTransformers = [...this.dataTransformers];\n cloned.defaultValue = this.defaultValue;\n cloned.shouldOmit = this.shouldOmit;\n cloned.description = this.description;\n cloned.attributesText = { ...this.attributesText };\n cloned.isNullable = this.isNullable;\n cloned.isOptional = this.isOptional;\n cloned.requiredRule = this.requiredRule; // same reference is fine — rule is treated as immutable\n cloned.catchValue = this.catchValue;\n cloned.hasCatch = this.hasCatch;\n\n return cloned;\n }\n\n /**\n * @deprecated This method is no longer needed and does nothing.\n * Empty values are now automatically skipped for validation rules by default.\n * Only presence validators (required, present, etc.) will check empty values.\n * You can safely remove this call from your code.\n */\n public ignoreEmptyValue(_ignoreEmptyValue = true) {\n // No-op for backward compatibility\n return this;\n }\n\n /**\n * Omit this field from the validated data output\n *\n * Field will still be validated but not included in the final result.\n * Useful for confirmation fields, captcha, terms acceptance, etc.\n *\n * @example\n * ```ts\n * v.object({\n * password: v.string().required(),\n * confirmPassword: v.string().required().sameAs(\"password\").omit(),\n * acceptTerms: v.boolean().required().omit(),\n * });\n * // Output: { password: \"...\" }\n * // confirmPassword and acceptTerms validated but omitted\n * ```\n */\n public omit() {\n const instance = this.instance;\n instance.shouldOmit = true;\n return instance;\n }\n\n /**\n * @alias omit\n */\n public exclude() {\n return this.omit();\n }\n\n /**\n * Check if this field should be omitted from the output\n */\n public isOmitted(): boolean {\n return this.shouldOmit;\n }\n\n /**\n * Add rule to the validator\n */\n public addRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.addMutableRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Set the required-condition rule for this field.\n *\n * Unlike addRule(), this does NOT push to rules[]. The rule is stored in the\n * dedicated `requiredRule` slot and is prepended to the validation pipeline\n * at runtime. Only one required rule can be active per field — this replaces\n * any previously set required rule.\n *\n * Also marks the field as not optional (isOptional = false).\n *\n * @example\n * ```ts\n * // Used internally by required(), requiredIf(), requiredWith(), etc.\n * BaseValidator.prototype.required = function(msg) {\n * return this.setRequiredRule(requiredRule, msg);\n * };\n * ```\n */\n public setRequiredRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.isOptional = false;\n instance.requiredRule = instance.createRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Add mutable rule\n */\n public addMutableRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = this.createRule(rule, errorMessage, options);\n\n this.rules.push(newRule);\n\n return newRule;\n }\n\n /**\n * Create new rule\n */\n protected createRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = {\n ...(clone(rule) as ContextualSchemaRule<T>),\n context: {\n errorMessage,\n options,\n attributesList: this.attributesText,\n translatedAttributes: this.translatedAttributes,\n translationParams: {},\n translatableParams: {},\n },\n };\n\n if (errorMessage) {\n newRule.errorMessage = errorMessage;\n }\n\n if (rule.sortOrder === undefined) {\n newRule.sortOrder = this.rules.length + 1;\n }\n\n return newRule;\n }\n\n /**\n * Use a custom or pre-built validation rule\n *\n * @param rule - The validation rule to apply\n * @param options - Rule options including errorMessage and any rule-specific options\n *\n * @example\n * ```ts\n * import { hexColorRule } from \"@warlock.js/seal\";\n *\n * v.string().useRule(hexColorRule, { errorMessage: \"Invalid color\" });\n * ```\n *\n * @example\n * ```ts\n * // With rule options\n * v.string().useRule(myCustomRule, {\n * customOption: true,\n * errorMessage: \"Custom validation failed\"\n * });\n * ```\n */\n public useRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n options?: T & { errorMessage?: string },\n ) {\n const { errorMessage, ...ruleOptions } = options || ({} as any);\n return this.addRule(rule, errorMessage, ruleOptions);\n }\n\n /**\n * Define custom rule\n */\n public refine(\n callback: (\n value: any,\n context: SchemaContext,\n ) => Promise<string | undefined> | string | undefined,\n ) {\n return this.addRule({\n name: \"custom\",\n async validate(value, context) {\n const result = await callback(value, context);\n if (result) {\n this.context.errorMessage = result;\n return invalidRule(this, context);\n }\n return VALID_RULE;\n },\n });\n }\n\n /**\n * Add mutator to the validator\n */\n public addMutator(mutator: Mutator, options: any = {}) {\n const instance = this.instance;\n instance.addMutableMutator(mutator, options);\n return instance;\n }\n\n /**\n * Add mutable mutator\n */\n public addMutableMutator(mutator: Mutator, options: any = {}) {\n this.mutators.push({\n mutate: mutator,\n context: {\n options,\n ctx: {} as any,\n },\n });\n }\n\n /**\n * Set default value for the field. The default is used when the input is\n * absent (`undefined`); it then flows through the rule pipeline.\n *\n * Brands the return type with `{ hasDefault: true }` so `Infer<>` treats\n * the field as guaranteed-present even when chained with `.optional()`.\n */\n public default(value: any): this & { hasDefault: true } {\n const instance = this.instance;\n instance.defaultValue = value;\n return instance as this & { hasDefault: true };\n }\n\n /**\n * Fallback to a value when validation fails.\n *\n * Complementary to `.default()`: `.default(x)` fires when input is **absent**,\n * `.catch(y)` fires when input is **present but invalid**. Combine them when\n * you want both behaviours: `.optional().default(x).catch(y)`.\n *\n * The fallback can be a value or a callback `(errors, originalInput) => fallback`.\n * The callback variant is the only side-channel for the swallowed errors —\n * use it to log/alert before the fallback substitutes.\n *\n * Brands the return type with `{ hasCatch: true }` so `Infer<>` treats the\n * field as guaranteed-present (the catch ensures a value will always exist).\n *\n * **Scope (v1).** Catch is honoured for **leaf validators** (string, number,\n * boolean, date, …) and for fields inside containers. It is a **no-op on\n * container validators themselves** (`v.object`, `v.array`, `v.record`,\n * `v.tuple`, `v.discriminatedUnion`) — those use their own iteration logic\n * that bypasses the catch hook in `BaseValidator.validate()`.\n *\n * @example\n * ```ts\n * v.int().min(0).catch(3) // bad number → 3\n * v.string().in([\"us\", \"eu\"]).catch(\"us\") // unknown enum → \"us\"\n * v.string().catch((errors, input) => {\n * console.warn(`bad user value: ${JSON.stringify(input)}`, errors);\n * return \"anonymous\";\n * })\n * ```\n */\n public catch(\n fallback:\n | any\n | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>),\n ): this & { hasCatch: true } {\n const instance = this.instance;\n\n instance.catchValue = fallback;\n instance.hasCatch = true;\n\n return instance as this & { hasCatch: true };\n }\n\n /**\n * Mutate the data\n */\n public async mutate(data: any, context: SchemaContext) {\n let mutatedData = data;\n\n for (const mutator of this.mutators) {\n mutator.context.ctx = context;\n mutatedData = await mutator.mutate(mutatedData, mutator.context);\n }\n\n return mutatedData;\n }\n\n /**\n * Set the label for the validator that will be matching the :input attribute\n */\n public label(label: string) {\n const instance = this.instance;\n instance.attributesText.input = label;\n return instance;\n }\n\n /**\n * Validate the data\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n if (data === null && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const valueForRules = data ?? this.getDefaultValue();\n const mutatedData = await this.mutate(valueForRules, context);\n\n const errors: ValidationResult[\"errors\"] = [];\n let isValid = true;\n const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;\n\n const isEmpty = isEmptyValue(valueForRules);\n\n // D8 fix (design/core-defects-found.md): for an optional field, only a\n // truly ABSENT value (`valueForRules === undefined` — the key was\n // missing, or was `null`/`undefined` and got coalesced above) may skip\n // the value rules. A PRESENT-but-empty value (e.g. `\"\"` from `?page=`)\n // must still run them, so `v.int().optional()` given `\"\"` fails instead\n // of silently handing back a string that `Infer.Output`'s\n // `number | undefined` forbids. Non-optional fields are unaffected —\n // their `requiredRule` (not nulled out by `.optional()`) already rejects\n // `\"\"` before these rules matter.\n const skipEmptyRules = this.isOptional ? valueForRules === undefined : isEmpty;\n\n // Prepend the required-condition rule if set, so it always runs first.\n // requiredRule has requiresValue = false so it runs even on empty values.\n const rulesToRun = this.requiredRule ? [this.requiredRule, ...this.rules] : this.rules;\n\n for (const rule of rulesToRun) {\n if ((rule.requiresValue ?? true) && skipEmptyRules) continue;\n\n this.setRuleAttributesList(rule);\n\n const result = await rule.validate(mutatedData, context);\n\n if (result.isValid === false) {\n isValid = false;\n errors.push({\n type: rule.name,\n error: result.error,\n input: result.path ?? context.path,\n });\n\n if (isFirstErrorOnly) {\n break;\n }\n }\n }\n\n const result: ValidationResult = {\n isValid,\n errors,\n data:\n mutatedData !== undefined\n ? await this.startTransformationPipeline(mutatedData, context)\n : undefined,\n };\n\n // Catch fallback — only on the leaf path. Container validators override\n // validate() and don't run this hook on their own outcome, so catching\n // a whole object/array/record is a no-op in v1.\n if (result.isValid === false && this.hasCatch) {\n const fallback =\n typeof this.catchValue === \"function\"\n ? await this.catchValue(result.errors, data)\n : this.catchValue;\n\n return { isValid: true, errors: [], data: fallback };\n }\n\n return result;\n }\n\n /**\n * Set rule attributes list\n */\n protected setRuleAttributesList(rule: ContextualSchemaRule) {\n rule.context.attributesList =\n typeof this.attributesText[rule.name] === \"object\"\n ? (this.attributesText[rule.name] as ValidationAttributesList)\n : this.attributesText;\n }\n\n /**\n * Standard Schema V1 compliance.\n *\n * Allows this validator to be used with any Standard Schema-aware library\n * (OpenAI structured outputs, LangGraph, TanStack Form, Conform, Valibot adapters, etc.)\n * without extra adapters.\n *\n * Delegates to the `validate()` factory so all `configureSeal()` options\n * (translations, firstErrorOnly) are picked up automatically at call time.\n *\n * Includes Standard JSON Schema support via `jsonSchema.input()` / `jsonSchema.output()`.\n *\n * ## How Standard Schema libraries consume this\n *\n * You pass the **schema object itself** to the library — they internally read\n * `schema[\"~standard\"]`. Do NOT pass `schema[\"~standard\"]` directly.\n *\n * @example\n * ```ts\n * const schema = v.object({ name: v.string().required() });\n *\n * // TanStack Form — pass schema, library reads [\"~standard\"] internally\n * const form = useForm({ validators: { onChange: schema } });\n *\n * // Conform (Remix) — same pattern\n * const [form] = useForm({ onValidate({ formData }) {\n * return parseWithStandardSchema(formData, { schema });\n * }});\n *\n * // Direct validation (lower level — most apps don't need this)\n * const result = await schema[\"~standard\"].validate({ name: \"Hasan\" });\n * // → { value: { name: \"Hasan\" } } on success\n * // → { issues: [{ message: \"...\", path: [{ key: \"name\" }] }] } on failure\n *\n * // JSON Schema for OpenAI / LangChain tool calling\n * const parameters = schema[\"~standard\"].jsonSchema.input({ target: \"openai-strict\" });\n * // → { type: \"object\", properties: {...}, required: [...], additionalProperties: false }\n * ```\n *\n * @note Cross-field rules (sameAs, requiredIf, requiredWith) rely on sibling values\n * available in the full validation context. When called on a standalone scalar validator,\n * sibling data is absent and those rules will not evaluate correctly.\n * Always call on the parent ObjectValidator for full-payload validation.\n */\n get [\"~standard\"](): StandardJSONSchemaV1.Props<TInput, TOutput> {\n return {\n version: 1,\n vendor: \"seal\",\n types: undefined as unknown as StandardSchemaV1.Types<TInput, TOutput>,\n validate: async (value: unknown) => {\n const result = await validate(this, value);\n return mapToStandardResult(result) as StandardSchemaV1.Result<TOutput>;\n },\n jsonSchema: {\n input: (options) => this.toJsonSchema(options.target),\n output: (options) => this.toJsonSchema(options.target),\n },\n };\n }\n\n /**\n * Generate a JSON Schema representation of this validator.\n *\n * Supports targets: `\"draft-2020-12\"` (default), `\"draft-07\"`, `\"openapi-3.0\"`.\n *\n * Subclasses override this to describe their specific constraints.\n * The base implementation returns `{}` (permissive — accepts anything),\n * which is correct for validators with no representable JSON Schema constraints.\n *\n * @note Rules that cannot be expressed in JSON Schema are silently omitted:\n * - Cross-field rules: sameAs, requiredIf, requiredWith, requiredWithout\n * - Custom callbacks: refine()\n * - Framework-specific runtime rules (core/cascade plugins)\n * These rules still run normally at validation time — only absent from JSON Schema.\n *\n * @example\n * ```ts\n * v.string().min(3).max(50).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"string\", minLength: 3, maxLength: 50 }\n *\n * v.object({ name: v.string().required(), age: v.int().optional() })\n * .toJsonSchema(\"draft-07\")\n * // → { type: \"object\", properties: { name: { type: \"string\" }, age: { type: \"integer\" } }, required: [\"name\"] }\n * ```\n */\n public toJsonSchema(_target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA+D;;eACtB,C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.mts","names":[],"sources":["../../../../../../../seal/src/validators/object-validator.ts"],"mappings":";;;;;;;;;;;;AA+BA;;;;;;;;;;;;cAAa,eAAA,iBAAgC,MAAA,GAAS,MAAA,UAAgB,aAAA,CACpE,qBAAA,CAAsB,OAAA,GACtB,sBAAA,CAAuB,OAAA;EAOd,MAAA,EAAQ,OAAA;EAAA,UALP,kBAAA;EAAA,UACA,WAAA;EAAA,UACA,iBAAA;cAGD,MAAA,EAAQ,OAAA,EACf,YAAA;EAyK0B;;;EAhKrB,WAAA,CAAY,KAAA;EAkKU;EA7JtB,YAAA;EAyNqB;EA/MrB,KAAA,IAAS,IAAA;EA+MyD;EAxMlE,IAAA,CAAK,SAAA;EAwMwD;;;EAhM7D,YAAA,CAAa,KAAA;
|
|
1
|
+
{"version":3,"file":"object-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/object-validator.ts"],"mappings":";;;;;;;;;;;;AA+BA;;;;;;;;;;;;cAAa,eAAA,iBAAgC,MAAA,GAAS,MAAA,UAAgB,aAAA,CACpE,qBAAA,CAAsB,OAAA,GACtB,sBAAA,CAAuB,OAAA;EAOd,MAAA,EAAQ,OAAA;EAAA,UALP,kBAAA;EAAA,UACA,WAAA;EAAA,UACA,iBAAA;cAGD,MAAA,EAAQ,OAAA,EACf,YAAA;EAyK0B;;;EAhKrB,WAAA,CAAY,KAAA;EAkKU;EA7JtB,YAAA;EAyNqB;EA/MrB,KAAA,IAAS,IAAA;EA+MyD;EAxMlE,IAAA,CAAK,SAAA;EAwMwD;;;EAhM7D,YAAA,CAAa,KAAA;EAuOkB;;;;;;;;;;;;;EApNtB,KAAA,CAAM,IAAA;EApE8C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoI7D,MAAA,oBAA0B,MAAA,EAC/B,iBAAA,EAAmB,UAAA,GAAa,eAAA,CAAgB,UAAA,IAC/C,eAAA,CAAgB,OAAA,GAAU,UAAA;EA6ChB;;;;;;;;;;;;;;;;;;;;;;;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