prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, {
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
>(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": "}\n/**\n * VineObject represents an object value in the validation\n * schema.\n */\nexport class VineObject<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> extends BaseType<Output, CamelCaseOutput> {", "score": 0.8923541307449341 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },", "score": 0.870674192905426 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(() => true, properties)\n}", "score": 0.8551148176193237 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "import { ObjectGroup } from './group.js'\nimport { GroupConditional } from './conditional.js'\nimport { BaseModifiersType, BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js'\n/**\n * Converts schema properties to camelCase\n */\nexport class VineCamelCaseObject<\n Schema extends VineObject<any, any, any>,", "score": 0.8495320081710815 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(conditon, properties)\n}\n/**", "score": 0.8408527970314026 } ]
typescript
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [
PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.908103883266449 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 0.8953438997268677 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.8944092988967896 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8926043510437012 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.8896386623382568 } ]
typescript
PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] ||
!schema[UNIQUE_NAME]) {
throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return this\n }\n /**\n * Clones the VineUnionOfTypes schema type.\n */\n clone(): this {\n const cloned = new VineUnionOfTypes<Schema>(this.#schemas)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this\n }", "score": 0.8642842769622803 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 0.861072301864624 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.8479374647140503 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.8418749570846558 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 0.8263358473777771 } ]
typescript
!schema[UNIQUE_NAME]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values),
options?: FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 0.9146298766136169 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 0.868840217590332 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.8674771189689636 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 0.8668174743652344 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8645652532577515 } ]
typescript
options?: FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroup } from './group.js' import { OTYPE, COTYPE } from '../../symbols.js' import { CamelCase } from '../camelcase_types.js' import { GroupConditional } from './conditional.js' import type { FieldContext, SchemaTypes } from '../../types.js' /** * Create an object group. Groups are used to conditionally merge properties * to an existing object. */ export function group<Conditional extends GroupConditional<any, any, any>>( conditionals: Conditional[] ) { return new ObjectGroup<Conditional>(conditionals) } /** * Wrap object properties inside a conditonal */ group.if = function groupIf<Properties extends Record<string, SchemaTypes>>( conditon: (value: Record<string, unknown>, field: FieldContext) => any, properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, {
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
>(conditon, properties) } /** * Wrap object properties inside an else conditon */ group.else = function groupElse<Properties extends Record<string, SchemaTypes>>( properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(() => true, properties) }
src/schema/object/group_builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 0.8833034038543701 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8772886991500854 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " declare [OTYPE]: Output;\n declare [COTYPE]: CamelCaseOutput\n /**\n * Properties to merge when conditonal is true\n */\n #properties: Properties\n /**\n * Conditional to evaluate\n */\n #conditional: ConditionalFn<Record<string, unknown>>", "score": 0.86798495054245 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "import { ObjectGroup } from './group.js'\nimport { GroupConditional } from './conditional.js'\nimport { BaseModifiersType, BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js'\n/**\n * Converts schema properties to camelCase\n */\nexport class VineCamelCaseObject<\n Schema extends VineObject<any, any, any>,", "score": 0.8544873595237732 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 0.8455721735954285 } ]
typescript
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values
| ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 0.8977510929107666 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.8773713707923889 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8719863295555115 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 0.8508012890815735 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 0.8432924747467041 } ]
typescript
| ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { GroupConditional } from './conditional.js' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, UnionNoMatchCallback } from '../../types.js' /** * Object group represents a group with multiple conditionals, where each * condition returns a set of object properties to merge into the * existing object. */ export class ObjectGroup<Conditional extends GroupConditional<any, any, any>> { declare [OTYPE]: Conditional[typeof OTYPE]; declare [COTYPE]: Conditional[typeof COTYPE] #conditionals: Conditional[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionGroup, 'unionGroup', field) } constructor(conditionals: Conditional[]) { this.#conditionals = conditionals } /** * Clones the ObjectGroup schema type. */ clone(): this { const cloned = new ObjectGroup<Conditional>(this.#conditionals) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Define a fallback method to invoke when all of the group conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Compiles the group */
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
return { type: 'group', elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)), } } }
src/schema/object/group.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 0.8564271926879883 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.8526111841201782 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 0.8492280840873718 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n allowUnknownProperties: this.#allowUnknownProperties,\n validations: this.compileValidations(refs),\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: this.#groups.map((group) => {\n return group[PARSE](refs, options)\n }),", "score": 0.8457609415054321 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " type: 'sub_object',\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: [], // Compiler allows nested groups, but we are not implementing it\n },\n conditionalFnRefId: refs.trackConditional(this.#conditional),\n }\n }\n}", "score": 0.842171311378479 } ]
typescript
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values), options?:
FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 0.8982937335968018 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.8774895668029785 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8714532852172852 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 0.8504496216773987 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 0.843504786491394 } ]
typescript
FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { GroupConditional } from './conditional.js' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, UnionNoMatchCallback } from '../../types.js' /** * Object group represents a group with multiple conditionals, where each * condition returns a set of object properties to merge into the * existing object. */ export class ObjectGroup<Conditional extends GroupConditional<any, any, any>> { declare [OTYPE]: Conditional[typeof OTYPE]; declare [COTYPE]: Conditional[typeof COTYPE] #conditionals: Conditional[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionGroup, 'unionGroup', field) } constructor(conditionals: Conditional[]) { this.#conditionals = conditionals } /** * Clones the ObjectGroup schema type. */ clone(): this { const cloned = new ObjectGroup<Conditional>(this.#conditionals) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Define a fallback method to invoke when all of the group conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Compiles the group */ [
PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
return { type: 'group', elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)), } } }
src/schema/object/group.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 0.8688280582427979 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.8661742806434631 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 0.8620456457138062 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n allowUnknownProperties: this.#allowUnknownProperties,\n validations: this.compileValidations(refs),\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: this.#groups.map((group) => {\n return group[PARSE](refs, options)\n }),", "score": 0.8559457063674927 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " type: 'sub_object',\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: [], // Compiler allows nested groups, but we are not implementing it\n },\n conditionalFnRefId: refs.trackConditional(this.#conditional),\n }\n }\n}", "score": 0.8527442812919617 } ]
typescript
PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */
export const positiveRule = createRule((value, _, field) => {
/** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * Enforce value to be within the range of minimum and maximum output.\n */\n range(value: [min: number, max: number]) {\n return this.use(rangeRule({ min: value[0], max: value[1] }))\n }\n /**\n * Enforce the value be a positive number\n */\n positive() {", "score": 0.8816055059432983 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length < options.min) {\n field.report(messages['record.minLength'], 'record.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an object field", "score": 0.871994137763977 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 0.8707481622695923 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 0.8660099506378174 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 0.8570336699485779 } ]
typescript
export const positiveRule = createRule((value, _, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroup } from './group.js' import { OTYPE, COTYPE } from '../../symbols.js' import { CamelCase } from '../camelcase_types.js' import { GroupConditional } from './conditional.js' import type { FieldContext, SchemaTypes } from '../../types.js' /** * Create an object group. Groups are used to conditionally merge properties * to an existing object. */ export function group<Conditional extends GroupConditional<any, any, any>>( conditionals: Conditional[] ) { return new ObjectGroup<Conditional>(conditionals) } /** * Wrap object properties inside a conditonal */ group.if = function groupIf<Properties extends Record<string, SchemaTypes>>( conditon: (value: Record<string, unknown>, field: FieldContext) => any, properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof
Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
>(conditon, properties) } /** * Wrap object properties inside an else conditon */ group.else = function groupElse<Properties extends Record<string, SchemaTypes>>( properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(() => true, properties) }
src/schema/object/group_builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8785673379898071 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 0.8782243132591248 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " declare [OTYPE]: Output;\n declare [COTYPE]: CamelCaseOutput\n /**\n * Properties to merge when conditonal is true\n */\n #properties: Properties\n /**\n * Conditional to evaluate\n */\n #conditional: ConditionalFn<Record<string, unknown>>", "score": 0.8618799448013306 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "import { ObjectGroup } from './group.js'\nimport { GroupConditional } from './conditional.js'\nimport { BaseModifiersType, BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js'\n/**\n * Converts schema properties to camelCase\n */\nexport class VineCamelCaseObject<\n Schema extends VineObject<any, any, any>,", "score": 0.8501570820808411 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 0.8313470482826233 } ]
typescript
Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Group conditional represents a sub-set of object wrapped * inside a conditional */ export class GroupConditional< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > { declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Properties to merge when conditonal is true */ #properties: Properties /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) { this.#properties = properties this.#conditional = conditional } /** * Compiles to a union conditional */
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {
return { schema: { type: 'sub_object', properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: [], // Compiler allows nested groups, but we are not implementing it }, conditionalFnRefId: refs.trackConditional(this.#conditional), } } }
src/schema/object/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " /**\n * Compiles to a union conditional\n */\n [PARSE](\n propertyName: string,\n refs: RefsStore,\n options: ParserOptions\n ): UnionNode['conditions'][number] {\n return {\n conditionalFnRefId: refs.trackConditional(this.#conditional),", "score": 0.9104176163673401 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.8839572072029114 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 0.8794382810592651 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 0.8750172257423401 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback\n return this\n }\n /**\n * Compiles the group\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {\n return {\n type: 'group',", "score": 0.8681352734565735 } ]
typescript
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.9087018966674805 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.8993592858314514 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 0.8953422904014587 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 0.8941699266433716 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8914905190467834 } ]
typescript
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true
return this.#schema[PARSE](propertyName, refs, options) }
} /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 0.9069728851318359 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.9067015051841736 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 0.8954305052757263 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.8928312659263611 }, { "filename": "src/types.ts", "retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**", "score": 0.8881040811538696 } ]
typescript
return this.#schema[PARSE](propertyName, refs, options) }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject<
Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> {
/** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },", "score": 0.8644883036613464 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 0.8566867709159851 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\n/**\n * VineTuple is an array with known length and may have different\n * schema type for each array element.\n */\nexport class VineTuple<\n Schema extends SchemaTypes[],\n Output extends any[],", "score": 0.8519070148468018 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 0.845924973487854 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " this.#allowUnknownProperties = true\n return this as unknown as VineTuple<\n Schema,\n [...Output, ...Value[]],\n [...CamelCaseOutput, ...Value[]]\n >\n }\n /**\n * Clone object\n */", "score": 0.8441901803016663 } ]
typescript
Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) }
constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.9282225966453552 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8877788186073303 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8774654865264893 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8735155463218689 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.8692842125892639 } ]
typescript
constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties
: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.9299455881118774 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8957653045654297 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8801632523536682 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8696318864822388 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.862506628036499 } ]
typescript
: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[
typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { ObjectGroup } from './group.js'\nimport { OTYPE, COTYPE } from '../../symbols.js'", "score": 0.8489909768104553 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8377214670181274 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'", "score": 0.8151058554649353 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " * Vine union represents a union data type. A union is a collection\n * of conditionals and each condition has an associated schema\n */\nexport class VineUnion<Conditional extends UnionConditional<SchemaTypes>>\n implements ConstructableSchema<Conditional[typeof OTYPE], Conditional[typeof COTYPE]>\n{\n declare [OTYPE]: Conditional[typeof OTYPE];\n declare [COTYPE]: Conditional[typeof COTYPE]\n #conditionals: Conditional[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {", "score": 0.8115844130516052 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 0.8038570880889893 } ]
typescript
typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output
& Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { ObjectGroup } from './group.js'\nimport { OTYPE, COTYPE } from '../../symbols.js'", "score": 0.8481324911117554 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8366175889968872 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'", "score": 0.816963791847229 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " * Vine union represents a union data type. A union is a collection\n * of conditionals and each condition has an associated schema\n */\nexport class VineUnion<Conditional extends UnionConditional<SchemaTypes>>\n implements ConstructableSchema<Conditional[typeof OTYPE], Conditional[typeof COTYPE]>\n{\n declare [OTYPE]: Conditional[typeof OTYPE];\n declare [COTYPE]: Conditional[typeof COTYPE]\n #conditionals: Conditional[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {", "score": 0.8125355839729309 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 0.8045177459716797 } ]
typescript
& Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this
.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " clone(): this {\n const cloned = new VineTuple<Schema, Output, CamelCaseOutput>(\n this.#schemas.map((schema) => schema.clone()) as Schema,\n this.cloneOptions(),\n this.cloneValidations()\n )\n if (this.#allowUnknownProperties) {\n cloned.allowUnknownProperties()\n }\n return cloned as this", "score": 0.9135554432868958 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " this.#allowUnknownProperties = true\n return this as unknown as VineTuple<\n Schema,\n [...Output, ...Value[]],\n [...CamelCaseOutput, ...Value[]]\n >\n }\n /**\n * Clone object\n */", "score": 0.8951020240783691 }, { "filename": "src/schema/any/main.ts", "retrieved_chunk": " */\n clone(): this {\n return new VineAny(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8885009288787842 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " clone(): this {\n return new VineLiteral(this.#value, this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8753571510314941 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " clone(): this {\n return new VineString(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8735088109970093 } ]
typescript
.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties,
Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { ObjectGroup } from './group.js'\nimport { OTYPE, COTYPE } from '../../symbols.js'", "score": 0.8435879945755005 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8327121734619141 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'", "score": 0.8104475140571594 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " * Vine union represents a union data type. A union is a collection\n * of conditionals and each condition has an associated schema\n */\nexport class VineUnion<Conditional extends UnionConditional<SchemaTypes>>\n implements ConstructableSchema<Conditional[typeof OTYPE], Conditional[typeof COTYPE]>\n{\n declare [OTYPE]: Conditional[typeof OTYPE];\n declare [COTYPE]: Conditional[typeof COTYPE]\n #conditionals: Conditional[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {", "score": 0.8071143627166748 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 0.8008823394775391 } ]
typescript
Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.
compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 0.9252160787582397 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9166877269744873 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9039497971534729 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.897245466709137 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8881280422210693 } ]
typescript
compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, RecordNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' import { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js' /** * VineRecord represents an object of key-value pair in which * keys are unknown */ export class VineRecord<Schema extends SchemaTypes> extends BaseType< { [K: string]: Schema[typeof OTYPE] }, { [K: string]: Schema[typeof COTYPE] } > { /** * Default collection of record rules */ static rules = { maxLength: maxLengthRule, minLength: minLengthRule, fixedLength: fixedLengthRule, validateKeys: validateKeysRule, } #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schema = schema } /** * Enforce a minimum length on an object field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on an object field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on an object field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Register a callback to validate the object keys */ validateKeys
(...args: Parameters<typeof validateKeysRule>) {
return this.use(validateKeysRule(...args)) } /** * Clones the VineRecord schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineRecord( this.#schema.clone(), this.cloneOptions(), this.cloneValidations() ) as this } /** * Compiles to record data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode { return { type: 'record', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, each: this.#schema[PARSE]('*', refs, options), parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/record/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Ensure the array is not empty\n */\n notEmpty() {\n return this.use(notEmptyRule())\n }", "score": 0.8587012887001038 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Register a callback to validate the object keys\n */\nexport const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>(\n (value, callback, field) => {\n /**\n * Skip if the field is not valid.\n */", "score": 0.8574480414390564 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Ensure the field under validation is confirmed by\n * having another field with the same name.\n */\n confirmed(options?: { confirmationField: string }) {\n return this.use(confirmedRule(options))\n }", "score": 0.8562271595001221 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " }\n /**\n * Enforce a maximum length on a string field\n */\n maxLength(expectedLength: number) {\n return this.use(maxLengthRule({ max: expectedLength }))\n }\n /**\n * Enforce a fixed length on a string field\n */", "score": 0.8512758612632751 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid postal code\n */\n postalCode(...args: Parameters<typeof postalCodeRule>) {\n return this.use(postalCodeRule(...args))\n }\n /**\n * Validates the value to be a valid UUID\n */\n uuid(...args: Parameters<typeof uuidRule>) {", "score": 0.8440796732902527 } ]
typescript
(...args: Parameters<typeof validateKeysRule>) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */
[UNIQUE_NAME] = 'vine.string';
/** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8518617749214172 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 0.8498310446739197 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "import type { FieldContext } from '@vinejs/compiler/types'\nimport { helpers } from '../../vine/helpers.js'\nimport { messages } from '../../defaults.js'\nimport { createRule } from '../../vine/create_rule.js'\nimport type {\n URLOptions,\n AlphaOptions,\n EmailOptions,\n MobileOptions,\n PassportOptions,", "score": 0.8451274037361145 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 0.8400577306747437 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " static rules = {\n max: maxRule,\n min: minRule,\n range: rangeRule,\n number: numberRule,\n decimal: decimalRule,\n negative: negativeRule,\n positive: positiveRule,\n withoutDecimals: withoutDecimalsRule,\n };", "score": 0.839534342288971 } ]
typescript
[UNIQUE_NAME] = 'vine.string';
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class
VineString extends BaseLiteralType<string, string> {
static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 0.8770990371704102 }, { "filename": "src/schema/accepted/main.ts", "retrieved_chunk": "/*\n * vinejs\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { acceptedRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.8753165006637573 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { enumRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.8692054152488708 }, { "filename": "src/schema/enum/main.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { enumRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.8692054152488708 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "/*\n * vinejs\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { equalsRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.8682460784912109 } ]
typescript
VineString extends BaseLiteralType<string, string> {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>(
(value, locales, field) => {
if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(normalizeEmailRule(options))\n }\n /**\n * Converts the field value to UPPERCASE.\n */\n toUpperCase() {\n return this.use(toUpperCaseRule())\n }\n /**\n * Converts the field value to lowercase.", "score": 0.8776205778121948 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.831061601638794 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8296015858650208 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.8293246626853943 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {", "score": 0.8278576731681824 } ]
typescript
(value, locales, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, RecordNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' import { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js' /** * VineRecord represents an object of key-value pair in which * keys are unknown */ export class VineRecord<Schema extends SchemaTypes> extends BaseType< { [K: string]: Schema[typeof OTYPE] }, { [K: string]: Schema[typeof COTYPE] } > { /** * Default collection of record rules */ static rules = { maxLength: maxLengthRule, minLength: minLengthRule, fixedLength: fixedLengthRule, validateKeys: validateKeysRule, } #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schema = schema } /** * Enforce a minimum length on an object field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on an object field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on an object field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Register a callback to validate the object keys */ validateKeys(...args: Parameters<typeof validateKeysRule>) { return this.use(validateKeysRule(...args)) } /** * Clones the VineRecord schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineRecord( this.#schema.clone(), this.cloneOptions(), this.cloneValidations() ) as this } /** * Compiles to record data type */
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {
return { type: 'record', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, each: this.#schema[PARSE]('*', refs, options), parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/record/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.9160990715026855 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {\n return {\n type: 'tuple',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,", "score": 0.8977787494659424 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.8903863430023193 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.8896212577819824 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.887485146522522 } ]
typescript
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this
.use(urlRule(...args)) }
/** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if (!helpers.isHexColor(value as string)) {\n field.report(messages.hexCode, 'hexCode', field)\n }\n})\n/**\n * Validates the value to be a valid URL\n */\nexport const urlRule = createRule<URLOptions | undefined>((value, options, field) => {\n if (!field.isValid) {", "score": 0.861810028553009 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " */\nexport const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>(\n (value, options, field) => {\n if (!field.isValid) {\n return\n }\n field.mutate(normalizeUrl(value as string, options), field)\n }\n)\n/**", "score": 0.8614584803581238 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.8551077246665955 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8548628091812134 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " */\nexport const stringRule = createRule((value, _, field) => {\n if (typeof value !== 'string') {\n field.report(messages.string, 'string', field)\n }\n})\n/**\n * Validates the value to be a valid email address\n */\nexport const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {", "score": 0.8520994186401367 } ]
typescript
.use(urlRule(...args)) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find(
(provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8099252581596375 }, { "filename": "src/defaults.ts", "retrieved_chunk": " */\nexport const messages = {\n 'required': 'The {{ field }} field must be defined',\n 'string': 'The {{ field }} field must be a string',\n 'email': 'The {{ field }} field must be a valid email address',\n 'mobile': 'The {{ field }} field must be a valid mobile phone number',\n 'creditCard': 'The {{ field }} field must be a valid {{ providersList }} card number',\n 'passport': 'The {{ field }} field must be a valid passport number',\n 'postalCode': 'The {{ field }} field must be a valid postal code',\n 'regex': 'The {{ field }} field format is invalid',", "score": 0.799101710319519 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length <= 0) {\n field.report(messages.notEmpty, 'notEmpty', field)\n }\n})\n/**", "score": 0.7974781394004822 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.7967562675476074 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\n if (!field.isValid) {\n return\n }\n if ((value as number) >= 0) {\n field.report(messages.negative, 'negative', field)\n }\n})\n/**\n * Enforce the value to have a fixed or range of decimals", "score": 0.7950168251991272 } ]
typescript
(provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) { field.report(messages['record.maxLength'], 'record.maxLength', field, options) } }) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) { field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) } }) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>( (value
, callback, field) => {
/** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " * Enforce a fixed length on an object field\n */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Register a callback to validate the object keys\n */\n validateKeys(...args: Parameters<typeof validateKeysRule>) {\n return this.use(validateKeysRule(...args))", "score": 0.8669849634170532 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 0.8515375256538391 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\n if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 0.8485622406005859 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.8466401100158691 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 0.8429833650588989 } ]
typescript
, callback, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, RecordNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' import { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js' /** * VineRecord represents an object of key-value pair in which * keys are unknown */ export class VineRecord<Schema extends SchemaTypes> extends BaseType< { [K: string]: Schema[typeof OTYPE] }, { [K: string]: Schema[typeof COTYPE] } > { /** * Default collection of record rules */ static rules = { maxLength: maxLengthRule, minLength: minLengthRule, fixedLength: fixedLengthRule, validateKeys: validateKeysRule, } #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schema = schema } /** * Enforce a minimum length on an object field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on an object field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on an object field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Register a callback to validate the object keys */ validateKeys(...args: Parameters<typeof validateKeysRule>) { return this.use(validateKeysRule(...args)) } /** * Clones the VineRecord schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineRecord( this.#schema.clone(), this.cloneOptions(), this.cloneValidations() ) as this } /** * Compiles to record data type */ [PARSE](propertyName: string, refs: RefsStore,
options: ParserOptions): RecordNode {
return { type: 'record', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, each: this.#schema[PARSE]('*', refs, options), parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/record/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.9123472571372986 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {\n return {\n type: 'tuple',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,", "score": 0.9017204642295837 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.900800347328186 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.9003528356552124 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.8979108333587646 } ]
typescript
options: ParserOptions): RecordNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!
helpers.isEmail(value as string, options)) {
field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Trims whitespaces around the string value\n */\n trim() {\n return this.use(trimRule())\n }\n /**\n * Normalizes the email address\n */\n normalizeEmail(options?: NormalizeEmailOptions) {", "score": 0.8643760681152344 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8599688410758972 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8540447950363159 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8498017191886902 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8494409322738647 } ]
typescript
helpers.isEmail(value as string, options)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<
RegExp>((value, expression, field) => {
if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {", "score": 0.8526937961578369 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8477156162261963 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8365000486373901 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.8322690725326538 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 0.8294882774353027 } ]
typescript
RegExp>((value, expression, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode
const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8359482884407043 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8346430063247681 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 0.8314164876937866 }, { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type PassportOptions = {\n countryCode: (typeof helpers)['passportCountryCodes'][number][]\n}\n/**\n * Options accepted by the postal code validation\n */\nexport type PostalCodeOptions = {\n countryCode: PostalCodeLocale[]\n}", "score": 0.8288582563400269 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8287941813468933 } ]
typescript
const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */
export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {
if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8723697662353516 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.8714617490768433 }, { "filename": "src/schema/accepted/rules.ts", "retrieved_chunk": "export const acceptedRule = createRule((value, _, field) => {\n if (!ACCEPTED_VALUES.includes(value as any)) {\n field.report(messages.accepted, 'accepted', field)\n }\n})", "score": 0.8708434104919434 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8593644499778748 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {", "score": 0.8570522665977478 } ]
typescript
export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */
export class VineString extends BaseLiteralType<string, string> {
static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 0.8864564895629883 }, { "filename": "src/schema/accepted/main.ts", "retrieved_chunk": "/*\n * vinejs\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { acceptedRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.8779449462890625 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "/*\n * vinejs\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { equalsRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.871198832988739 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " withoutDecimalsRule,\n} from './rules.js'\n/**\n * VineNumber represents a numeric value in the validation schema.\n */\nexport class VineNumber extends BaseLiteralType<number, number> {\n protected declare options: FieldOptions & { strict?: boolean }\n /**\n * Default collection of number rules\n */", "score": 0.8693229556083679 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { enumRule } from './rules.js'\nimport { BaseLiteralType } from '../base/literal.js'", "score": 0.8685013055801392 } ]
typescript
export class VineString extends BaseLiteralType<string, string> {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) }
constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.8956084251403809 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8863973021507263 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.87584388256073 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 0.8633031845092773 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8628857731819153 } ]
typescript
constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {
return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.9241963624954224 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 0.910109281539917 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.8952229619026184 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.8889550566673279 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.887641191482544 } ]
typescript
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...
Schema], options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.895158052444458 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.894994854927063 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8848056793212891 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8587627410888672 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 0.8587337732315063 } ]
typescript
Schema], options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor
(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.911274790763855 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.894649863243103 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8876833915710449 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8727554678916931 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 0.8599451780319214 } ]
typescript
(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ConditionalFn, RefsStore, UnionNode } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Represents a union conditional type. A conditional is a predicate * with a schema */ export class UnionConditional<Schema extends SchemaTypes> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] /** * Properties to merge when conditonal is true */ #schema: Schema /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema) { this.#schema = schema this.#conditional = conditional } /** * Compiles to a union conditional */
[PARSE]( propertyName: string, refs: RefsStore, options: ParserOptions ): UnionNode['conditions'][number] {
return { conditionalFnRefId: refs.trackConditional(this.#conditional), schema: this.#schema[PARSE](propertyName, refs, options), } } }
src/schema/union/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.9253559112548828 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 0.9247517585754395 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 0.9215124249458313 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.9023991823196411 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 0.8976746201515198 } ]
typescript
[PARSE]( propertyName: string, refs: RefsStore, options: ParserOptions ): UnionNode['conditions'][number] {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { RefsStore, UnionNode } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { OTYPE, COTYPE, PARSE, IS_OF_TYPE } from '../../symbols.js' import type { SchemaTypes, ParserOptions, ConstructableSchema, UnionNoMatchCallback, } from '../../types.js' /** * Vine union represents a union data type. A union is a collection * of conditionals and each condition has an associated schema */ export class VineUnionOfTypes<Schema extends SchemaTypes> implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] #schemas: Schema[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionOfTypes, 'unionOfTypes', field) } constructor(schemas: Schema[]) { this.#schemas = schemas } /** * Define a fallback method to invoke when all of the union conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Clones the VineUnionOfTypes schema type. */ clone(): this { const cloned = new VineUnionOfTypes<Schema>(this.#schemas) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Compiles to a union */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode { return { type: 'union', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#schemas.map((schema) => { return { conditionalFnRefId: refs.trackConditional((value, field) => {
return schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
}), } } }
src/schema/union_of_types/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 0.9029911160469055 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8973238468170166 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 0.8905520439147949 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 0.8830676078796387 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8794723153114319 } ]
typescript
return schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ConditionalFn, RefsStore, UnionNode } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Represents a union conditional type. A conditional is a predicate * with a schema */ export class UnionConditional<Schema extends SchemaTypes> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] /** * Properties to merge when conditonal is true */ #schema: Schema /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema) { this.#schema = schema this.#conditional = conditional } /** * Compiles to a union conditional */ [PARSE]( propertyName: string, refs: RefsStore, options
: ParserOptions ): UnionNode['conditions'][number] {
return { conditionalFnRefId: refs.trackConditional(this.#conditional), schema: this.#schema[PARSE](propertyName, refs, options), } } }
src/schema/union/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.9308633804321289 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 0.9257631897926331 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.9102791547775269 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.9064854979515076 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 0.8992109298706055 } ]
typescript
: ParserOptions ): UnionNode['conditions'][number] {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (
typeof helpers)['passportCountryCodes'][number][] }
/** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n creditCard(...args: Parameters<typeof creditCardRule>) {\n return this.use(creditCardRule(...args))\n }\n /**\n * Validates the value to be a valid passport number\n */\n passport(...args: Parameters<typeof passportRule>) {\n return this.use(passportRule(...args))\n }", "score": 0.8272860646247864 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " PassportOptions | ((field: FieldContext) => PassportOptions)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const countryCodes =\n typeof options === 'function' ? options(field).countryCode : options.countryCode", "score": 0.8262552618980408 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " isCreditCard: isCreditCard.default,\n isIBAN: isIBAN.default,\n isJWT: isJWT.default,\n isLatLong: isLatLong.default,\n isMobilePhone: isMobilePhone.default,\n isPassportNumber: isPassportNumber.default,\n isPostalCode: isPostalCode.default,\n isSlug: isSlug.default,\n isDecimal: isDecimal.default,\n mobileLocales: mobilePhoneLocales as MobilePhoneLocale[],", "score": 0.8132093548774719 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " CreditCardOptions,\n PostalCodeOptions,\n NormalizeUrlOptions,\n AlphaNumericOptions,\n NormalizeEmailOptions,\n} from '../../types.js'\nimport camelcase from 'camelcase'\nimport normalizeUrl from 'normalize-url'\n/**\n * Validates the value to be a string", "score": 0.8127512335777283 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " postalCountryCodes: postalCodeLocales as PostalCodeLocale[],\n passportCountryCodes: [\n 'AM',\n 'AR',\n 'AT',\n 'AU',\n 'AZ',\n 'BE',\n 'BG',\n 'BR',", "score": 0.8109872341156006 } ]
typescript
typeof helpers)['passportCountryCodes'][number][] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */
[UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.9094946384429932 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.8793030977249146 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.8764305710792542 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.8755144476890564 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8744602799415588 } ]
typescript
[UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = {
countryCode: (typeof helpers)['passportCountryCodes'][number][] }
/** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n creditCard(...args: Parameters<typeof creditCardRule>) {\n return this.use(creditCardRule(...args))\n }\n /**\n * Validates the value to be a valid passport number\n */\n passport(...args: Parameters<typeof passportRule>) {\n return this.use(passportRule(...args))\n }", "score": 0.8302883505821228 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " PassportOptions | ((field: FieldContext) => PassportOptions)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const countryCodes =\n typeof options === 'function' ? options(field).countryCode : options.countryCode", "score": 0.8223142027854919 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " CreditCardOptions,\n PostalCodeOptions,\n NormalizeUrlOptions,\n AlphaNumericOptions,\n NormalizeEmailOptions,\n} from '../../types.js'\nimport camelcase from 'camelcase'\nimport normalizeUrl from 'normalize-url'\n/**\n * Validates the value to be a string", "score": 0.8150879144668579 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " isCreditCard: isCreditCard.default,\n isIBAN: isIBAN.default,\n isJWT: isJWT.default,\n isLatLong: isLatLong.default,\n isMobilePhone: isMobilePhone.default,\n isPassportNumber: isPassportNumber.default,\n isPostalCode: isPostalCode.default,\n isSlug: isSlug.default,\n isDecimal: isDecimal.default,\n mobileLocales: mobilePhoneLocales as MobilePhoneLocale[],", "score": 0.8134303092956543 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": ")\n/**\n * Validates the value to be a valid credit card number\n */\nexport const creditCardRule = createRule<\n CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */", "score": 0.8121179938316345 } ]
typescript
countryCode: (typeof helpers)['passportCountryCodes'][number][] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(
): ValidationError }
/** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": "import type { ErrorReporterContract, FieldContext } from '../types.js'\n/**\n * Shape of the error message collected by the SimpleErrorReporter\n */\ntype SimpleError = {\n message: string\n field: string\n rule: string\n index?: number\n meta?: Record<string, any>", "score": 0.8220523595809937 }, { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": " */\nexport class SimpleErrorReporter implements ErrorReporterContract {\n /**\n * Boolean to know one or more errors have been reported\n */\n hasErrors: boolean = false\n /**\n * Collection of errors\n */\n errors: SimpleError[] = []", "score": 0.8123762011528015 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 0.8115535974502563 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 0.7918108701705933 }, { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": " /**\n * Report an error.\n */\n report(\n message: string,\n rule: string,\n field: FieldContext,\n meta?: Record<string, any> | undefined\n ) {\n const error: SimpleError = {", "score": 0.788388729095459 } ]
typescript
): ValidationError }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string
[IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 0.9094946384429932 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.8793030977249146 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.8764305710792542 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.8755144476890564 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8744602799415588 } ]
typescript
[IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */
export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/vine/validator.ts", "retrieved_chunk": " */\nexport class VineValidator<\n Schema extends SchemaTypes,\n MetaData extends undefined | Record<string, any>,\n> {\n /**\n * Reference to static types\n */\n declare [OTYPE]: Schema[typeof OTYPE]\n /**", "score": 0.8550654649734497 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": "import { messages } from '../defaults.js'\nimport { OTYPE, PARSE } from '../symbols.js'\nimport type {\n Infer,\n SchemaTypes,\n MetaDataValidator,\n ValidationOptions,\n ErrorReporterContract,\n} from '../types.js'\n/**", "score": 0.8510708808898926 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " Schema extends BaseModifiersType<any, any>,\n Output,\n> extends BaseModifiersType<Output, Output> {\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;\n declare [COTYPE]: Output\n #parent: Schema", "score": 0.8195123672485352 }, { "filename": "src/vine/main.ts", "retrieved_chunk": " * Data to validate\n */\n data: any\n } & ValidationOptions<Record<string, any> | undefined>\n ): Promise<Infer<Schema>> {\n const validator = this.compile(options.schema)\n return validator.validate(options.data, options)\n }\n}", "score": 0.813340425491333 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": "import type { LiteralNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE, VALIDATION } from '../../symbols.js'\nimport type {\n Parser,\n Validation,\n RuleBuilder,\n Transformer,\n FieldOptions,\n ParserOptions,\n ConstructableSchema,", "score": 0.8074188232421875 } ]
typescript
export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder {
[VALIDATION](): Validation<any> }
/** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": "import type {\n Parser,\n Validation,\n RuleBuilder,\n FieldOptions,\n ParserOptions,\n ConstructableSchema,\n} from '../../types.js'\nimport Macroable from '@poppinss/macroable'\n/**", "score": 0.8456038236618042 }, { "filename": "src/vine/create_rule.ts", "retrieved_chunk": " implicit?: boolean\n isAsync?: boolean\n }\n) {\n const rule: ValidationRule<Options> = {\n validator,\n isAsync: metaData?.isAsync || validator.constructor.name === 'AsyncFunction',\n implicit: metaData?.implicit ?? false,\n }\n return function (...options: GetArgs<Options>): Validation<Options> {", "score": 0.8405356407165527 }, { "filename": "src/symbols.ts", "retrieved_chunk": " * The symbol to generate a validation rule from rule builder\n */\nexport const VALIDATION = Symbol.for('to_validation')", "score": 0.8388888835906982 }, { "filename": "src/vine/create_rule.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { Validation, ValidationRule, Validator } from '../types.js'\n/**", "score": 0.8382845520973206 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " use(validation: Validation<any> | RuleBuilder): this {\n this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation)\n return this\n }\n /**\n * Enable/disable the bail mode. In bail mode, the field validations\n * are stopped after the first error.\n */\n bail(state: boolean) {\n this.options.bail = state", "score": 0.836970865726471 } ]
typescript
[VALIDATION](): Validation<any> }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { Compiler, refsBuilder } from '@vinejs/compiler' import type { MessagesProviderContact, Refs } from '@vinejs/compiler/types' import { messages } from '../defaults.js' import { OTYPE, PARSE } from '../symbols.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, } from '../types.js' /** * Error messages to share with the compiler */ const COMPILER_ERROR_MESSAGES = { required: messages.required, array: messages.array, object: messages.object, } /** * Vine Validator exposes the API to validate data using a pre-compiled * schema. */ export class VineValidator< Schema extends SchemaTypes, MetaData extends undefined | Record<string, any>, > { /** * Reference to static types */ declare [OTYPE]: Schema[typeof OTYPE] /** * Validator to use to validate metadata */ #metaDataValidator?: MetaDataValidator /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract /** * Parses schema to compiler nodes. */ #parse(schema: Schema) { const refs = refsBuilder() return { compilerNode: { type: 'root' as const,
schema: schema[PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
} /** * Refs computed from the compiled output */ #refs: Refs /** * Compiled validator function */ #validateFn: ReturnType<Compiler['compile']> constructor( schema: Schema, options: { convertEmptyStringsToNull: boolean metaDataValidator?: MetaDataValidator messagesProvider: MessagesProviderContact errorReporter: () => ErrorReporterContract } ) { const { compilerNode, refs } = this.#parse(schema) this.#refs = refs this.#validateFn = new Compiler(compilerNode, { convertEmptyStringsToNull: options.convertEmptyStringsToNull, messages: COMPILER_ERROR_MESSAGES, }).compile() this.errorReporter = options.errorReporter this.messagesProvider = options.messagesProvider this.#metaDataValidator = options.metaDataValidator } /** * Validate data against a schema. Optionally, you can share metaData with * the validator * * ```ts * await validator.validate(data) * await validator.validate(data, { meta: {} }) * * await validator.validate(data, { * meta: { userId: auth.user.id }, * errorReporter, * messagesProvider * }) * ``` */ validate( data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>] ): Promise<Infer<Schema>> { if (options?.meta && this.#metaDataValidator) { this.#metaDataValidator(options.meta) } const errorReporter = options?.errorReporter || this.errorReporter const messagesProvider = options?.messagesProvider || this.messagesProvider return this.#validateFn( data, options?.meta || {}, this.#refs, messagesProvider, errorReporter() ) } }
src/vine/validator.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.8942638635635376 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8927780389785767 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8840739130973816 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.8836156129837036 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.878822922706604 } ]
typescript
schema: schema[PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter {
createError(): ValidationError }
/** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": "import type { ErrorReporterContract, FieldContext } from '../types.js'\n/**\n * Shape of the error message collected by the SimpleErrorReporter\n */\ntype SimpleError = {\n message: string\n field: string\n rule: string\n index?: number\n meta?: Record<string, any>", "score": 0.8300266265869141 }, { "filename": "src/reporters/simple_error_reporter.ts", "retrieved_chunk": " */\nexport class SimpleErrorReporter implements ErrorReporterContract {\n /**\n * Boolean to know one or more errors have been reported\n */\n hasErrors: boolean = false\n /**\n * Collection of errors\n */\n errors: SimpleError[] = []", "score": 0.8256906270980835 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 0.8230574727058411 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 0.8070619106292725 }, { "filename": "src/vine/main.ts", "retrieved_chunk": "import { SchemaBuilder } from '../schema/builder.js'\nimport { SimpleMessagesProvider } from '../messages_provider/simple_messages_provider.js'\nimport { VineValidator } from './validator.js'\nimport { fields, messages } from '../defaults.js'\nimport type {\n Infer,\n SchemaTypes,\n MetaDataValidator,\n ValidationOptions,\n ErrorReporterContract,", "score": 0.8017498254776001 } ]
typescript
createError(): ValidationError }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { Compiler, refsBuilder } from '@vinejs/compiler' import type { MessagesProviderContact, Refs } from '@vinejs/compiler/types' import { messages } from '../defaults.js' import { OTYPE, PARSE } from '../symbols.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, } from '../types.js' /** * Error messages to share with the compiler */ const COMPILER_ERROR_MESSAGES = { required: messages.required, array: messages.array, object: messages.object, } /** * Vine Validator exposes the API to validate data using a pre-compiled * schema. */ export class VineValidator< Schema extends SchemaTypes, MetaData extends undefined | Record<string, any>, > { /** * Reference to static types */ declare [OTYPE]: Schema[typeof OTYPE] /** * Validator to use to validate metadata */ #metaDataValidator?: MetaDataValidator /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract /** * Parses schema to compiler nodes. */ #parse(schema: Schema) { const refs = refsBuilder() return { compilerNode: { type: 'root' as const, schema: schema[
PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
} /** * Refs computed from the compiled output */ #refs: Refs /** * Compiled validator function */ #validateFn: ReturnType<Compiler['compile']> constructor( schema: Schema, options: { convertEmptyStringsToNull: boolean metaDataValidator?: MetaDataValidator messagesProvider: MessagesProviderContact errorReporter: () => ErrorReporterContract } ) { const { compilerNode, refs } = this.#parse(schema) this.#refs = refs this.#validateFn = new Compiler(compilerNode, { convertEmptyStringsToNull: options.convertEmptyStringsToNull, messages: COMPILER_ERROR_MESSAGES, }).compile() this.errorReporter = options.errorReporter this.messagesProvider = options.messagesProvider this.#metaDataValidator = options.metaDataValidator } /** * Validate data against a schema. Optionally, you can share metaData with * the validator * * ```ts * await validator.validate(data) * await validator.validate(data, { meta: {} }) * * await validator.validate(data, { * meta: { userId: auth.user.id }, * errorReporter, * messagesProvider * }) * ``` */ validate( data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>] ): Promise<Infer<Schema>> { if (options?.meta && this.#metaDataValidator) { this.#metaDataValidator(options.meta) } const errorReporter = options?.errorReporter || this.errorReporter const messagesProvider = options?.messagesProvider || this.messagesProvider return this.#validateFn( data, options?.meta || {}, this.#refs, messagesProvider, errorReporter() ) } }
src/vine/validator.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.893113911151886 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.8880586624145508 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return {\n conditionalFnRefId: refs.trackConditional((value, field) => {\n return schema[IS_OF_TYPE]!(value, field)\n }),\n schema: schema[PARSE](propertyName, refs, options),\n }\n }),\n }\n }\n}", "score": 0.8820931911468506 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8820313215255737 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8782688975334167 } ]
typescript
PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from './helpers.js' import { createRule } from './create_rule.js' import { SchemaBuilder } from '../schema/builder.js' import { SimpleMessagesProvider } from '../messages_provider/simple_messages_provider.js' import { VineValidator } from './validator.js' import { fields, messages } from '../defaults.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' import { SimpleErrorReporter } from '../reporters/simple_error_reporter.js' /** * Validate user input with type-safety using a pre-compiled schema. */ export class Vine extends SchemaBuilder { /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact = new SimpleMessagesProvider(messages, fields) /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract = () => new SimpleErrorReporter() /** * Control whether or not to convert empty strings to null */ convertEmptyStringsToNull: boolean = false /** * Helpers to perform type-checking or cast types keeping * HTML forms serialization behavior in mind. */ helpers = helpers /** * Convert a validation function to a Vine schema rule */ createRule = createRule /** * Pre-compiles a schema into a validation function. * * ```ts * const validate = vine.compile(schema) * await validate({ data }) * ``` */ compile<Schema extends SchemaTypes>(schema: Schema) {
return new VineValidator<Schema, Record<string, any> | undefined>(schema, {
convertEmptyStringsToNull: this.convertEmptyStringsToNull, messagesProvider: this.messagesProvider, errorReporter: this.errorReporter, }) } /** * Define a callback to validate the metadata given to the validator * at runtime */ withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) { return { compile: <Schema extends SchemaTypes>(schema: Schema) => { return new VineValidator<Schema, MetaData>(schema, { convertEmptyStringsToNull: this.convertEmptyStringsToNull, messagesProvider: this.messagesProvider, errorReporter: this.errorReporter, metaDataValidator: callback, }) }, } } /** * Validate data against a schema. Optionally, you can define * error messages, fields, a custom messages provider, * or an error reporter. * * ```ts * await vine.validate({ schema, data }) * await vine.validate({ schema, data, messages, fields }) * * await vine.validate({ schema, data, messages, fields }, { * errorReporter * }) * ``` */ validate<Schema extends SchemaTypes>( options: { /** * Schema to use for validation */ schema: Schema /** * Data to validate */ data: any } & ValidationOptions<Record<string, any> | undefined> ): Promise<Infer<Schema>> { const validator = this.compile(options.schema) return validator.validate(options.data, options) } }
src/vine/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.825202226638794 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " * Error messages to share with the compiler\n */\nconst COMPILER_ERROR_MESSAGES = {\n required: messages.required,\n array: messages.array,\n object: messages.object,\n}\n/**\n * Vine Validator exposes the API to validate data using a pre-compiled\n * schema.", "score": 0.8231385946273804 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " */\nexport class VineValidator<\n Schema extends SchemaTypes,\n MetaData extends undefined | Record<string, any>,\n> {\n /**\n * Reference to static types\n */\n declare [OTYPE]: Schema[typeof OTYPE]\n /**", "score": 0.8179531097412109 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " */\n #validateFn: ReturnType<Compiler['compile']>\n constructor(\n schema: Schema,\n options: {\n convertEmptyStringsToNull: boolean\n metaDataValidator?: MetaDataValidator\n messagesProvider: MessagesProviderContact\n errorReporter: () => ErrorReporterContract\n }", "score": 0.8136498332023621 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " */\n number(options?: { strict: boolean }) {\n return new VineNumber(options)\n }\n /**\n * Define a schema type in which the input value\n * matches the pre-defined value\n */\n literal<const Value>(value: Value) {\n return new VineLiteral<Value>(value)", "score": 0.8135799169540405 } ]
typescript
return new VineValidator<Schema, Record<string, any> | undefined>(schema, {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an array field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length < options.min) { field.report(messages['array.minLength'], 'array.minLength', field, options) } }) /** * Enforce a maximum length on an array field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length > options.max) { field.report(messages['array.maxLength'], 'array.maxLength', field, options) } }) /** * Enforce a fixed length on an array field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length !== options.size) { field.report(messages['array.fixedLength'], 'array.fixedLength', field, options) } }) /** * Ensure the array is not empty */ export const notEmptyRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length <= 0) {
field.report(messages.notEmpty, 'notEmpty', field) }
}) /** * Ensure array elements are distinct/unique */ export const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if (!helpers.isDistinct(value as any[], options.fields)) { field.report(messages.distinct, 'distinct', field, options) } }) /** * Removes empty strings, null and undefined values from the array */ export const compactRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } field.mutate( (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''), field ) })
src/schema/array/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.903302788734436 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.8834065198898315 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8816705942153931 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\n if (!field.isValid) {\n return\n }\n if ((value as number) >= 0) {\n field.report(messages.negative, 'negative', field)\n }\n})\n/**\n * Enforce the value to have a fixed or range of decimals", "score": 0.8763236999511719 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n const list = typeof options.list === 'function' ? options.list(field) : options.list\n /**\n * Performing validation and reporting error\n */\n if (list.includes(value as string)) {\n field.report(messages.notIn, 'notIn', field, options)\n return\n }\n }", "score": 0.8734772205352783 } ]
typescript
field.report(messages.notEmpty, 'notEmpty', field) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { RefsStore, UnionNode } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { OTYPE, COTYPE, PARSE, IS_OF_TYPE } from '../../symbols.js' import type { SchemaTypes, ParserOptions, ConstructableSchema, UnionNoMatchCallback, } from '../../types.js' /** * Vine union represents a union data type. A union is a collection * of conditionals and each condition has an associated schema */ export class VineUnionOfTypes<Schema extends SchemaTypes> implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] #schemas: Schema[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionOfTypes, 'unionOfTypes', field) } constructor(schemas: Schema[]) { this.#schemas = schemas } /** * Define a fallback method to invoke when all of the union conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Clones the VineUnionOfTypes schema type. */ clone(): this { const cloned = new VineUnionOfTypes<Schema>(this.#schemas) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Compiles to a union */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode { return { type: 'union', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#schemas.map((schema) => { return { conditionalFnRefId: refs.trackConditional((value, field) => { return
schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
}), } } }
src/schema/union_of_types/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 0.905755877494812 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 0.9027212858200073 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8907851576805115 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 0.8858073949813843 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8821331262588501 } ]
typescript
schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an array field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length < options.min) { field.report(messages['array.minLength'], 'array.minLength', field, options) } }) /** * Enforce a maximum length on an array field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length > options.max) { field.report(messages['array.maxLength'], 'array.maxLength', field, options) } }) /** * Enforce a fixed length on an array field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length !== options.size) { field.report(messages['array.fixedLength'], 'array.fixedLength', field, options) } }) /** * Ensure the array is not empty */ export const notEmptyRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length <= 0) { field.report(messages.notEmpty, 'notEmpty', field) } }) /** * Ensure array elements are distinct/unique */ export const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if (!helpers.
isDistinct(value as any[], options.fields)) {
field.report(messages.distinct, 'distinct', field, options) } }) /** * Removes empty strings, null and undefined values from the array */ export const compactRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } field.mutate( (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''), field ) })
src/schema/array/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.9067069888114929 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8909488916397095 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const input = field.parent[options.otherField]\n /**\n * Performing validation and reporting error\n */", "score": 0.888413667678833 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.8805152177810669 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " if (!field.isValid) {\n return\n }\n const providers = options\n ? typeof options === 'function'\n ? options(field)?.provider || []\n : options.provider\n : []\n if (!providers.length) {\n if (!helpers.isCreditCard(value as string)) {", "score": 0.8643425107002258 } ]
typescript
isDistinct(value as any[], options.fields)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { CompilerNodes, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE, VALIDATION } from '../../symbols.js' import type { Parser, Validation, RuleBuilder, FieldOptions, ParserOptions, ConstructableSchema, } from '../../types.js' import Macroable from '@poppinss/macroable' /** * Base schema type with only modifiers applicable on all the schema types. */ export abstract class BaseModifiersType<Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Output, CamelCaseOutput> { /** * Each subtype should implement the compile method that returns * one of the known compiler nodes */ abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes /** * The child class must implement the clone method */ abstract clone(): this /** * The output value of the field. The property points to a type only * and not the real value. */ declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Mark the field under validation as optional. An optional * field allows both null and undefined values. */ optional(): OptionalModifier<this> { return new OptionalModifier(this) } /** * Mark the field under validation to be null. The null value will * be written to the output as well. * * If `optional` and `nullable` are used together, then both undefined * and null values will be allowed. */ nullable(): NullableModifier<this> { return new NullableModifier(this) } } /** * Modifies the schema type to allow null values */ class NullableModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the nullable modifier */ clone(): this { return new NullableModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes { const output
= this.#parent[PARSE](propertyName, refs, options) if (output.type !== 'union') {
output.allowNull = true } return output } } /** * Modifies the schema type to allow undefined values */ class OptionalModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the optional modifier */ clone(): this { return new OptionalModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes { const output = this.#parent[PARSE](propertyName, refs, options) if (output.type !== 'union') { output.isOptional = true } return output } } /** * The BaseSchema class abstracts the repetitive parts of creating * a custom schema type. */ export abstract class BaseType<Output, CamelCaseOutput> extends BaseModifiersType< Output, CamelCaseOutput > { /** * Field options */ protected options: FieldOptions /** * Set of validations to run */ protected validations: Validation<any>[] constructor(options?: FieldOptions, validations?: Validation<any>[]) { super() this.options = options || { bail: true, allowNull: false, isOptional: false, } this.validations = validations || [] } /** * Shallow clones the validations. Since, there are no API's to mutate * the validation options, we can safely copy them by reference. */ protected cloneValidations(): Validation<any>[] { return this.validations.map((validation) => { return { options: validation.options, rule: validation.rule, } }) } /** * Shallow clones the options */ protected cloneOptions(): FieldOptions { return { ...this.options } } /** * Compiles validations */ protected compileValidations(refs: RefsStore) { return this.validations.map((validation) => { return { ruleFnId: refs.track({ validator: validation.rule.validator, options: validation.options, }), implicit: validation.rule.implicit, isAsync: validation.rule.isAsync, } }) } /** * Define a method to parse the input value. The method * is invoked before any validation and hence you must * perform type-checking to know the value you are * working it. */ parse(callback: Parser): this { this.options.parse = callback return this } /** * Push a validation to the validations chain. */ use(validation: Validation<any> | RuleBuilder): this { this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation) return this } /** * Enable/disable the bail mode. In bail mode, the field validations * are stopped after the first error. */ bail(state: boolean) { this.options.bail = state return this } }
src/schema/base/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 0.9294567108154297 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 0.9033921957015991 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 0.8950333595275879 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.8937462568283081 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.", "score": 0.8900099992752075 } ]
typescript
= this.#parent[PARSE](propertyName, refs, options) if (output.type !== 'union') {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import Macroable from '@poppinss/macroable' import type { LiteralNode, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE, VALIDATION } from '../../symbols.js' import type { Parser, Validation, RuleBuilder, Transformer, FieldOptions, ParserOptions, ConstructableSchema, } from '../../types.js' /** * Base schema type with only modifiers applicable on all the schema types. */ abstract class BaseModifiersType<Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Output, CamelCaseOutput> { /** * Each subtype should implement the compile method that returns * one of the known compiler nodes */ abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode /** * The child class must implement the clone method */ abstract clone(): this /** * The output value of the field. The property points to a type only * and not the real value. */ declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Mark the field under validation as optional. An optional * field allows both null and undefined values. */ optional(): OptionalModifier<this> { return new OptionalModifier(this) } /** * Mark the field under validation to be null. The null value will * be written to the output as well. * * If `optional` and `nullable` are used together, then both undefined * and null values will be allowed. */ nullable(): NullableModifier<this> { return new NullableModifier(this) } /** * Apply transform on the final validated value. The transform method may * convert the value to any new datatype. */ transform<TransformedOutput>( transformer: Transformer<this, TransformedOutput> ): TransformModifier<this, TransformedOutput> { return new TransformModifier(transformer, this) } } /** * Modifies the schema type to allow null values */ class NullableModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the nullable modifier */ clone(): this { return new NullableModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { const output =
this.#parent[PARSE](propertyName, refs, options) output.allowNull = true return output }
} /** * Modifies the schema type to allow undefined values */ class OptionalModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the optional modifier */ clone(): this { return new OptionalModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { const output = this.#parent[PARSE](propertyName, refs, options) output.isOptional = true return output } } /** * Modifies the schema type to allow custom transformed values */ class TransformModifier< Schema extends BaseModifiersType<any, any>, Output, > extends BaseModifiersType<Output, Output> { /** * The output value of the field. The property points to a type only * and not the real value. */ declare [OTYPE]: Output; declare [COTYPE]: Output #parent: Schema #transform: Transformer<Schema, Output> constructor(transform: Transformer<Schema, Output>, parent: Schema) { super() this.#transform = transform this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the transform modifier. */ clone(): this { return new TransformModifier(this.#transform, this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { const output = this.#parent[PARSE](propertyName, refs, options) output.transformFnId = refs.trackTransformer(this.#transform) return output } } /** * The base type for creating a custom literal type. Literal type * is a schema type that has no children elements. */ export abstract class BaseLiteralType<Output, CamelCaseOutput> extends BaseModifiersType< Output, CamelCaseOutput > { /** * The child class must implement the clone method */ abstract clone(): this /** * Field options */ protected options: FieldOptions /** * Set of validations to run */ protected validations: Validation<any>[] constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) { super() this.options = { bail: true, allowNull: false, isOptional: false, ...options, } this.validations = validations || [] } /** * Shallow clones the validations. Since, there are no API's to mutate * the validation options, we can safely copy them by reference. */ protected cloneValidations(): Validation<any>[] { return this.validations.map((validation) => { return { options: validation.options, rule: validation.rule, } }) } /** * Shallow clones the options */ protected cloneOptions(): FieldOptions { return { ...this.options } } /** * Compiles validations */ protected compileValidations(refs: RefsStore) { return this.validations.map((validation) => { return { ruleFnId: refs.track({ validator: validation.rule.validator, options: validation.options, }), implicit: validation.rule.implicit, isAsync: validation.rule.isAsync, } }) } /** * Define a method to parse the input value. The method * is invoked before any validation and hence you must * perform type-checking to know the value you are * working it. */ parse(callback: Parser): this { this.options.parse = callback return this } /** * Push a validation to the validations chain. */ use(validation: Validation<any> | RuleBuilder): this { this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation) return this } /** * Enable/disable the bail mode. In bail mode, the field validations * are stopped after the first error. */ bail(state: boolean) { this.options.bail = state return this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { return { type: 'literal', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/base/literal.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 0.9511104822158813 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 0.9399203062057495 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 0.9178234338760376 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 0.9150099158287048 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.9130511283874512 } ]
typescript
this.#parent[PARSE](propertyName, refs, options) output.allowNull = true return output }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new
VineLiteral<Value>(value) }
/** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " }\n #value: Value\n constructor(value: Value, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [equalsRule({ expectedValue: value })])\n this.#value = value\n }\n /**\n * Clones the VineLiteral schema type. The applied options\n * and validations are copied to the new instance\n */", "score": 0.8794769048690796 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 0.8719760179519653 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " clone(): this {\n return new VineLiteral(this.#value, this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8572825789451599 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " }\n /**\n * Clones the VineNumber schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNumber(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8561341762542725 }, { "filename": "src/schema/any/main.ts", "retrieved_chunk": "/*\n * vinejs\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { BaseLiteralType } from '../base/literal.js'\nimport type { FieldOptions, Validation } from '../../types.js'", "score": 0.8351504802703857 } ]
typescript
VineLiteral<Value>(value) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties
extends Record<string, SchemaTypes>>(properties: Properties) {
return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " }\n #value: Value\n constructor(value: Value, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [equalsRule({ expectedValue: value })])\n this.#value = value\n }\n /**\n * Clones the VineLiteral schema type. The applied options\n * and validations are copied to the new instance\n */", "score": 0.8644455671310425 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "}\n/**\n * VineObject represents an object value in the validation\n * schema.\n */\nexport class VineObject<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> extends BaseType<Output, CamelCaseOutput> {", "score": 0.853192925453186 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 0.8449142575263977 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " clone(): this {\n return new VineLiteral(this.#value, this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8408858180046082 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 0.8406925797462463 } ]
typescript
extends Record<string, SchemaTypes>>(properties: Properties) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => {
if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) {
throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 0.8636870384216309 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return this\n }\n /**\n * Clones the VineUnionOfTypes schema type.\n */\n clone(): this {\n const cloned = new VineUnionOfTypes<Schema>(this.#schemas)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this\n }", "score": 0.8622725605964661 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.8608645796775818 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.8555342555046082 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": "import { messages } from '../../defaults.js'\nimport { OTYPE, COTYPE, PARSE, IS_OF_TYPE } from '../../symbols.js'\nimport type {\n SchemaTypes,\n ParserOptions,\n ConstructableSchema,\n UnionNoMatchCallback,\n} from '../../types.js'\n/**\n * Vine union represents a union data type. A union is a collection", "score": 0.8326712846755981 } ]
typescript
if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof
Properties]: Properties[K][typeof OTYPE] }, {
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 0.8525410294532776 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " this.#schemas = schemas\n }\n /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineTuple<\n Schema,\n [...Output, ...Value[]],\n [...CamelCaseOutput, ...Value[]]\n > {", "score": 0.8263242840766907 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "}\n/**\n * VineObject represents an object value in the validation\n * schema.\n */\nexport class VineObject<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> extends BaseType<Output, CamelCaseOutput> {", "score": 0.8255760669708252 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },", "score": 0.8250554203987122 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " * Clone object\n */\n clone(): this {\n const cloned = new VineObject<Properties, Output, CamelCaseOutput>(\n this.getProperties(),\n this.cloneOptions(),\n this.cloneValidations()\n )\n this.#groups.forEach((group) => cloned.merge(group))\n if (this.#allowUnknownProperties) {", "score": 0.8244419097900391 } ]
typescript
Properties]: Properties[K][typeof OTYPE] }, {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]
: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] }
>(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\n/**\n * VineTuple is an array with known length and may have different\n * schema type for each array element.\n */\nexport class VineTuple<\n Schema extends SchemaTypes[],\n Output extends any[],", "score": 0.863521933555603 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 0.8454892039299011 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.829958975315094 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 0.8295497894287109 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },", "score": 0.8275890350341797 } ]
typescript
: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values), options
?: FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 0.8996726274490356 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.884352445602417 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8763137459754944 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 0.8488655686378479 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 0.8465547561645508 } ]
typescript
?: FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] },
{ [K in keyof Schema]: Schema[K][typeof COTYPE] }
>(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\n/**\n * VineTuple is an array with known length and may have different\n * schema type for each array element.\n */\nexport class VineTuple<\n Schema extends SchemaTypes[],\n Output extends any[],", "score": 0.862950325012207 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 0.8492048382759094 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 0.8365933895111084 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.8342404365539551 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },", "score": 0.8317466974258423 } ]
typescript
{ [K in keyof Schema]: Schema[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) {
field.report(messages.min, 'min', field, options) }
}) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 0.9711070656776428 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.9126430749893188 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an array field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.9081641435623169 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8922224044799805 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.884097158908844 } ]
typescript
field.report(messages.min, 'min', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report
(messages.max, 'max', field, options) }
}) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.9240844249725342 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.9218863248825073 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.9187890291213989 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const input = field.parent[options.otherField]\n /**\n * Performing validation and reporting error\n */", "score": 0.8920462131500244 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 0.8796762228012085 } ]
typescript
(messages.max, 'max', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Group conditional represents a sub-set of object wrapped * inside a conditional */ export class GroupConditional< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > { declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Properties to merge when conditonal is true */ #properties: Properties /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) { this.#properties = properties this.#conditional = conditional } /** * Compiles to a union conditional */ [PARSE](refs: RefsStore, options:
ParserOptions): ObjectGroupNode['conditions'][number] {
return { schema: { type: 'sub_object', properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: [], // Compiler allows nested groups, but we are not implementing it }, conditionalFnRefId: refs.trackConditional(this.#conditional), } } }
src/schema/object/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " /**\n * Compiles to a union conditional\n */\n [PARSE](\n propertyName: string,\n refs: RefsStore,\n options: ParserOptions\n ): UnionNode['conditions'][number] {\n return {\n conditionalFnRefId: refs.trackConditional(this.#conditional),", "score": 0.9110298752784729 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 0.885312557220459 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 0.8816773891448975 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 0.8762339353561401 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback\n return this\n }\n /**\n * Compiles the group\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {\n return {\n type: 'group',", "score": 0.8668599128723145 } ]
typescript
ParserOptions): ObjectGroupNode['conditions'][number] {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[] ) { super(
options, validations || [enumRule({ choices: values })]) this.#values = values }
/** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 0.938290536403656 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 0.8967341184616089 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 0.8814709186553955 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8757149577140808 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.8748908042907715 } ]
typescript
options, validations || [enumRule({ choices: values })]) this.#values = values }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(
properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.9310771226882935 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8935613036155701 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8765861392021179 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.870147705078125 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.8636747598648071 } ]
typescript
properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) {
field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) }
}) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices\n /**\n * Performing validation and reporting error\n */\n if (!choices.includes(value as string)) {\n field.report(messages.in, 'in', field, options)\n return\n }\n }\n)", "score": 0.872921347618103 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n const list = typeof options.list === 'function' ? options.list(field) : options.list\n /**\n * Performing validation and reporting error\n */\n if (list.includes(value as string)) {\n field.report(messages.notIn, 'notIn', field, options)\n return\n }\n }", "score": 0.8710675239562988 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8658989667892456 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8600730299949646 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if (!helpers.isHexColor(value as string)) {\n field.report(messages.hexCode, 'hexCode', field)\n }\n})\n/**\n * Validates the value to be a valid URL\n */\nexport const urlRule = createRule<URLOptions | undefined>((value, options, field) => {\n if (!field.isValid) {", "score": 0.8599770665168762 } ]
typescript
field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor
(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 0.9301749467849731 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 0.8927160501480103 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 0.8762382864952087 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {", "score": 0.8753473162651062 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 0.869796872138977 } ]
typescript
(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (
!helpers.isDecimal(String(value), {
force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8858421444892883 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.8838517665863037 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 0.8738341331481934 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "})\n/**\n * Enforce a maximum length on a string field\n */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.8734753131866455 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.8719597458839417 } ]
typescript
!helpers.isDecimal(String(value), {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject
<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { ObjectGroup } from './group.js'\nimport { OTYPE, COTYPE } from '../../symbols.js'", "score": 0.8495051264762878 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8354223966598511 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 0.8173047304153442 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'", "score": 0.8165567517280579 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 0.8131081461906433 } ]
typescript
<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties,
validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 0.9232869148254395 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9109743237495422 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.9001160860061646 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 0.8923197388648987 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 0.8919951319694519 } ]
typescript
validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group )
: VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport { ObjectGroup } from './group.js'\nimport { OTYPE, COTYPE } from '../../symbols.js'", "score": 0.84894198179245 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 0.8382694125175476 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " * Vine union represents a union data type. A union is a collection\n * of conditionals and each condition has an associated schema\n */\nexport class VineUnion<Conditional extends UnionConditional<SchemaTypes>>\n implements ConstructableSchema<Conditional[typeof OTYPE], Conditional[typeof COTYPE]>\n{\n declare [OTYPE]: Conditional[typeof OTYPE];\n declare [COTYPE]: Conditional[typeof COTYPE]\n #conditionals: Conditional[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {", "score": 0.8138741850852966 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "/*\n * @vinejs/vine\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'", "score": 0.8136545419692993 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 0.8054190874099731 } ]
typescript
: VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.
cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " clone(): this {\n const cloned = new VineTuple<Schema, Output, CamelCaseOutput>(\n this.#schemas.map((schema) => schema.clone()) as Schema,\n this.cloneOptions(),\n this.cloneValidations()\n )\n if (this.#allowUnknownProperties) {\n cloned.allowUnknownProperties()\n }\n return cloned as this", "score": 0.9125986099243164 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " this.#allowUnknownProperties = true\n return this as unknown as VineTuple<\n Schema,\n [...Output, ...Value[]],\n [...CamelCaseOutput, ...Value[]]\n >\n }\n /**\n * Clone object\n */", "score": 0.8941485285758972 }, { "filename": "src/schema/any/main.ts", "retrieved_chunk": " */\n clone(): this {\n return new VineAny(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8875987529754639 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " clone(): this {\n return new VineLiteral(this.#value, this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8739859461784363 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " clone(): this {\n return new VineString(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.8719110488891602 } ]
typescript
cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this {
return new VineString(this.cloneOptions(), this.cloneValidations()) as this }
}
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " }\n /**\n * Clones the VineNumber schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNumber(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.9195854067802429 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " return this.use(compactRule())\n }\n /**\n * Clones the VineArray schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineArray(this.#schema.clone(), this.cloneOptions(), this.cloneValidations()) as this\n }\n /**", "score": 0.9133337736129761 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n /**\n * Clones the VineRecord schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineRecord(\n this.#schema.clone(),\n this.cloneOptions(),\n this.cloneValidations()", "score": 0.909537136554718 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " super(options, validations || [booleanRule(options || {})])\n }\n /**\n * Clones the VineBoolean schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineBoolean(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 0.9081658124923706 }, { "filename": "src/schema/accepted/main.ts", "retrieved_chunk": " }\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super(options, validations || [acceptedRule()])\n }\n /**\n * Clones the VineAccepted schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineAccepted(this.cloneOptions(), this.cloneValidations()) as this", "score": 0.9017014503479004 } ]
typescript
return new VineString(this.cloneOptions(), this.cloneValidations()) as this }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) { field.report(messages['record.maxLength'], 'record.maxLength', field, options) } }) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) {
field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) }
}) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>( (value, callback, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.947120189666748 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.9350013136863708 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.893478274345398 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 0.8838374614715576 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 0.8812289237976074 } ]
typescript
field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return }
if (!helpers.isEmail(value as string, options)) {
field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Trims whitespaces around the string value\n */\n trim() {\n return this.use(trimRule())\n }\n /**\n * Normalizes the email address\n */\n normalizeEmail(options?: NormalizeEmailOptions) {", "score": 0.8671472072601318 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8584539294242859 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8583807349205017 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.855675458908081 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8500540256500244 } ]
typescript
if (!helpers.isEmail(value as string, options)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) {
field.report(messages['record.maxLength'], 'record.maxLength', field, options) }
}) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) { field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) } }) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>( (value, callback, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.9181800484657288 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.9117162823677063 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 0.907805323600769 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.9049270153045654 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.8947860598564148 } ]
typescript
field.report(messages['record.maxLength'], 'record.maxLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any'
if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) {
field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8501639366149902 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8458181619644165 }, { "filename": "src/types.ts", "retrieved_chunk": "import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js'\nimport type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js'\nimport type { PostalCodeLocale } from 'validator/lib/isPostalCode.js'\nimport type { helpers } from './vine/helpers.js'\nimport type { ValidationError } from './errors/validation_error.js'\nimport type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js'\n/**\n * Options accepted by the mobile number validation\n */\nexport type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions", "score": 0.8409867882728577 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.8405833840370178 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.8380758762359619 } ]
typescript
if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (
!helpers.isHexColor(value as string)) {
field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/vine/helpers.ts", "retrieved_chunk": " /**\n * Check if the value is a valid color hexcode\n */\n isHexColor: (value: string) => {\n if (!value.startsWith('#')) {\n return false\n }\n return isHexColor.default(value)\n },\n /**", "score": 0.8671540021896362 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8553982973098755 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 0.8490224480628967 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Ensure the array is not empty\n */\nexport const notEmptyRule = createRule<undefined>((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8448430299758911 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "/**\n * Enforce the value is a positive number\n */\nexport const positiveRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }", "score": 0.8431978821754456 } ]
typescript
!helpers.isHexColor(value as string)) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) {
return this.use(urlRule(...args)) }
/** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if (!helpers.isHexColor(value as string)) {\n field.report(messages.hexCode, 'hexCode', field)\n }\n})\n/**\n * Validates the value to be a valid URL\n */\nexport const urlRule = createRule<URLOptions | undefined>((value, options, field) => {\n if (!field.isValid) {", "score": 0.8666493892669678 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " */\nexport const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>(\n (value, options, field) => {\n if (!field.isValid) {\n return\n }\n field.mutate(normalizeUrl(value as string, options), field)\n }\n)\n/**", "score": 0.8637183308601379 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " */\nexport const stringRule = createRule((value, _, field) => {\n if (typeof value !== 'string') {\n field.report(messages.string, 'string', field)\n }\n})\n/**\n * Validates the value to be a valid email address\n */\nexport const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {", "score": 0.8550231456756592 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 0.8510584831237793 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 0.8501251935958862 } ]
typescript
return this.use(urlRule(...args)) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) { field.report(messages['record.maxLength'], 'record.maxLength', field, options) } }) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) { field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) } }) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>(
(value, callback, field) => {
/** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " * Enforce a fixed length on an object field\n */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Register a callback to validate the object keys\n */\n validateKeys(...args: Parameters<typeof validateKeysRule>) {\n return this.use(validateKeysRule(...args))", "score": 0.8666743040084839 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\n if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 0.8581992387771606 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 0.8564401865005493 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 0.8512134552001953 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8465428352355957 } ]
typescript
(value, callback, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (
!helpers.isIP(value as string, options?.version)) {
field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n mobile(...args: Parameters<typeof mobileRule>) {\n return this.use(mobileRule(...args))\n }\n /**\n * Validates the value to be a valid IP address.\n */\n ipAddress(version?: 4 | 6) {\n return this.use(ipAddressRule(version ? { version } : undefined))\n }", "score": 0.8825576305389404 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8573094606399536 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8443803787231445 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8418930768966675 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.8411005735397339 } ]
typescript
!helpers.isIP(value as string, options?.version)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) {
field.report(messages.mobile, 'mobile', field) }
}) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/types.ts", "retrieved_chunk": "import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js'\nimport type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js'\nimport type { PostalCodeLocale } from 'validator/lib/isPostalCode.js'\nimport type { helpers } from './vine/helpers.js'\nimport type { ValidationError } from './errors/validation_error.js'\nimport type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js'\n/**\n * Options accepted by the mobile number validation\n */\nexport type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions", "score": 0.8455413579940796 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8447631597518921 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8444741368293762 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8441728949546814 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 0.839522659778595 } ]
typescript
field.report(messages.mobile, 'mobile', field) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.
regex, 'regex', field) }
}) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/accepted/rules.ts", "retrieved_chunk": "export const acceptedRule = createRule((value, _, field) => {\n if (!ACCEPTED_VALUES.includes(value as any)) {\n field.report(messages.accepted, 'accepted', field)\n }\n})", "score": 0.8446720838546753 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 0.8432146906852722 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8415334820747375 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.8244566917419434 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.814917266368866 } ]
typescript
regex, 'regex', field) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */
export const regexRule = createRule<RegExp>((value, expression, field) => {
if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {", "score": 0.8604892492294312 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8488321900367737 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 0.8333301544189453 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 0.8326601386070251 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.8325798511505127 } ]
typescript
export const regexRule = createRule<RegExp>((value, expression, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return }
if (!(await helpers.isActiveURL(value as string))) {
field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid URL\n */\n url(...args: Parameters<typeof urlRule>) {\n return this.use(urlRule(...args))\n }\n /**\n * Validates the value to be an active URL\n */\n activeUrl() {", "score": 0.8931618332862854 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 0.8561845421791077 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Ensure the array is not empty\n */\nexport const notEmptyRule = createRule<undefined>((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.8468042612075806 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "/**\n * Enforce the value is a positive number\n */\nexport const positiveRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }", "score": 0.8266587853431702 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(activeUrlRule())\n }\n /**\n * Validates the value to be a valid email address\n */\n email(...args: Parameters<typeof emailRule>) {\n return this.use(emailRule(...args))\n }\n /**\n * Validates the value to be a valid mobile number", "score": 0.8234805464744568 } ]
typescript
if (!(await helpers.isActiveURL(value as string))) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) {
field.report(messages.minLength, 'minLength', field, options) }
}) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.9654868841171265 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.9323164224624634 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an array field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.9287720322608948 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.9066268801689148 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.9020000100135803 } ]
typescript
field.report(messages.minLength, 'minLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) {
field.report(messages.startsWith, 'startsWith', field, options) }
}) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.8819154500961304 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.8638491034507751 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an array field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 0.8615385293960571 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.8521905541419983 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 0.8517717123031616 } ]
typescript
field.report(messages.startsWith, 'startsWith', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) {
field.report(messages.maxLength, 'maxLength', field, options) }
}) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 0.9619582295417786 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 0.9579280614852905 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {", "score": 0.9182708263397217 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 0.9091113805770874 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {", "score": 0.9016754031181335 } ]
typescript
field.report(messages.maxLength, 'maxLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages
.sameAs, 'sameAs', field, options) return }
}) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " */\n if (typeof options.expectedValue === 'boolean') {\n input = helpers.asBoolean(value)\n } else if (typeof options.expectedValue === 'number') {\n input = helpers.asNumber(value)\n }\n /**\n * Performing validation and reporting error\n */\n if (input !== options.expectedValue) {", "score": 0.8747050762176514 }, { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " field.report(messages.literal, 'literal', field, options)\n return\n }\n /**\n * Mutating input with normalized value\n */\n field.mutate(input, field)\n})", "score": 0.8714267611503601 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.86173415184021 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 0.8586868047714233 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 0.8573590517044067 } ]
typescript
.sameAs, 'sameAs', field, options) return }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(
messages.in, 'in', field, options) return }
} ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8975601196289062 }, { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " */\n if (typeof options.expectedValue === 'boolean') {\n input = helpers.asBoolean(value)\n } else if (typeof options.expectedValue === 'number') {\n input = helpers.asNumber(value)\n }\n /**\n * Performing validation and reporting error\n */\n if (input !== options.expectedValue) {", "score": 0.8624483346939087 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 0.8568239808082581 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.854739785194397 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length < options.min) {\n field.report(messages['record.minLength'], 'record.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an object field", "score": 0.8516035079956055 } ]
typescript
messages.in, 'in', field, options) return }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else {
const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 0.8154991865158081 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length <= 0) {\n field.report(messages.notEmpty, 'notEmpty', field)\n }\n})\n/**", "score": 0.8089407682418823 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(inRule({ choices }))\n }\n /**\n * Ensure the field's value under validation is not inside the pre-defined list.\n */\n notIn(list: string[] | ((field: FieldContext) => string[])) {\n return this.use(notInRule({ list }))\n }\n /**\n * Validates the value to be a valid credit card number", "score": 0.8050269484519958 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 0.8022496700286865 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " if ((value as number) < 0) {\n field.report(messages.positive, 'positive', field)\n }\n})\n/**\n * Enforce the value is a negative number\n */\nexport const negativeRule = createRule<undefined>((value, _, field) => {\n /**\n * Skip if the field is not valid.", "score": 0.8018897771835327 } ]
typescript
const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization (
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) {
const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 0.9252673387527466 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 0.9095532298088074 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], _overrides?: AwsServiceOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);\n this.cost = await this.getNatGatewayPrice(credentials); \n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);\n }\n }", "score": 0.908288836479187 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " {\n Name: 'ClusterName',\n Value: service.clusterArn?.split('/').pop()\n }]);\n });\n }\n console.info('this.utilization:\\n', JSON.stringify(this.utilization, null, 2));\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides", "score": 0.8983502388000488 }, { "filename": "src/aws-utilization-provider.ts", "retrieved_chunk": " }\n async getUtilization (\n credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {}\n ) {\n for (const service of this.services) {\n const serviceOverrides = overrides[service];\n if (serviceOverrides?.forceRefesh) {\n this.utilization[service] = await this.refreshUtilizationData(\n service, credentialsProvider, region, serviceOverrides\n );", "score": 0.8893487453460693 } ]
typescript
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) {
import React from 'react'; import { Box, Heading, Text, SimpleGrid } from '@chakra-ui/react'; import { ActionType, HistoryEvent, Utilization } from '../types/types.js'; import { filterUtilizationForActionType, getNumberOfResourcesFromFilteredActions, getTotalMonthlySavings, getTotalNumberOfResources } from '../utils/utilization.js'; export default function RecommendationOverview ( props: { utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] } ) { const { utilizations, sessionHistory } = props; const { totalUnusedResources, totalMonthlySavings, totalResources } = getTotalRecommendationValues(utilizations, sessionHistory); const labelStyles = { fontFamily: 'Inter', fontSize: '42px', fontWeight: '400', lineHeight: '150%', color: '#000000' }; const textStyles = { fontFamily: 'Inter', fontSize: '14px', fontWeight: '500', lineHeight: '150%', color: 'rgba(0, 0, 0, 0.48)' }; return ( <SimpleGrid columns={3} spacing={2}> <Box p={5}> <Heading style={labelStyles}>{totalResources}</Heading> <Text style={textStyles}>{'resources'}</Text> </Box> <Box p={5}> <Heading style={labelStyles}>{totalUnusedResources}</Heading> <Text style={textStyles}>{'unused resources'}</Text> </Box> <Box p={5}> <Heading style={labelStyles}>{ totalMonthlySavings }</Heading> <Text style={textStyles}>{'potential monthly savings'}</Text> </Box> </SimpleGrid> ); } function getTotalRecommendationValues ( utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] ) {
const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);
const totalUnusedResources = getNumberOfResourcesFromFilteredActions(deleteChanges); const totalResources = getTotalNumberOfResources(utilizations); const totalMonthlySavings = getTotalMonthlySavings(utilizations); return { totalUnusedResources, totalMonthlySavings, totalResources }; }
src/components/recommendation-overview.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import { ActionType } from '../../types/types.js';\nimport { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js';\nimport { TbRefresh } from 'react-icons/tb/index.js';\nexport function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) {\n const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props;\n const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory);\n const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory);\n const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory);\n const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges);", "score": 0.8674880266189575 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 0.8648488521575928 }, { "filename": "src/widgets/utilization-recommendations-ui/utilization-recommendations-ui.tsx", "retrieved_chunk": "}\nexport function UtilizationRecommendationsUi (props: UtilizationRecommendationsUiProps) {\n const { utilization, sessionHistory, onResourcesAction, onRefresh, allRegions, region, onRegionChange } = props;\n const [wizardStep, setWizardStep] = useState<string>(WizardSteps.SUMMARY);\n const [selectedResourceArns, setSelectedResourceArns] = useState<string[]>([]);\n const [actionType, setActionType] = useState<ActionType>(ActionType.DELETE);\n if (wizardStep === WizardSteps.SUMMARY) {\n return (\n <RecommendationsActionSummary\n utilization={utilization}", "score": 0.8570460677146912 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": " });\n return total;\n}\nexport function getTotalMonthlySavings (utilization: { [service: string]: Utilization<string> }): string { \n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD'\n });\n let totalSavings = 0; \n Object.keys(utilization).forEach((service) => {", "score": 0.8556264638900757 }, { "filename": "src/widgets/utilization-recommendations-ui/confirm-recommendations.tsx", "retrieved_chunk": "export function ConfirmRecommendations (props: ConfirmRecommendationsProps) {\n const { actionType, resourceArns, onRemoveResource, onResourcesAction, utilization, sessionHistory } = props;\n const { isOpen, onOpen, onClose } = useDisclosure();\n const [confirmationText, setConfirmationText] = useState<string>('');\n const [error, setError] = useState<string | undefined>(undefined);\n const actionLabel = actionTypeText[actionType].charAt(0).toUpperCase() + actionTypeText[actionType].slice(1);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const resourceFilteredServices = new Set<string>();\n Object.entries(filteredServices).forEach(([serviceName, serviceUtil]) => {\n for (const resourceArn of resourceArns) {", "score": 0.8514325618743896 } ]
typescript
const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);
import cached from 'cached'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { BaseProvider } from '@tinystacks/ops-core'; import { ActionType, AwsResourceType, AwsServiceOverrides, AwsUtilizationOverrides, HistoryEvent, Utilization } from './types/types.js'; import { AwsServiceUtilization } from './service-utilizations/aws-service-utilization.js'; import { AwsServiceUtilizationFactory } from './service-utilizations/aws-service-utilization-factory.js'; import { AwsUtilizationProvider as AwsUtilizationProviderType } from './ops-types.js'; const utilizationCache = cached<Utilization<string>>('utilization', { backend: { type: 'memory' } }); const sessionHistoryCache = cached<Array<HistoryEvent>>('session-history', { backend: { type: 'memory' } }); type AwsUtilizationProviderProps = AwsUtilizationProviderType & { utilization?: { [key: AwsResourceType | string]: Utilization<string> }; region?: string; }; class AwsUtilizationProvider extends BaseProvider { static type = 'AwsUtilizationProvider'; services: AwsResourceType[]; utilizationClasses: { [key: AwsResourceType | string]: AwsServiceUtilization<string> }; utilization: { [key: AwsResourceType | string]: Utilization<string> }; region: string; constructor (props: AwsUtilizationProviderProps) { super(props); const { services } = props; this.utilizationClasses = {}; this.utilization = {}; this.initServices(services || [ 'Account', 'CloudwatchLogs', 'Ec2Instance', 'EcsService', 'NatGateway', 'S3Bucket', 'EbsVolume', 'RdsInstance' ]); } static fromJson (props: AwsUtilizationProviderProps) { return new AwsUtilizationProvider(props); } toJson (): AwsUtilizationProviderProps { return { ...super.toJson(), services: this.services, utilization: this.utilization }; } initServices (services: AwsResourceType[]) { this.services = services; for (const service of this.services) {
this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);
} } async refreshUtilizationData ( service: AwsResourceType, credentialsProvider: AwsCredentialsProvider, region: string, overrides?: AwsServiceOverrides ): Promise<Utilization<string>> { try { await this.utilizationClasses[service]?.getUtilization(credentialsProvider, [ region ], overrides); return this.utilizationClasses[service]?.utilization; } catch (e) { console.error(e); return {}; } } async doAction ( service: AwsResourceType, credentialsProvider: AwsCredentialsProvider, actionName: string, actionType: ActionType, resourceArn: string, region: string ) { const event: HistoryEvent = { service, actionType, actionName, resourceArn, region, timestamp: new Date().toISOString() }; const history: HistoryEvent[] = await this.getSessionHistory(); history.push(event); await this.utilizationClasses[service].doAction(credentialsProvider, actionName, resourceArn, region); await sessionHistoryCache.set('history', history); } async hardRefresh ( credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {} ) { for (const service of this.services) { const serviceOverrides = overrides[service]; this.utilization[service] = await this.refreshUtilizationData( service, credentialsProvider, region, serviceOverrides ); await utilizationCache.set(service, this.utilization[service]); } return this.utilization; } async getUtilization ( credentialsProvider: AwsCredentialsProvider, region: string, overrides: AwsUtilizationOverrides = {} ) { for (const service of this.services) { const serviceOverrides = overrides[service]; if (serviceOverrides?.forceRefesh) { this.utilization[service] = await this.refreshUtilizationData( service, credentialsProvider, region, serviceOverrides ); await utilizationCache.set(service, this.utilization[service]); } else { this.utilization[service] = await utilizationCache.getOrElse( service, async () => await this.refreshUtilizationData(service, credentialsProvider, region, serviceOverrides) ); } } return this.utilization; } async getSessionHistory (): Promise<HistoryEvent[]> { return sessionHistoryCache.getOrElse('history', []); } } export { AwsUtilizationProvider };
src/aws-utilization-provider.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " if (overrides?.region) {\n this.region = overrides.region;\n await utilProvider.hardRefresh(awsCredsProvider, this.region);\n }\n this.utilization = await utilProvider.getUtilization(awsCredsProvider, this.region);\n if (overrides?.resourceActions) {\n const { actionType, resourceArns } = overrides.resourceActions;\n const resourceArnsSet = new Set<string>(resourceArns);\n const filteredServices = \n filterUtilizationForActionType(this.utilization, actionTypeToEnum[actionType], this.sessionHistory);", "score": 0.8645397424697876 }, { "filename": "src/widgets/aws-utilization-recommendations.tsx", "retrieved_chunk": " this.allRegions = props.allRegions;\n }\n static fromJson (props: AwsUtilizationRecommendationsProps) {\n return new AwsUtilizationRecommendations(props);\n }\n toJson () {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n sessionHistory: this.sessionHistory,", "score": 0.8518092036247253 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " }\n static fromJson (object: AwsUtilizationProps): AwsUtilization {\n return new AwsUtilization(object);\n }\n toJson (): AwsUtilizationProps {\n return {\n ...super.toJson(),\n utilization: this.utilization,\n region: this.region, \n sessionHistory: this.sessionHistory", "score": 0.851717472076416 }, { "filename": "src/widgets/aws-utilization.tsx", "retrieved_chunk": " region: string\n}\nexport class AwsUtilization extends BaseWidget {\n utilization: { [ serviceName: string ] : Utilization<string> };\n sessionHistory: HistoryEvent[];\n region: string;\n constructor (props: AwsUtilizationProps) {\n super(props);\n this.region = props.region || 'us-east-1';\n this.utilization = props.utilization || {};", "score": 0.84857177734375 }, { "filename": "src/service-utilizations/aws-service-utilization-factory.ts", "retrieved_chunk": "import { AwsEcsUtilization } from './aws-ecs-utilization.js';\nimport { AwsServiceUtilization } from './aws-service-utilization.js';\nexport class AwsServiceUtilizationFactory {\n static createObject (awsService: AwsResourceType): AwsServiceUtilization<string> {\n switch (awsService) {\n case AwsResourceTypes.CloudwatchLogs:\n return new AwsCloudwatchLogsUtilization();\n case AwsResourceTypes.S3Bucket: \n return new s3Utilization(); \n case AwsResourceTypes.RdsInstance: ", "score": 0.845947265625 } ]
typescript
this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);