feat: Reinitialize frontend with SvelteKit and TypeScript

- Delete old Vite+Svelte frontend
- Initialize new SvelteKit project with TypeScript
- Configure Tailwind CSS v4 + DaisyUI
- Implement JWT authentication with auto-refresh
- Create login page with form validation (Zod)
- Add protected route guards
- Update Docker configuration for single-stage build
- Add E2E tests with Playwright (6/11 passing)
- Fix Svelte 5 reactivity with $state() runes

Known issues:
- 5 E2E tests failing (timing/async issues)
- Token refresh implementation needs debugging
- Validation error display timing
This commit is contained in:
2026-02-17 16:19:59 -05:00
parent 54df6018f5
commit de2d83092e
28274 changed files with 3816354 additions and 90 deletions

9
frontend/node_modules/@vinejs/compiler/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,9 @@
# The MIT License
Copyright (c) 2023
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

126
frontend/node_modules/@vinejs/compiler/README.md generated vendored Normal file
View File

@@ -0,0 +1,126 @@
# @vinejs/compiler
[![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url]
The compiler is used to convert an array of schema nodes to a function with imperative JavaScript code that can be executed to validate a data object. The compiler operates at the low-level and does not offer any JavaScript API for creating the schema (see vinejs for user-land APIs).
## Benchmarks
Ajv performs better in some instances because Ajv holds a reference to the input data object and does not create a new output object. Though Ajv behavior results in slightly better performance, it comes at the cost of sharing the same pointers between the input and output objects, and hence mutating one will mutate the other as well.
![](./vinejs_benchmarks.png)
## Schema
Schema refers to an object or an array of objects that the compiler takes as an input to generate JavaScript output. Following is an example of an `object` schema node with `username` property.
```ts
{
type: 'root',
schema: {
type: 'object',
fieldName: '',
propertyName: '',
bail: true,
allowNull: false,
isOptional: false,
allowUnknownProperties: false,
properties: [
{
type: 'literal',
fieldName: 'username',
propertyName: 'userName',
transformFnId: 'ref://1',
parseFnId: 'ref://2',
bail: true,
allowNull: false,
isOptional: false,
validations: [
{
ruleFnId: 'ref://3',
isAsync: false,
implicit: false,
}
]
}
],
groups: [],
}
}
```
## What is `ref://x`?
Since, we pre-compile the schema to a string, we cannot serialize certain JavaScript datatypes like functions or complex objects. Therefore, we use a `refs` system, which works as follows.
- When you define a function or a complex data type inside your schema, we will generate a unique ref id for it.
- The compiler will receive the ref id (starting with `ref://`).
- At the time of validations, we will pass the refs key-value pair. The key will be ref id and the value will be the complex data type and the compiled output will lookup the ref value based upon the ref id.
Consider the following simplified flow of using refs.
![](./compiler_parsing_flow.png)
## Schema types
Following is the list of supported schema types.
- `literal`: Literal refers to any value that does not have children schema nodes. For example: `number`, `string`, `boolean`, `dates`, and so on. Custom data types like `file` can be a literal schema type.
- `object`: Object refers to a JavaScript Object data type. An object may have children schema nodes as well.
- `array`: Array refers to a JavaScript Array data type. An array may also define the schema node for the array elements.
- `tuple`: Tuple refers to a JavaScript Array data type. A tuple can define a separate schema for each array element.
- `union`: A union is a collection of conditions + schema. If the condition is `true` at runtime, the associated schema will validate the field.
- `record`: Record refers to a JavaScript Object data type with unknown keys. Each element of a record must have the same type.
## Schema moving parts
There are moving parts inside the schema nodes. These moving parts generate different outputs based on their state.
### Standalone moving parts
Standalone moving parts refers to conditions that act individually and does not get impacted if other moving parts are enabled or disabled.
- `parseFnId`: A function to convert the input value before the validation lifecycle of the input begins. The function receives the exact value of the input, so consider the value as `unknown`.
- `transformFnId`: A function to convert the output value after all the validations of the input field are over.
- The function can only be defined for the `literal` schema type.
- The function is invoked only when the value is written to the output. Any conditions that do not write value to the output will also skip calling the transform function.
- `allowUnknownProperties`: When enabled, the flag will keep all the properties of an object or an array. The children properties with schema are still validated and replaced, but other properties are deeply copied from the source to the output.
- `bail`: When enabled, the flag will stop validating the field after the first error. In the case of `arrays` and `objects`, the validation of children nodes will also be skipped.
### Dependent flags (optional and null)
Flags that behave differently when used together.
- `isOptional`: Mark the field under validation as optional. It means the field value can be `undefined` or `null`.
- `allowNull`: Mark the field under validation to be `null`, but not undefined. However, when both `isOptional` and `allowNull` flags are used, the undefined values will also be allowed.
The `null` values are written to the output when `allowNull` flag is enabled.
## Validations behavior
The validations are functions executed one after the other in the same sequence as they are registered in the schema. Following is the default behavior of validations.
- Validation functions are not executed if the value is `null` or `undefined` even when the field is marked as optional.
- You may use the `implicit` flag on the validation rule to make the validation run for `null` or `undefined` values as well.
- When the `bail` mode is enabled for the field, the next validation will not run if the previous one fails. There is no way for rules to bypass this behavior.
## Implicit rules
The validation rules are not executed by default when the field's value is `null` or `undefined`. However, the implicit rules can bypass this check by enabling the `implicit` flag inside the schema object.
## Writing value to the output
If the value of a field is `null` or `undefined` it will not be written to the output. However, the `null` values are written to the output when `allowNull` flag is enabled.
[gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/vinejs/compiler/checks.yml?style=for-the-badge
[gh-workflow-url]: https://github.com/vinejs/compiler/actions/workflows/test.yml 'Github action'
[npm-image]: https://img.shields.io/npm/v/@vinejs/compiler/latest.svg?style=for-the-badge&logo=npm
[npm-url]: https://www.npmjs.com/package/@vinejs/compiler/v/latest 'npm'
[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
[license-url]: LICENSE.md
[license-image]: https://img.shields.io/github/license/vinejs/compiler?style=for-the-badge

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
// factories/error_reporter.ts
var ValidationError = class extends Error {
};
var ErrorReporterFactory = class {
create() {
const reporter = {
messages: [],
hasErrors: false,
report(message) {
this.hasErrors = true;
this.messages.push(message);
},
createError() {
const error = new ValidationError("Validation failure");
error.messages = this.messages;
return error;
}
};
return reporter;
}
};
// factories/messages_provider.ts
var MessagesProviderFactory = class {
create() {
const provider = {
getMessage(defaultMessage) {
return defaultMessage;
}
};
return provider;
}
};
export {
ErrorReporterFactory,
MessagesProviderFactory
};

View File

@@ -0,0 +1,2 @@
export { Compiler } from './src/compiler/main.js';
export { refsBuilder } from './src/refs_builder.js';

51
frontend/node_modules/@vinejs/compiler/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
import {
Compiler
} from "./chunk-K5F7IOJS.js";
// src/refs_builder.ts
function refsBuilder() {
let counter = 0;
const refs = {};
return {
toJSON() {
return refs;
},
/**
* Track a value inside refs
*/
track(value) {
counter++;
const ref = `ref://${counter}`;
refs[ref] = value;
return ref;
},
/**
* Track a validation inside refs
*/
trackValidation(validation) {
return this.track(validation);
},
/**
* Track input value parser inside refs
*/
trackParser(fn) {
return this.track(fn);
},
/**
* Track output value transformer inside refs
*/
trackTransformer(fn) {
return this.track(fn);
},
/**
* Track a conditional inside refs
*/
trackConditional(fn) {
return this.track(fn);
}
};
}
export {
Compiler,
refsBuilder
};

View File

@@ -0,0 +1,26 @@
/**
* Compiler buffer to collect JS fragments in memory
*/
export declare class CompilerBuffer {
#private;
/**
* The character used to create a new line
*/
newLine: string;
/**
* Write statement ot the output
*/
writeStatement(statement: string): void;
/**
* Creates a child buffer
*/
child(): CompilerBuffer;
/**
* Returns the buffer contents as string
*/
toString(): string;
/**
* Flush in-memory string
*/
flush(): void;
}

View File

@@ -0,0 +1,2 @@
import type { CompilerField, CompilerParent } from '../../types.js';
export declare function createArrayField(parent: CompilerParent): CompilerField;

View File

@@ -0,0 +1,2 @@
import type { CompilerField, FieldNode, CompilerParent } from '../../types.js';
export declare function createObjectField(node: Pick<FieldNode, 'fieldName' | 'propertyName'>, variablesCounter: number, parent: CompilerParent): CompilerField;

View File

@@ -0,0 +1,2 @@
import type { CompilerField, CompilerParent } from '../../types.js';
export declare function createRecordField(parent: CompilerParent): CompilerField;

View File

@@ -0,0 +1,2 @@
import type { CompilerField, CompilerParent } from '../../types.js';
export declare function createRootField(parent: CompilerParent): CompilerField;

View File

@@ -0,0 +1,2 @@
import type { CompilerField, FieldNode, CompilerParent } from '../../types.js';
export declare function createTupleField(node: Pick<FieldNode, 'fieldName' | 'propertyName'>, parent: CompilerParent): CompilerField;

View File

@@ -0,0 +1,28 @@
import { CompilerBuffer } from './buffer.js';
import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact } from '../types.js';
/**
* Compiler is used to compile an array of schema nodes into a re-usable
* JavaScript.
*/
export declare class Compiler {
#private;
/**
* Variables counter is used to generate unique variable
* names with a counter suffix.
*/
variablesCounter: number;
constructor(rootNode: RootNode, options?: CompilerOptions);
/**
* Converts a node to a field. Optionally accepts a parent node to create
* a field for a specific parent type.
*/
createFieldFor(node: CompilerNodes, parent: CompilerParent): CompilerField;
/**
* Compiles a given compiler node
*/
compileNode(node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField): void;
/**
* Compile schema nodes to an async function
*/
compile(): (data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract) => Promise<Record<string, any>>;
}

View File

@@ -0,0 +1,12 @@
import { BaseNode } from './base.js';
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { CompilerField, CompilerParent, ArrayNode } from '../../types.js';
/**
* Compiles an array schema node to JS string output.
*/
export declare class ArrayNodeCompiler extends BaseNode {
#private;
constructor(node: ArrayNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
compile(): void;
}

View File

@@ -0,0 +1,9 @@
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { CompilerField, CompilerNodes, CompilerParent } from '../../types.js';
export declare abstract class BaseNode {
#private;
protected field: CompilerField;
constructor(node: CompilerNodes, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
protected defineField(buffer: CompilerBuffer): void;
}

View File

@@ -0,0 +1,12 @@
import { BaseNode } from './base.js';
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { LiteralNode, CompilerParent, CompilerField } from '../../types.js';
/**
* Compiles a literal schema node to JS string output.
*/
export declare class LiteralNodeCompiler extends BaseNode {
#private;
constructor(node: LiteralNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
compile(): void;
}

View File

@@ -0,0 +1,12 @@
import { BaseNode } from './base.js';
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { CompilerField, CompilerParent, ObjectNode } from '../../types.js';
/**
* Compiles an object schema node to JS string output.
*/
export declare class ObjectNodeCompiler extends BaseNode {
#private;
constructor(node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
compile(): void;
}

View File

@@ -0,0 +1,12 @@
import { BaseNode } from './base.js';
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { CompilerField, CompilerParent, RecordNode } from '../../types.js';
/**
* Compiles a record schema node to JS string output.
*/
export declare class RecordNodeCompiler extends BaseNode {
#private;
constructor(node: RecordNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
compile(): void;
}

View File

@@ -0,0 +1,12 @@
import { BaseNode } from './base.js';
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { CompilerField, CompilerParent, TupleNode } from '../../types.js';
/**
* Compiles a tuple schema node to JS string output.
*/
export declare class TupleNodeCompiler extends BaseNode {
#private;
constructor(node: TupleNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
compile(): void;
}

View File

@@ -0,0 +1,12 @@
import { BaseNode } from './base.js';
import type { Compiler } from '../main.js';
import type { CompilerBuffer } from '../buffer.js';
import type { CompilerField, CompilerParent, UnionNode } from '../../types.js';
/**
* Compiles a union schema node to JS string output.
*/
export declare class UnionNodeCompiler extends BaseNode {
#private;
constructor(node: UnionNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField);
compile(): void;
}

View File

@@ -0,0 +1,4 @@
/**
* Converts the value to a valid JavaScript variable name
*/
export declare function toVariableName(value: string): string;

View File

@@ -0,0 +1,5 @@
import type { RefsStore } from './types.js';
/**
* Creates a refs store for parsing the schema
*/
export declare function refsBuilder(): RefsStore;

View File

@@ -0,0 +1,9 @@
type ArrayGuardOptions = {
variableName: string;
guardedCodeSnippet: string;
};
/**
* Returns JS fragment to wrap code inside an array conditional
*/
export declare function defineArrayGuard({ variableName, guardedCodeSnippet }: ArrayGuardOptions): string;
export {};

View File

@@ -0,0 +1,13 @@
/**
* Options accepts by the output script
*/
type OutputOptions = {
variableName: string;
outputExpression: string;
outputValueExpression: string;
};
/**
* Returns JS fragment for writing the initial output for an array
*/
export declare function defineArrayInitialOutput({ variableName, outputExpression, outputValueExpression, }: OutputOptions): string;
export {};

View File

@@ -0,0 +1,13 @@
/**
* Options accepts by the loop script
*/
type ArrayLoopOptions = {
variableName: string;
loopCodeSnippet: string;
startingIndex?: number;
};
/**
* Returns JS fragment for wrapping code inside an array loop
*/
export declare function defineArrayLoop({ variableName, loopCodeSnippet, startingIndex, }: ArrayLoopOptions): string;
export {};

View File

@@ -0,0 +1,8 @@
type FieldOptions = {
variableName: string;
};
/**
* Returns JS fragment for defining the array variables
*/
export declare function defineArrayVariables({ variableName }: FieldOptions): string;
export {};

View File

@@ -0,0 +1,11 @@
type ConditionalGuardOptions = {
variableName: string;
conditionalFnRefId: string;
guardedCodeSnippet: string;
conditional: 'if' | 'else if';
};
/**
* Returns JS fragment to wrap code inside a conditional guard
*/
export declare function defineConditionalGuard({ conditional, variableName, conditionalFnRefId, guardedCodeSnippet, }: ConditionalGuardOptions): string;
export {};

View File

@@ -0,0 +1,9 @@
type ConditionalGuardOptions = {
variableName: string;
conditionalFnRefId: string;
};
/**
* Returns JS fragment to invoke a function inside else block
*/
export declare function defineElseCondition({ variableName, conditionalFnRefId }: ConditionalGuardOptions): string;
export {};

View File

@@ -0,0 +1,6 @@
import { CompilerOptions } from '../types.js';
/**
* Returns JS fragment for inline error messages for errors raised
* by the compiler.
*/
export declare function defineInlineErrorMessages(messages: Required<Exclude<CompilerOptions['messages'], undefined>>): string;

View File

@@ -0,0 +1,7 @@
/**
* Returns JS fragment for inline function needed by the
* validation runtime code.
*/
export declare function defineInlineFunctions(options: {
convertEmptyStringsToNull: boolean;
}): string;

View File

@@ -0,0 +1,10 @@
type FieldOptions = {
variableName: string;
isOptional: boolean;
allowNull: boolean;
};
/**
* Returns JS fragment to validate a field's value for existence.
*/
export declare function defineFieldExistenceValidations({ allowNull, isOptional, variableName, }: FieldOptions): string;
export {};

View File

@@ -0,0 +1,10 @@
type ObjectGuardOptions = {
variableName: string;
bail: boolean;
guardedCodeSnippet: string;
};
/**
* Returns JS fragment to wrap code inside a valid guard
*/
export declare function defineIsValidGuard({ variableName, bail, guardedCodeSnippet }: ObjectGuardOptions): string;
export {};

View File

@@ -0,0 +1,16 @@
import { RefIdentifier } from '../../types.js';
/**
* Options accepts by the output script
*/
type OutputOptions = {
outputExpression: string;
variableName: string;
allowNull: boolean;
transformFnRefId?: RefIdentifier;
conditional?: 'if' | 'else if';
};
/**
* Returns JS fragment for writing the null value to the output.
*/
export declare function defineFieldNullOutput({ allowNull, conditional, variableName, outputExpression, transformFnRefId, }: OutputOptions): string;
export {};

View File

@@ -0,0 +1,24 @@
import { ValidationNode } from '../../types.js';
/**
* Options accepts by the validation script
*/
type ValidationOptions = {
bail: boolean;
variableName: string;
validations: ValidationNode[];
/**
* Drop missing conditional check regardless of whether
* rule is implicit or not
*/
dropMissingCheck: boolean;
/**
* The expression to use for performing the existence check.
* Defaults to "item.isDefined"
*/
existenceCheckExpression?: string;
};
/**
* Returns JS fragment for executing validations for a given field.
*/
export declare function defineFieldValidations({ bail, validations, variableName, dropMissingCheck, existenceCheckExpression, }: ValidationOptions): string;
export {};

View File

@@ -0,0 +1,14 @@
import { RefIdentifier } from '../../types.js';
/**
* Options accepts by the output script
*/
type OutputOptions = {
outputExpression: string;
variableName: string;
transformFnRefId?: RefIdentifier;
};
/**
* Returns JS fragment for writing the validated value to the output.
*/
export declare function defineFieldValueOutput({ variableName, outputExpression, transformFnRefId, }: OutputOptions): string;
export {};

View File

@@ -0,0 +1,18 @@
import { RefIdentifier } from '../../types.js';
type FieldOptions = {
parentExpression: string;
variableName: string;
valueExpression: string;
fieldNameExpression: string;
wildCardPath: string;
parentValueExpression: string;
isArrayMember: boolean;
parseFnRefId?: RefIdentifier;
};
/**
* Returns JS fragment for defining the field variables. It includes, the field
* value variable, context variable, and a boolean to know if the field
* exists.
*/
export declare function defineFieldVariables({ parseFnRefId, variableName, wildCardPath, isArrayMember, valueExpression, parentExpression, fieldNameExpression, parentValueExpression, }: FieldOptions): string;
export {};

View File

@@ -0,0 +1,9 @@
type ObjectGuardOptions = {
variableName: string;
guardedCodeSnippet: string;
};
/**
* Returns JS fragment to wrap code inside an object conditional
*/
export declare function defineObjectGuard({ variableName, guardedCodeSnippet }: ObjectGuardOptions): string;
export {};

View File

@@ -0,0 +1,13 @@
/**
* Options accepts by the output script
*/
type OutputOptions = {
variableName: string;
outputExpression: string;
outputValueExpression: string;
};
/**
* Returns JS fragment for writing the initial output for an object
*/
export declare function defineObjectInitialOutput({ variableName, outputExpression, outputValueExpression, }: OutputOptions): string;
export {};

View File

@@ -0,0 +1,14 @@
/**
* Options accepts by the output script
*/
type MovePropertiesOptions = {
variableName: string;
allowUnknownProperties: boolean;
fieldsToIgnore: string[];
};
/**
* Returns JS fragment for moving properties from the source
* to destination
*/
export declare function defineMoveProperties({ variableName, fieldsToIgnore, allowUnknownProperties, }: MovePropertiesOptions): string;
export {};

View File

@@ -0,0 +1,8 @@
type FieldOptions = {
variableName: string;
};
/**
* Returns JS fragment for defining the object variables
*/
export declare function defineObjectVariables({ variableName }: FieldOptions): string;
export {};

View File

@@ -0,0 +1,12 @@
/**
* Options accepts by the loop script
*/
type RecordLoopOptions = {
variableName: string;
loopCodeSnippet: string;
};
/**
* Returns JS fragment for wrapping code inside an record loop
*/
export declare function defineRecordLoop({ variableName, loopCodeSnippet }: RecordLoopOptions): string;
export {};

View File

@@ -0,0 +1,4 @@
/**
* Returns JS fragment to report errors
*/
export declare function reportErrors(): string;

View File

@@ -0,0 +1,11 @@
import type { RefIdentifier } from '../../types.js';
type FieldOptions = {
variableName: string;
parseFnRefId?: RefIdentifier;
};
/**
* Returns JS fragment to call the parse function on the union conditional
* schema.
*/
export declare function callParseFunction({ parseFnRefId, variableName }: FieldOptions): string;
export {};

View File

@@ -0,0 +1,427 @@
/**
* Represenation of a ref id
*/
export type RefIdentifier = `ref://${number}`;
/**
* Allowed values for refs
*/
export type Refs = Record<RefIdentifier, ValidationRule | TransformFn<any, any> | ParseFn | ConditionalFn<any>>;
/**
* Refs store to track runtime values as refs with
* type safety
*/
export type RefsStore = {
toJSON(): Refs;
/**
* Track a value inside refs
*/
track(value: Refs[keyof Refs]): RefIdentifier;
/**
* Track a validation inside refs
*/
trackValidation(validation: ValidationRule): RefIdentifier;
/**
* Track input value parser inside refs
*/
trackParser(fn: ParseFn): RefIdentifier;
/**
* Track output value transformer inside refs
*/
trackTransformer(fn: TransformFn<any, any>): RefIdentifier;
/**
* Track a conditional inside refs
*/
trackConditional(fn: ConditionalFn<any>): RefIdentifier;
};
/**
* The context shared with the entire validation pipeline.
* Each field gets its own context object.
*/
export type FieldContext = {
/**
* Field value
*/
value: unknown;
/**
* The data property is the top-level object under validation.
*/
data: any;
/**
* Shared metadata across the entire validation lifecycle. It can be
* used to pass data between validation rules
*/
meta: Record<string, any>;
/**
* Mutate the value of field under validation.
*/
mutate(newValue: any, field: FieldContext): void;
/**
* Report error to the error reporter
*/
report: ErrorReporterContract['report'];
/**
* Is this field valid. Default: true
*/
isValid: boolean;
/**
* Is this field has value defined.
*/
isDefined: boolean;
/**
* Returns the nested path to the field. The parts
* are joined by a dot notation.
*/
getFieldPath(): string;
/**
* Wildcard path for the field. The value is a nested
* pointer to the field under validation.
*
* In case of arrays, the `*` wildcard is used.
*/
wildCardPath: string;
/**
* The parent property is the parent of the field. It could be an
* array or an object.
*/
parent: any;
/**
* Name of the field under validation. In case of an array, the field
* name will be a number
*/
name: string | number;
/**
* Is this field an array member
*/
isArrayMember: boolean;
};
/**
* The shape of validation rule picked from the
* refs
*/
export type ValidationRule = {
/**
* Performs validation
*/
validator(value: unknown, options: any, field: FieldContext): any;
/**
* Options to pass
*/
options?: any;
};
/**
* The shape of parse function picked from the refs
*/
export type ParseFn = (value: unknown, ctx: Pick<FieldContext, 'data' | 'parent' | 'meta'>) => any;
/**
* The shape of transform function picked from the refs
*/
export type TransformFn<Input, Output> = (value: Input, field: FieldContext) => Output;
/**
* The shape of conditional function used for narrowing down unions.
*/
export type ConditionalFn<Input> = (value: Input, field: FieldContext) => boolean;
/**
* Shape of a validation rule accepted by the compiler
*/
export type ValidationNode = {
/**
* Rule implementation function id.
*/
ruleFnId: RefIdentifier;
/**
* Is this an async rule. This flag helps creating an optimized output
*/
isAsync: boolean;
/**
* The rules are skipped when the value of a field is "null" or "undefined".
* Unless, the "implicit" flag is true
*/
implicit: boolean;
};
/**
* Shape of field inside a schema.
*/
export type FieldNode = {
/**
* Should the validation cycle stop after the first error.
* Defaults to true
*/
bail: boolean;
/**
* Field name refers to the name of the field under the data
* object
*/
fieldName: string;
/**
* Name of the output property. This allows validating a field with a different name, but
* storing its output value with a different name.
*/
propertyName: string;
/**
* Are we expecting this field to be undefined or null
*/
isOptional: boolean;
/**
* Are we expecting this field to be null
*/
allowNull: boolean;
/**
* The reference id for the parse method. Parse method is called to mutate the
* initial value. The function is executed always even when value is undefined
* or null.
*
* @see [[ParseFn]]
*/
parseFnId?: RefIdentifier;
/**
* A set of validations to apply on the field
*/
validations: ValidationNode[];
};
/**
* Shape of a single field accepted by the compiler
*/
export type LiteralNode = FieldNode & {
type: 'literal';
/**
* Transform the output value of a field. The output of this method is the
* final source of truth. The function is executed at the time of writing the
* value to the output.
*/
transformFnId?: RefIdentifier;
};
/**
* Shape of the object node accepted by the compiler
*/
export type ObjectNode = FieldNode & {
type: 'object';
/**
* Whether or not to allow unknown properties. When disabled, the
* output object will have only validated properties.
*
* Default: false
*/
allowUnknownProperties: boolean;
/**
* Object known properties
*/
properties: CompilerNodes[];
/**
* A collection of object groups to merge into the main object.
* Each group is a collection of conditionals with a sub-object
* inside them.
*/
groups: ObjectGroupNode[];
};
/**
* A compiler object group produces a single sub object based upon
* the defined conditions.
*/
export type ObjectGroupNode = {
type: 'group';
/**
* An optional function to call when all of the conditions
* are false.
*/
elseConditionalFnRefId?: RefIdentifier;
/**
* Conditions to evaluate
*/
conditions: {
/**
* The conditional function reference id
*/
conditionalFnRefId: RefIdentifier;
/**
* Schema to use when condition is true
*/
schema: {
type: 'sub_object';
/**
* Object known properties
*/
properties: CompilerNodes[];
/**
* A collection of object groups to merge into the main object.
* Each group is a collection of conditionals with a sub-object
* inside them.
*/
groups: ObjectGroupNode[];
};
}[];
};
/**
* Shape of the tuple node accepted by the compiler
*/
export type TupleNode = FieldNode & {
type: 'tuple';
/**
* Whether or not to allow unknown properties. When disabled, the
* output array will have only validated properties.
*
* Default: false
*/
allowUnknownProperties: boolean;
/**
* Tuple known properties
*/
properties: CompilerNodes[];
};
/**
* Shape of the record node accepted by the compiler
*/
export type RecordNode = FieldNode & {
type: 'record';
/**
* Captures object elements
*/
each: CompilerNodes;
};
/**
* Shape of the array node accepted by the compiler
*/
export type ArrayNode = FieldNode & {
type: 'array';
/**
* Captures array elements
*/
each: CompilerNodes;
};
/**
* Shape of the union node accepted by the compiler. A union is a combination
* of conditionals.
*/
export type UnionNode = {
type: 'union';
/**
* Field name refers to the name of the field under the data
* object
*/
fieldName: string;
/**
* Name of the output property. This allows validating a field with a different name, but
* storing its value with a different name.
*/
propertyName: string;
/**
* An optional function to call when all of the conditions
* are false.
*/
elseConditionalFnRefId?: RefIdentifier;
/**
* Conditions to evaluate
*/
conditions: {
/**
* The conditional function reference id
*/
conditionalFnRefId: RefIdentifier;
/**
* Schema to use when condition is true
*/
schema: CompilerNodes;
}[];
};
/**
* The root of the schema
*/
export type RootNode = {
type: 'root';
/**
* Schema at the root level
*/
schema: CompilerNodes;
};
/**
* Known tree nodes accepted by the compiler
*/
export type CompilerNodes = LiteralNode | ObjectNode | ArrayNode | UnionNode | RecordNode | TupleNode;
/**
* Properties of a parent node as the compiler loops through the
* rules tree and constructs JS code.
*/
export type CompilerParent = {
type: 'array' | 'object' | 'tuple' | 'record' | 'root';
/**
* Wildcard path to the field
*/
wildCardPath: string;
/**
* Name of the variable for the parent property. The variable name
* is used to lookup values from the parent
*/
variableName: string;
/**
* Nested path to the parent field. If the parent is nested inside
* an object or array.
*/
fieldPathExpression: string;
/**
* The expression for the output value.
*/
outputExpression: string;
};
/**
* Compiler field is used to compute the variable and property
* names for the JS output.
*/
export type CompilerField = {
parentExpression: string;
parentValueExpression: string;
fieldNameExpression: string;
fieldPathExpression: string;
variableName: string;
wildCardPath: string;
valueExpression: string;
outputExpression: string;
isArrayMember: boolean;
};
/**
* The error reporter is used for reporting validation
* errors.
*/
export interface ErrorReporterContract {
/**
* A boolean to known if there are one or more
* errors.
*/
hasErrors: boolean;
/**
* Creates an instance of an exception to throw
*/
createError(): Error;
/**
* Report error for a field
*/
report(message: string, rule: string, field: FieldContext, args?: Record<string, any>): any;
}
/**
* Messages provider is used to resolve validation error messages
* during validation.
*/
export interface MessagesProviderContact {
/**
* Returns a validation message for a given field + rule. The args
* may get passed by a validation rule to share additional context.
*/
getMessage(defaultMessage: string, rule: string, field: FieldContext, args?: Record<string, any>): string;
}
/**
* Options accepted by the compiler
*/
export type CompilerOptions = {
/**
* Convert empty string values to null for sake of
* normalization
*/
convertEmptyStringsToNull: boolean;
/**
* Provide messages to use for required, object and
* array validations.
*/
messages?: Partial<{
required: string;
object: string;
array: string;
}>;
};

View File

129
frontend/node_modules/@vinejs/compiler/package.json generated vendored Normal file
View File

@@ -0,0 +1,129 @@
{
"name": "@vinejs/compiler",
"version": "3.0.0",
"description": "Low level compiler for VineJS validator",
"type": "module",
"main": "build/index.js",
"files": [
"build",
"!build/benchmarks",
"!build/bin",
"!build/examples",
"!build/factories",
"!build/tests"
],
"exports": {
".": "./build/index.js",
"./types": "./build/src/types.js"
},
"scripts": {
"pretest": "npm run lint",
"test": "c8 npm run quick:test",
"lint": "eslint",
"format": "prettier --write .",
"typecheck": "tsc --noEmit",
"clean": "del-cli build",
"precompile": "npm run lint && npm run clean",
"compile": "tsup-node && tsc --emitDeclarationOnly --declaration",
"build": "npm run compile",
"release": "release-it",
"version": "npm run build",
"prepublishOnly": "npm run build",
"quick:test": "node --import=ts-node-maintained/register/esm --enable-source-maps bin/test.ts"
},
"keywords": [
"vinejs",
"compiler",
"validator"
],
"author": "virk,vinejs",
"license": "MIT",
"devDependencies": {
"@adonisjs/eslint-config": "^2.0.0-beta.7",
"@adonisjs/prettier-config": "^1.4.0",
"@adonisjs/tsconfig": "^1.4.0",
"@japa/assert": "^3.0.0",
"@japa/runner": "^3.1.4",
"@release-it/conventional-changelog": "^9.0.3",
"@swc/core": "^1.9.3",
"@types/node": "^22.10.1",
"acorn": "^8.14.0",
"ajv": "^8.17.1",
"benchmark": "^2.1.4",
"c8": "^10.1.2",
"del-cli": "^6.0.0",
"eslint": "^9.15.0",
"js-beautify": "^1.15.1",
"prettier": "^3.4.1",
"release-it": "^17.10.0",
"tinybench": "^3.0.6",
"ts-node-maintained": "^10.9.4",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"zod": "^3.23.8"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vinejs/compiler.git"
},
"bugs": {
"url": "https://github.com/vinejs/compiler/issues"
},
"homepage": "https://github.com/vinejs/compiler#readme",
"engines": {
"node": ">=18.0.0"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"tsup": {
"entry": [
"./index.ts",
"./benchmarks/*.ts",
"./src/types.ts"
],
"outDir": "./build",
"clean": true,
"format": "esm",
"dts": false,
"sourcemap": false,
"target": "esnext"
},
"release-it": {
"git": {
"requireCleanWorkingDir": true,
"requireUpstream": true,
"commitMessage": "chore(release): ${version}",
"tagAnnotation": "v${version}",
"push": true,
"tagName": "v${version}"
},
"github": {
"release": true
},
"npm": {
"publish": true,
"skipChecks": true
},
"plugins": {
"@release-it/conventional-changelog": {
"preset": {
"name": "angular"
}
}
}
},
"c8": {
"reporter": [
"text",
"html"
],
"exclude": [
"tests/**",
"bin/**",
"factories/**"
]
},
"prettier": "@adonisjs/prettier-config"
}

9
frontend/node_modules/@vinejs/vine/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,9 @@
# The MIT License
Copyright (c) 2023 VineJS
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

51
frontend/node_modules/@vinejs/vine/README.md generated vendored Normal file
View File

@@ -0,0 +1,51 @@
# @vinejs/vine
<hr>
<br />
<div align="center">
<h3>One of the fastest validation library for Node.js</h3>
<p>VineJS is a form data validation library for Node.js. You may use it to validate the HTTP request body in your backend applications.</p>
</div>
<br />
<div align="center">
[![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url]
</div>
<div align="center">
<h3>
<a href="./benchmarks.md">
Benchmarks
</a>
<span> | </span>
<a href="https://vinejs.dev/docs/introduction">
Documentation
</a>
<span> | </span>
<a href="https://github.com/vinejs/.github/blob/main/docs/CONTRIBUTING.md">
Contributing
</a>
</h3>
</div>
<div align="center">
<sub>Built with ❤︎ by <a href="https://github.com/thetutlage">Harminder Virk</a>
</div>
<br />
<hr>
<br />
![](https://github.com/thetutlage/static/blob/main/sponsorkit/sponsors.png?raw=true)
[gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/vinejs/vine/checks.yml?style=for-the-badge
[gh-workflow-url]: https://github.com/vinejs/vine/actions/workflows/checks.yml 'Github action'
[npm-image]: https://img.shields.io/npm/v/@vinejs/vine/latest.svg?style=for-the-badge&logo=npm
[npm-url]: https://www.npmjs.com/package/@vinejs/vine/v/latest 'npm'
[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
[license-url]: LICENSE.md
[license-image]: https://img.shields.io/github/license/vinejs/vine?style=for-the-badge

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
// src/defaults.ts
var messages = {
"required": "The {{ field }} field must be defined",
"string": "The {{ field }} field must be a string",
"email": "The {{ field }} field must be a valid email address",
"mobile": "The {{ field }} field must be a valid mobile phone number",
"creditCard": "The {{ field }} field must be a valid {{ providersList }} card number",
"passport": "The {{ field }} field must be a valid passport number",
"postalCode": "The {{ field }} field must be a valid postal code",
"regex": "The {{ field }} field format is invalid",
"ascii": "The {{ field }} field must only contain ASCII characters",
"iban": "The {{ field }} field must be a valid IBAN number",
"jwt": "The {{ field }} field must be a valid JWT token",
"coordinates": "The {{ field }} field must contain latitude and longitude coordinates",
"url": "The {{ field }} field must be a valid URL",
"activeUrl": "The {{ field }} field must be a valid URL",
"alpha": "The {{ field }} field must contain only letters",
"alphaNumeric": "The {{ field }} field must contain only letters and numbers",
"minLength": "The {{ field }} field must have at least {{ min }} characters",
"maxLength": "The {{ field }} field must not be greater than {{ max }} characters",
"fixedLength": "The {{ field }} field must be {{ size }} characters long",
"confirmed": "The {{ field }} field and {{ otherField }} field must be the same",
"endsWith": "The {{ field }} field must end with {{ substring }}",
"startsWith": "The {{ field }} field must start with {{ substring }}",
"sameAs": "The {{ field }} field and {{ otherField }} field must be the same",
"notSameAs": "The {{ field }} field and {{ otherField }} field must be different",
"in": "The selected {{ field }} is invalid",
"notIn": "The selected {{ field }} is invalid",
"ipAddress": "The {{ field }} field must be a valid IP address",
"uuid": "The {{ field }} field must be a valid UUID",
"ulid": "The {{ field }} field must be a valid ULID",
"hexCode": "The {{ field }} field must be a valid hex color code",
"boolean": "The value must be a boolean",
"number": "The {{ field }} field must be a number",
"number.in": "The selected {{ field }} is not in {{ values }}",
"min": "The {{ field }} field must be at least {{ min }}",
"max": "The {{ field }} field must not be greater than {{ max }}",
"range": "The {{ field }} field must be between {{ min }} and {{ max }}",
"positive": "The {{ field }} field must be positive",
"negative": "The {{ field }} field must be negative",
"decimal": "The {{ field }} field must have {{ digits }} decimal places",
"withoutDecimals": "The {{ field }} field must be an integer",
"accepted": "The {{ field }} field must be accepted",
"enum": "The selected {{ field }} is invalid",
"literal": "The {{ field }} field must be {{ expectedValue }}",
"object": "The {{ field }} field must be an object",
"array": "The {{ field }} field must be an array",
"array.minLength": "The {{ field }} field must have at least {{ min }} items",
"array.maxLength": "The {{ field }} field must not have more than {{ max }} items",
"array.fixedLength": "The {{ field }} field must contain {{ size }} items",
"notEmpty": "The {{ field }} field must not be empty",
"distinct": "The {{ field }} field has duplicate values",
"record": "The {{ field }} field must be an object",
"record.minLength": "The {{ field }} field must have at least {{ min }} items",
"record.maxLength": "The {{ field }} field must not have more than {{ max }} items",
"record.fixedLength": "The {{ field }} field must contain {{ size }} items",
"tuple": "The {{ field }} field must be an array",
"union": "Invalid value provided for {{ field }} field",
"unionGroup": "Invalid value provided for {{ field }} field",
"unionOfTypes": "Invalid value provided for {{ field }} field",
"date": "The {{ field }} field must be a datetime value",
"date.equals": "The {{ field }} field must be a date equal to {{ expectedValue }}",
"date.after": "The {{ field }} field must be a date after {{ expectedValue }}",
"date.before": "The {{ field }} field must be a date before {{ expectedValue }}",
"date.afterOrEqual": "The {{ field }} field must be a date after or equal to {{ expectedValue }}",
"date.beforeOrEqual": "The {{ field }} field must be a date before or equal to {{ expectedValue }}",
"date.sameAs": "The {{ field }} field and {{ otherField }} field must be the same",
"date.notSameAs": "The {{ field }} field and {{ otherField }} field must be different",
"date.afterField": "The {{ field }} field must be a date after {{ otherField }}",
"date.afterOrSameAs": "The {{ field }} field must be a date after or same as {{ otherField }}",
"date.beforeField": "The {{ field }} field must be a date before {{ otherField }}",
"date.beforeOrSameAs": "The {{ field }} field must be a date before or same as {{ otherField }}",
"date.weekend": "The {{ field }} field is not a weekend",
"date.weekday": "The {{ field }} field is not a weekday"
};
var fields = {
"": "data"
};
export {
messages,
fields
};

View File

@@ -0,0 +1,9 @@
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
export {
__export
};

View File

@@ -0,0 +1,464 @@
import {
__export
} from "./chunk-MLKGABMK.js";
// src/messages_provider/simple_messages_provider.ts
var SimpleMessagesProvider = class {
#messages;
#fields;
constructor(messages, fields) {
this.#messages = messages;
this.#fields = fields || {};
}
/**
* Interpolates place holders within error messages
*/
#interpolate(message, data) {
if (!message.includes("{{")) {
return message;
}
return message.replace(/(\\)?{{(.*?)}}/g, (_, __, key) => {
const tokens = key.trim().split(".");
let output = data;
while (tokens.length) {
if (output === null || typeof output !== "object") {
return;
}
const token = tokens.shift();
output = Object.hasOwn(output, token) ? output[token] : void 0;
}
return output;
});
}
/**
* Returns a validation message for a given field + rule.
*/
getMessage(rawMessage, rule, field, args) {
const fieldName = this.#fields[field.name] || field.name;
const fieldMessage = this.#messages[`${field.getFieldPath()}.${rule}`];
if (fieldMessage) {
return this.#interpolate(fieldMessage, {
field: fieldName,
...args
});
}
const wildcardMessage = this.#messages[`${field.wildCardPath}.${rule}`];
if (wildcardMessage) {
return this.#interpolate(wildcardMessage, {
field: fieldName,
...args
});
}
const ruleMessage = this.#messages[rule];
if (ruleMessage) {
return this.#interpolate(ruleMessage, {
field: fieldName,
...args
});
}
return this.#interpolate(rawMessage, {
field: fieldName,
...args
});
}
toJSON() {
return {
messages: this.#messages,
fields: this.#fields
};
}
};
// src/errors/main.ts
var main_exports = {};
__export(main_exports, {
E_VALIDATION_ERROR: () => E_VALIDATION_ERROR
});
// src/errors/validation_error.ts
var ValidationError = class extends Error {
constructor(messages, options) {
super("Validation failure", options);
this.messages = messages;
const ErrorConstructor = this.constructor;
if ("captureStackTrace" in Error) {
Error.captureStackTrace(this, ErrorConstructor);
}
}
/**
* Http status code for the validation error
*/
status = 422;
/**
* Internal code for handling the validation error
* exception
*/
code = "E_VALIDATION_ERROR";
get [Symbol.toStringTag]() {
return this.constructor.name;
}
toString() {
return `${this.name} [${this.code}]: ${this.message}`;
}
};
// src/errors/main.ts
var E_VALIDATION_ERROR = ValidationError;
// src/reporters/simple_error_reporter.ts
var SimpleErrorReporter = class {
/**
* Boolean to know one or more errors have been reported
*/
hasErrors = false;
/**
* Collection of errors
*/
errors = [];
/**
* Report an error.
*/
report(message, rule, field, meta) {
const error = {
message,
rule,
field: field.getFieldPath()
};
if (meta) {
error.meta = meta;
}
if (field.isArrayMember) {
error.index = field.name;
}
this.hasErrors = true;
this.errors.push(error);
}
/**
* Returns an instance of the validation error
*/
createError() {
return new E_VALIDATION_ERROR(this.errors);
}
};
// src/vine/helpers.ts
import delve from "dlv";
import isIP from "validator/lib/isIP.js";
import isJWT from "validator/lib/isJWT.js";
import isURL from "validator/lib/isURL.js";
import isSlug from "validator/lib/isSlug.js";
import isIBAN from "validator/lib/isIBAN.js";
import isUUID from "validator/lib/isUUID.js";
import isAscii from "validator/lib/isAscii.js";
import isEmail from "validator/lib/isEmail.js";
import isAlpha from "validator/lib/isAlpha.js";
import isLatLong from "validator/lib/isLatLong.js";
import isDecimal from "validator/lib/isDecimal.js";
import isHexColor from "validator/lib/isHexColor.js";
import isCreditCard from "validator/lib/isCreditCard.js";
import isAlphanumeric from "validator/lib/isAlphanumeric.js";
import isPassportNumber from "validator/lib/isPassportNumber.js";
import isPostalCode from "validator/lib/isPostalCode.js";
import isMobilePhone from "validator/lib/isMobilePhone.js";
import { locales as mobilePhoneLocales } from "validator/lib/isMobilePhone.js";
import { locales as postalCodeLocales } from "validator/lib/isPostalCode.js";
var BOOLEAN_POSITIVES = ["1", 1, "true", true, "on"];
var BOOLEAN_NEGATIVES = ["0", 0, "false", false];
var ULID = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var helpers = {
/**
* Returns true when value is not null and neither
* undefined
*/
exists(value) {
return value !== null && value !== void 0;
},
/**
* Returns true when value is null or value is undefined
*/
isMissing(value) {
return !this.exists(value);
},
/**
* Returns true when the value is one of the following.
*
* true
* 1
* "1"
* "true"
* "on"
*/
isTrue(value) {
return BOOLEAN_POSITIVES.includes(value);
},
/**
* Returns true when the value is one of the following.
*
* false
* 0
* "0"
* "false"
*/
isFalse(value) {
return BOOLEAN_NEGATIVES.includes(value);
},
/**
* Check if the value is a valid string. This method narrows
* the type of value to string.
*/
isString(value) {
return typeof value === "string";
},
/**
* Check if the value is a plain JavaScript object. This method
* filters out null and Arrays and does not consider them as Objects.
*/
isObject(value) {
return !!(value && typeof value === "object" && !Array.isArray(value));
},
/**
* Check if an object has all the mentioned keys
*/
hasKeys(value, keys) {
for (let key of keys) {
if (key in value === false) {
return false;
}
}
return true;
},
/**
* Check if the value is an Array.
*/
isArray(value) {
return Array.isArray(value);
},
/**
* Check if the value is a number or a string representation of a number.
*/
isNumeric(value) {
return !Number.isNaN(Number(value));
},
/**
* Casts the value to a number using the Number method.
* Returns NaN when unable to cast.
*/
asNumber(value) {
return value === null ? Number.NaN : Number(value);
},
/**
* Casts the value to a boolean.
*
* - [true, 1, "1", "true", "on"] will be converted to true.
* - [false, 0, "0", "false"] will be converted to false.
* - Everything else will return null. So make sure to handle that case.
*/
asBoolean(value) {
if (this.isTrue(value)) {
return true;
}
if (this.isFalse(value)) {
return false;
}
return null;
},
isEmail: isEmail.default,
isURL: isURL.default,
isAlpha: isAlpha.default,
isAlphaNumeric: isAlphanumeric.default,
isIP: isIP.default,
isUUID: isUUID.default,
isAscii: isAscii.default,
isCreditCard: isCreditCard.default,
isIBAN: isIBAN.default,
isJWT: isJWT.default,
isLatLong: isLatLong.default,
isMobilePhone: isMobilePhone.default,
isPassportNumber: isPassportNumber.default,
isPostalCode: isPostalCode.default,
isSlug: isSlug.default,
isDecimal: isDecimal.default,
mobileLocales: mobilePhoneLocales,
postalCountryCodes: postalCodeLocales,
passportCountryCodes: [
"AM",
"AR",
"AT",
"AU",
"AZ",
"BE",
"BG",
"BR",
"BY",
"CA",
"CH",
"CY",
"CZ",
"DE",
"DK",
"DZ",
"ES",
"FI",
"FR",
"GB",
"GR",
"HR",
"HU",
"IE",
"IN",
"ID",
"IR",
"IS",
"IT",
"JM",
"JP",
"KR",
"KZ",
"LI",
"LT",
"LU",
"LV",
"LY",
"MT",
"MZ",
"MY",
"MX",
"NL",
"NZ",
"PH",
"PK",
"PL",
"PT",
"RO",
"RU",
"SE",
"SL",
"SK",
"TH",
"TR",
"UA",
"US"
],
/**
* Check if the value is a valid ULID
*/
isULID(value) {
if (typeof value !== "string") {
return false;
}
if (value[0] > "7") {
return false;
}
return ULID.test(value);
},
/**
* Check if the value is a valid color hexcode
*/
isHexColor: (value) => {
if (!value.startsWith("#")) {
return false;
}
return isHexColor.default(value);
},
/**
* Check if a URL has valid `A` or `AAAA` DNS records
*/
isActiveURL: async (url) => {
const { resolve4, resolve6 } = await import("node:dns/promises");
try {
const { hostname } = new URL(url);
const v6Addresses = await resolve6(hostname);
if (v6Addresses.length) {
return true;
} else {
const v4Addresses = await resolve4(hostname);
return v4Addresses.length > 0;
}
} catch {
return false;
}
},
/**
* Check if all the elements inside the dataset are unique.
*
* In case of an array of objects, you must provide one or more keys
* for the fields that must be unique across the objects.
*
* ```ts
* helpers.isDistinct([1, 2, 4, 5]) // true
*
* // Null and undefined values are ignored
* helpers.isDistinct([1, null, 2, null, 4, 5]) // true
*
* helpers.isDistinct([
* {
* email: 'foo@bar.com',
* name: 'foo'
* },
* {
* email: 'baz@bar.com',
* name: 'baz'
* }
* ], 'email') // true
*
* helpers.isDistinct([
* {
* email: 'foo@bar.com',
* tenant_id: 1,
* name: 'foo'
* },
* {
* email: 'foo@bar.com',
* tenant_id: 2,
* name: 'baz'
* }
* ], ['email', 'tenant_id']) // true
* ```
*/
isDistinct: (dataSet, fields) => {
const uniqueItems = /* @__PURE__ */ new Set();
if (!fields) {
for (let item of dataSet) {
if (helpers.exists(item)) {
if (uniqueItems.has(item)) {
return false;
} else {
uniqueItems.add(item);
}
}
}
return true;
}
const fieldsList = Array.isArray(fields) ? fields : [fields];
for (let item of dataSet) {
if (helpers.isObject(item) && helpers.hasKeys(item, fieldsList)) {
const element = fieldsList.map((field) => item[field]).join("_");
if (uniqueItems.has(element)) {
return false;
} else {
uniqueItems.add(element);
}
}
}
return true;
},
/**
* Returns the nested value from the field root
* object or the sibling value from the field
* parent object
*/
getNestedValue(key, field) {
if (key.indexOf(".") > -1) {
return delve(field.data, key);
}
return field.parent[key];
}
};
export {
helpers,
SimpleMessagesProvider,
ValidationError,
main_exports,
SimpleErrorReporter
};

View File

@@ -0,0 +1,23 @@
import { ErrorReporterContract } from '@vinejs/compiler/types';
import type { FieldContext, MessagesProviderContact } from '../src/types.js';
/**
* Exposes API to create a dummy field context
*/
export declare class FieldFactory {
create(fieldName: string, value: any, messagesProvider?: MessagesProviderContact, errorReporter?: ErrorReporterContract): {
value: any;
isArrayMember: false;
parent: any;
data: {
[fieldName]: any;
};
name: any;
wildCardPath: string;
getFieldPath(): string;
isDefined: boolean;
isValid: true;
meta: {};
mutate(newValue: any): FieldContext;
report(message: string, rule: string, context: FieldContext, args: Record<string, any> | undefined): void;
};
}

View File

@@ -0,0 +1,8 @@
import { FieldFactory } from './field.js';
import { ValidatorFactory } from './validator.js';
/**
* Validator factory is used for unit testing validation
* rules.
*/
export declare const validator: ValidatorFactory;
export declare const fieldContext: FieldFactory;

View File

@@ -0,0 +1,210 @@
import {
SimpleErrorReporter,
SimpleMessagesProvider,
helpers
} from "../chunk-YXNUTVGP.js";
import "../chunk-MLKGABMK.js";
// factories/field.ts
var FieldFactory = class {
create(fieldName, value, messagesProvider, errorReporter) {
const reporter = errorReporter || new SimpleErrorReporter();
const provider = messagesProvider || new SimpleMessagesProvider({}, {});
return {
value,
isArrayMember: false,
parent: { [fieldName]: value },
data: { [fieldName]: value },
name: fieldName,
wildCardPath: fieldName,
getFieldPath() {
return fieldName;
},
isDefined: helpers.exists(value),
isValid: true,
meta: {},
mutate(newValue) {
this.value = newValue;
this.isDefined = helpers.exists(newValue);
return this;
},
report(message, rule, context, args) {
this.isValid = false;
reporter.report(provider.getMessage(message, rule, context, args), rule, context, args);
}
};
}
};
// factories/validator.ts
import { AssertionError, deepEqual } from "node:assert";
var ValidationResult = class {
#outputValue;
#reporter;
constructor(outputValue, reporter) {
this.#outputValue = outputValue;
this.#reporter = reporter;
}
/**
* Creates an assertion error instance
*/
#assertionError(options) {
const assertion = new AssertionError(options);
Object.defineProperty(assertion, "showDiff", { value: true });
return assertion;
}
/**
* Returns the validation result output
*/
getOutput() {
return this.#outputValue;
}
/**
* Returns an array of errors reported to the
* error reporter
*/
getErrors() {
return this.#reporter.errors;
}
/**
* Assert one or more validation errors have occurred
*/
assertSucceeded() {
if (this.#reporter.hasErrors) {
const errorsCount = this.#reporter.errors.length;
throw this.#assertionError({
message: `Expected validation to pass. Instead failed with "${errorsCount} error(s)"`,
operator: "strictEqual",
stackStartFn: this.assertSucceeded
});
}
}
/**
* Assert the output value of validation. The output value is
* same as the input value, unless "mutate" method is called
*/
assertOutput(expectedOutput) {
deepEqual(this.#outputValue, expectedOutput);
}
/**
* Assert one or more validation errors have occurred
*/
assertFailed() {
if (!this.#reporter.hasErrors) {
throw this.#assertionError({
message: `Expected validation to report one or more errors`,
operator: "strictEqual",
stackStartFn: this.assertFailed
});
}
}
/**
* Assert the number of errors have occurred
*/
assertErrorsCount(count) {
const errorsCount = this.#reporter.errors.length;
if (errorsCount !== count) {
throw this.#assertionError({
message: `Expected validation to report "${count}" errors. Received "${errorsCount}"`,
expected: count,
actual: errorsCount,
operator: "strictEqual",
stackStartFn: this.assertErrorsCount,
showDiff: true
});
}
}
/**
* Assert error messages to include a given error message
*/
assertError(message) {
const messages = this.#reporter.errors.map((e) => e.message);
if (!messages.includes(message)) {
throw this.#assertionError({
message: `Expected validation errors to include "${message}" message`,
expected: [message],
actual: messages,
operator: "includes",
stackStartFn: this.assertError,
showDiff: true
});
}
}
};
var ValidatorFactory = class _ValidatorFactory {
#field;
#bail;
constructor(field, bail) {
this.#field = field;
this.#bail = bail;
}
/**
* Creates an instance of the error reporter required
* to report errors.
*/
#getReporter() {
return new SimpleErrorReporter();
}
/**
* Define field context for the validation
*/
withContext(field) {
return new _ValidatorFactory(field, this.#bail);
}
/**
* Toggle bail mode for the validation
*/
bail(state) {
return new _ValidatorFactory(this.#field, state);
}
/**
* Executes a validation against the provided value
*/
execute(validation, value) {
const errorReporter = this.#getReporter();
const bail = this.#bail === false ? false : true;
const field = {
...new FieldFactory().create("dummy", value, void 0, errorReporter),
...this.#field
};
const validations = Array.isArray(validation) ? validation : [validation];
for (let one of validations) {
if (one.rule.isAsync) {
throw new Error(
`Cannot execute async rule "${one.rule.validator.name}". Use "validator.executeAsync" instead`
);
}
if ((field.isDefined || one.rule.implicit) && (field.isValid || !bail)) {
one.rule.validator(field.value, one.options, field);
}
}
return new ValidationResult(field.value, errorReporter);
}
/**
* Executes an async validation against the provided
* value
*/
async executeAsync(validation, value) {
const errorReporter = this.#getReporter();
const bail = this.#bail === false ? false : true;
const field = {
...new FieldFactory().create("dummy", value, void 0, errorReporter),
...this.#field
};
const validations = Array.isArray(validation) ? validation : [validation];
for (let one of validations) {
if ((field.isDefined || one.rule.implicit) && (field.isValid || !bail)) {
await one.rule.validator(field.value, one.options, field);
}
}
return new ValidationResult(field.value, errorReporter);
}
};
// factories/main.ts
var validator = new ValidatorFactory();
var fieldContext = new FieldFactory();
export {
fieldContext,
validator
};

View File

@@ -0,0 +1,71 @@
import type { FieldContext, Validation } from '../src/types.js';
import { SimpleErrorReporter } from '../src/reporters/simple_error_reporter.js';
/**
* Exposes APIs for writing validation assertions
*/
declare class ValidationResult {
#private;
constructor(outputValue: any, reporter: SimpleErrorReporter);
/**
* Returns the validation result output
*/
getOutput(): any;
/**
* Returns an array of errors reported to the
* error reporter
*/
getErrors(): {
message: string;
field: string;
rule: string;
index?: number;
meta?: Record<string, any>;
}[];
/**
* Assert one or more validation errors have occurred
*/
assertSucceeded(): void;
/**
* Assert the output value of validation. The output value is
* same as the input value, unless "mutate" method is called
*/
assertOutput(expectedOutput: any): void;
/**
* Assert one or more validation errors have occurred
*/
assertFailed(): void;
/**
* Assert the number of errors have occurred
*/
assertErrorsCount(count: number): void;
/**
* Assert error messages to include a given error message
*/
assertError(message: string): void;
}
/**
* Validator factory exposes the API to execute validations
* during tests
*/
export declare class ValidatorFactory {
#private;
constructor(field?: Partial<FieldContext>, bail?: boolean);
/**
* Define field context for the validation
*/
withContext(field: Partial<FieldContext>): ValidatorFactory;
/**
* Toggle bail mode for the validation
*/
bail(state: boolean): ValidatorFactory;
/**
* Executes a validation against the provided value
*/
execute(validation: Validation<any> | Validation<any>[], value: any): ValidationResult;
/**
* Executes an async validation against the provided
* value
*/
executeAsync(validation: Validation<any> | Validation<any>[], value: any): Promise<ValidationResult>;
}
export {};

25
frontend/node_modules/@vinejs/vine/build/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import { Vine } from './src/vine/main.js';
export { Vine };
export * as symbols from './src/symbols.js';
export * as errors from './src/errors/main.js';
export { VineAny } from './src/schema/any/main.js';
export { VineEnum } from './src/schema/enum/main.js';
export { VineNativeEnum } from './src/schema/enum/native_enum.js';
export { VineTuple } from './src/schema/tuple/main.js';
export { VineUnion } from './src/schema/union/main.js';
export { VineArray } from './src/schema/array/main.js';
export { VineValidator } from './src/vine/validator.js';
export { VineString } from './src/schema/string/main.js';
export { VineNumber } from './src/schema/number/main.js';
export { VineDate } from './src/schema/date/main.js';
export { VineRecord } from './src/schema/record/main.js';
export { VineObject } from './src/schema/object/main.js';
export { VineLiteral } from './src/schema/literal/main.js';
export { VineBoolean } from './src/schema/boolean/main.js';
export { VineAccepted } from './src/schema/accepted/main.js';
export { BaseLiteralType } from './src/schema/base/literal.js';
export { BaseType, BaseModifiersType } from './src/schema/base/main.js';
export { SimpleErrorReporter } from './src/reporters/simple_error_reporter.js';
export { SimpleMessagesProvider } from './src/messages_provider/simple_messages_provider.js';
declare const vine: Vine;
export default vine;

56
frontend/node_modules/@vinejs/vine/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,56 @@
import {
BaseLiteralType,
BaseModifiersType,
BaseType,
Vine,
VineAccepted,
VineAny,
VineArray,
VineBoolean,
VineDate,
VineEnum,
VineLiteral,
VineNativeEnum,
VineNumber,
VineObject,
VineRecord,
VineString,
VineTuple,
VineUnion,
VineValidator,
index_default,
symbols_exports
} from "./chunk-FED7BU4B.js";
import {
SimpleErrorReporter,
SimpleMessagesProvider,
main_exports
} from "./chunk-YXNUTVGP.js";
import "./chunk-M2DOTJGC.js";
import "./chunk-MLKGABMK.js";
export {
BaseLiteralType,
BaseModifiersType,
BaseType,
SimpleErrorReporter,
SimpleMessagesProvider,
Vine,
VineAccepted,
VineAny,
VineArray,
VineBoolean,
VineDate,
VineEnum,
VineLiteral,
VineNativeEnum,
VineNumber,
VineObject,
VineRecord,
VineString,
VineTuple,
VineUnion,
VineValidator,
index_default as default,
main_exports as errors,
symbols_exports as symbols
};

View File

@@ -0,0 +1,83 @@
/**
* Collection of default error messages to use
*/
export declare const messages: {
required: string;
string: string;
email: string;
mobile: string;
creditCard: string;
passport: string;
postalCode: string;
regex: string;
ascii: string;
iban: string;
jwt: string;
coordinates: string;
url: string;
activeUrl: string;
alpha: string;
alphaNumeric: string;
minLength: string;
maxLength: string;
fixedLength: string;
confirmed: string;
endsWith: string;
startsWith: string;
sameAs: string;
notSameAs: string;
in: string;
notIn: string;
ipAddress: string;
uuid: string;
ulid: string;
hexCode: string;
boolean: string;
number: string;
'number.in': string;
min: string;
max: string;
range: string;
positive: string;
negative: string;
decimal: string;
withoutDecimals: string;
accepted: string;
enum: string;
literal: string;
object: string;
array: string;
'array.minLength': string;
'array.maxLength': string;
'array.fixedLength': string;
notEmpty: string;
distinct: string;
record: string;
'record.minLength': string;
'record.maxLength': string;
'record.fixedLength': string;
tuple: string;
union: string;
unionGroup: string;
unionOfTypes: string;
date: string;
'date.equals': string;
'date.after': string;
'date.before': string;
'date.afterOrEqual': string;
'date.beforeOrEqual': string;
'date.sameAs': string;
'date.notSameAs': string;
'date.afterField': string;
'date.afterOrSameAs': string;
'date.beforeField': string;
'date.beforeOrSameAs': string;
'date.weekend': string;
'date.weekday': string;
};
/**
* Collection of default fields
*/
export declare const fields: {
'': string;
};

View File

@@ -0,0 +1,9 @@
import {
fields,
messages
} from "../chunk-M2DOTJGC.js";
import "../chunk-MLKGABMK.js";
export {
fields,
messages
};

View File

@@ -0,0 +1,5 @@
import { ValidationError } from './validation_error.js';
/**
* Create an instance of validation error
*/
export declare const E_VALIDATION_ERROR: typeof ValidationError;

View File

@@ -0,0 +1,19 @@
/**
* Validation error is a superset of Error class with validation
* error messages
*/
export declare class ValidationError extends Error {
messages: any;
/**
* Http status code for the validation error
*/
status: number;
/**
* Internal code for handling the validation error
* exception
*/
code: string;
constructor(messages: any, options?: ErrorOptions);
get [Symbol.toStringTag](): string;
toString(): string;
}

View File

@@ -0,0 +1,17 @@
import type { FieldContext, ValidationFields, ValidationMessages, MessagesProviderContact } from '../types.js';
/**
* Default messages provider performs messages lookup inside
* a collection of key-value pair.
*/
export declare class SimpleMessagesProvider implements MessagesProviderContact {
#private;
constructor(messages: ValidationMessages, fields?: ValidationFields);
/**
* Returns a validation message for a given field + rule.
*/
getMessage(rawMessage: string, rule: string, field: FieldContext, args?: Record<string, any>): string;
toJSON(): {
messages: ValidationMessages;
fields: ValidationFields;
};
}

View File

@@ -0,0 +1,41 @@
import { ValidationError } from '../errors/validation_error.js';
import type { ErrorReporterContract, FieldContext } from '../types.js';
/**
* Shape of the error message collected by the SimpleErrorReporter
*/
type SimpleError = {
message: string;
field: string;
rule: string;
index?: number;
meta?: Record<string, any>;
};
/**
* Simple error reporter collects error messages as an array of object.
* Each object has following properties.
*
* - message: string
* - field: string
* - rule: string
* - index?: number (in case of an array member)
* - args?: Record<string, any>
*/
export declare class SimpleErrorReporter implements ErrorReporterContract {
/**
* Boolean to know one or more errors have been reported
*/
hasErrors: boolean;
/**
* Collection of errors
*/
errors: SimpleError[];
/**
* Report an error.
*/
report(message: string, rule: string, field: FieldContext, meta?: Record<string, any> | undefined): void;
/**
* Returns an instance of the validation error
*/
createError(): ValidationError;
}
export {};

View File

@@ -0,0 +1,24 @@
import { BaseLiteralType } from '../base/literal.js';
import type { FieldOptions, Validation } from '../../types.js';
import { SUBTYPE } from '../../symbols.js';
/**
* VineAccepted represents a checkbox input that must be checked
*/
export declare class VineAccepted extends BaseLiteralType<'on' | '1' | 'yes' | 'true' | true | 1, true, true> {
/**
* Default collection of accepted rules
*/
static rules: {
accepted: (options?: undefined) => Validation<undefined>;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]);
/**
* Clones the VineAccepted schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,10 @@
/**
* Validates the value to be present and have one of
* the following values.
*
* - "on"
* - "1"
* - "yes"
* - "true"
*/
export declare const acceptedRule: (options?: undefined) => import("../../types.js").Validation<undefined>;

View File

@@ -0,0 +1,18 @@
import { BaseLiteralType } from '../base/literal.js';
import type { FieldOptions, Validation } from '../../types.js';
import { SUBTYPE } from '../../symbols.js';
/**
* VineAny represents a value that can be anything
*/
export declare class VineAny extends BaseLiteralType<any, any, any> {
constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]);
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
/**
* Clones the VineAny schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,81 @@
import { RefsStore, ArrayNode } from '@vinejs/compiler/types';
import { BaseType } from '../base/main.js';
import { ITYPE, OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js';
import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js';
/**
* VineArray represents an array schema type in the validation
* pipeline
*/
export declare class VineArray<Schema extends SchemaTypes> extends BaseType<Schema[typeof ITYPE][], Schema[typeof OTYPE][], Schema[typeof COTYPE][]> {
#private;
/**
* Default collection of array rules
*/
static rules: {
compact: (options?: undefined) => Validation<undefined>;
notEmpty: (options?: undefined) => Validation<undefined>;
distinct: (options: {
fields?: string | string[];
}) => Validation<{
fields?: string | string[];
}>;
minLength: (options: {
min: number;
}) => Validation<{
min: number;
}>;
maxLength: (options: {
max: number;
}) => Validation<{
max: number;
}>;
fixedLength: (options: {
size: number;
}) => Validation<{
size: number;
}>;
};
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of array type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => value is any[];
constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]);
/**
* Enforce a minimum length on an array field
*/
minLength(expectedLength: number): this;
/**
* Enforce a maximum length on an array field
*/
maxLength(expectedLength: number): this;
/**
* Enforce a fixed length on an array field
*/
fixedLength(expectedLength: number): this;
/**
* Ensure the array is not empty
*/
notEmpty(): this;
/**
* Ensure array elements are distinct/unique
*/
distinct(fields?: string | string[]): this;
/**
* Removes empty strings, null and undefined values from the array
*/
compact(): this;
/**
* Clones the VineArray schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
/**
* Compiles to array data type
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode;
}

View File

@@ -0,0 +1,40 @@
/**
* Enforce a minimum length on an array field
*/
export declare const minLengthRule: (options: {
min: number;
}) => import("../../types.js").Validation<{
min: number;
}>;
/**
* Enforce a maximum length on an array field
*/
export declare const maxLengthRule: (options: {
max: number;
}) => import("../../types.js").Validation<{
max: number;
}>;
/**
* Enforce a fixed length on an array field
*/
export declare const fixedLengthRule: (options: {
size: number;
}) => import("../../types.js").Validation<{
size: number;
}>;
/**
* Ensure the array is not empty
*/
export declare const notEmptyRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Ensure array elements are distinct/unique
*/
export declare const distinctRule: (options: {
fields?: string | string[];
}) => import("../../types.js").Validation<{
fields?: string | string[];
}>;
/**
* Removes empty strings, null and undefined values from the array
*/
export declare const compactRule: (options?: undefined) => import("../../types.js").Validation<undefined>;

View File

@@ -0,0 +1,225 @@
import Macroable from '@poppinss/macroable';
import type { LiteralNode, RefsStore } from '@vinejs/compiler/types';
import { OTYPE, COTYPE, PARSE, ITYPE, SUBTYPE } from '../../symbols.js';
import type { Parser, Validation, RuleBuilder, Transformer, FieldContext, FieldOptions, ParserOptions, ConstructableSchema, ComparisonOperators, ArrayComparisonOperators, NumericComparisonOperators } from '../../types.js';
/**
* Base schema type with only modifiers applicable on all the schema types.
*/
declare abstract class BaseModifiersType<Input, Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Input, 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 & {
subtype: string;
};
/**
* The child class must implement the clone method
*/
abstract clone(): this;
/**
* Define the input type of the schema
*/
[ITYPE]: Input;
/**
* The output value of the field. The property points to a type only
* and not the real value.
*/
[OTYPE]: Output;
[COTYPE]: CamelCaseOutput;
/**
* Mark the field under validation as optional. An optional
* field allows both null and undefined values.
*/
optional(validations?: Validation<any>[]): 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>;
/**
* 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>;
}
/**
* Modifies the schema type to allow null values
*/
export declare class NullableModifier<Schema extends BaseModifiersType<any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE] | null, Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null> {
#private;
constructor(parent: Schema);
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the nullable modifier
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
/**
* Modifies the schema type to allow undefined values
*/
export declare class OptionalModifier<Schema extends BaseModifiersType<any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE] | undefined | null, Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined> {
#private;
/**
* Optional modifier validations list
*/
validations: Validation<any>[];
constructor(parent: Schema, validations?: Validation<any>[]);
/**
* 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>[];
/**
* Compiles validations
*/
protected compileValidations(refs: RefsStore): {
ruleFnId: `ref://${number}`;
implicit: boolean;
isAsync: boolean;
}[];
/**
* Push a validation to the validations chain.
*/
use(validation: Validation<any> | RuleBuilder): this;
/**
* Define a callback to conditionally require a field at
* runtime.
*
* The callback method should return "true" to mark the
* field as required, or "false" to skip the required
* validation
*/
requiredWhen<Operator extends ComparisonOperators>(otherField: string, operator: Operator, expectedValue: Operator extends ArrayComparisonOperators ? (string | number | boolean)[] : Operator extends NumericComparisonOperators ? number : string | number | boolean): this;
requiredWhen(callback: (field: FieldContext) => boolean): this;
/**
* Mark the field under validation as required when all
* the other fields are present with value other
* than `undefined` or `null`.
*/
requiredIfExists(fields: string | string[]): this;
/**
* Mark the field under validation as required when any
* one of the other fields are present with non-nullable
* value.
*/
requiredIfAnyExists(fields: string[]): this;
/**
* Mark the field under validation as required when all
* the other fields are missing or their value is
* `undefined` or `null`.
*/
requiredIfMissing(fields: string | string[]): this;
/**
* Mark the field under validation as required when any
* one of the other fields are missing.
*/
requiredIfAnyMissing(fields: string[]): this;
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the optional modifier
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
/**
* Modifies the schema type to allow custom transformed values
*/
export declare class TransformModifier<Schema extends BaseModifiersType<any, any, any>, Output> extends BaseModifiersType<Schema[typeof ITYPE], Output, Output> {
#private;
/**
* The output value of the field. The property points to a type only
* and not the real value.
*/
[OTYPE]: Output;
[COTYPE]: Output;
constructor(transform: Transformer<Schema, Output>, parent: Schema);
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the transform modifier.
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
/**
* The base type for creating a custom literal type. Literal type
* is a schema type that has no children elements.
*/
export declare abstract class BaseLiteralType<Input, Output, CamelCaseOutput> extends BaseModifiersType<Input, Output, CamelCaseOutput> {
/**
* Specify the subtype of the literal schema field
*/
abstract [SUBTYPE]: string;
/**
* 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>[]);
/**
* 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>[];
/**
* Shallow clones the options
*/
protected cloneOptions(): FieldOptions;
/**
* Compiles validations
*/
protected compileValidations(refs: RefsStore): {
ruleFnId: `ref://${number}`;
implicit: boolean;
isAsync: boolean;
}[];
/**
* 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;
/**
* Push a validation to the validations chain.
*/
use(validation: Validation<any> | RuleBuilder): this;
/**
* Enable/disable the bail mode. In bail mode, the field validations
* are stopped after the first error.
*/
bail(state: boolean): this;
/**
* Compiles the schema type to a compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
export {};

View File

@@ -0,0 +1,175 @@
import type { FieldContext, RefsStore } from '@vinejs/compiler/types';
import { ITYPE, OTYPE, COTYPE, PARSE } from '../../symbols.js';
import type { Parser, Validation, RuleBuilder, FieldOptions, CompilerNodes, ParserOptions, ConstructableSchema, ComparisonOperators, ArrayComparisonOperators, NumericComparisonOperators } from '../../types.js';
import Macroable from '@poppinss/macroable';
/**
* Base schema type with only modifiers applicable on all the schema types.
*/
export declare abstract class BaseModifiersType<Input, Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Input, 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;
/**
* Define the input type of the schema
*/
[ITYPE]: Input;
/**
* The output value of the field. The property points to a type only
* and not the real value.
*/
[OTYPE]: Output;
[COTYPE]: CamelCaseOutput;
/**
* Mark the field under validation as optional. An optional
* field allows both null and undefined values.
*/
optional(): 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>;
}
/**
* Modifies the schema type to allow null values
*/
export declare class NullableModifier<Schema extends BaseModifiersType<any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE] | null, Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null> {
#private;
constructor(parent: Schema);
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the nullable modifier
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes;
}
/**
* Modifies the schema type to allow undefined values
*/
export declare class OptionalModifier<Schema extends BaseModifiersType<any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE] | undefined | null, Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined> {
#private;
/**
* Optional modifier validations list
*/
validations: Validation<any>[];
constructor(parent: Schema, validations?: Validation<any>[]);
/**
* 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>[];
/**
* Compiles validations
*/
protected compileValidations(refs: RefsStore): {
ruleFnId: `ref://${number}`;
implicit: boolean;
isAsync: boolean;
}[];
/**
* Push a validation to the validations chain.
*/
use(validation: Validation<any> | RuleBuilder): this;
/**
* Define a callback to conditionally require a field at
* runtime.
*
* The callback method should return "true" to mark the
* field as required, or "false" to skip the required
* validation
*/
requiredWhen<Operator extends ComparisonOperators>(otherField: string, operator: Operator, expectedValue: Operator extends ArrayComparisonOperators ? (string | number | boolean)[] : Operator extends NumericComparisonOperators ? number : string | number | boolean): this;
requiredWhen(callback: (field: FieldContext) => boolean): this;
/**
* Mark the field under validation as required when all
* the other fields are present with value other
* than `undefined` or `null`.
*/
requiredIfExists(fields: string | string[]): this;
/**
* Mark the field under validation as required when any
* one of the other fields are present with non-nullable
* value.
*/
requiredIfAnyExists(fields: string[]): this;
/**
* Mark the field under validation as required when all
* the other fields are missing or their value is
* `undefined` or `null`.
*/
requiredIfMissing(fields: string | string[]): this;
/**
* Mark the field under validation as required when any
* one of the other fields are missing.
*/
requiredIfAnyMissing(fields: string[]): this;
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the optional modifier
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes;
}
/**
* The BaseSchema class abstracts the repetitive parts of creating
* a custom schema type.
*/
export declare abstract class BaseType<Input, Output, CamelCaseOutput> extends BaseModifiersType<Input, Output, CamelCaseOutput> {
/**
* Field options
*/
protected options: FieldOptions;
/**
* Set of validations to run
*/
protected validations: Validation<any>[];
constructor(options?: FieldOptions, validations?: Validation<any>[]);
/**
* 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>[];
/**
* Shallow clones the options
*/
protected cloneOptions(): FieldOptions;
/**
* Compiles validations
*/
protected compileValidations(refs: RefsStore): {
ruleFnId: `ref://${number}`;
implicit: boolean;
isAsync: boolean;
}[];
/**
* 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;
/**
* Push a validation to the validations chain.
*/
use(validation: Validation<any> | RuleBuilder): this;
/**
* Enable/disable the bail mode. In bail mode, the field validations
* are stopped after the first error.
*/
bail(state: boolean): this;
}

View File

@@ -0,0 +1,6 @@
import type { FieldContext } from '../../types.js';
/**
* Validates the value to be required when a certain condition
* is matched
*/
export declare const requiredWhen: (options: (field: FieldContext) => boolean) => import("../../types.js").Validation<(field: FieldContext) => boolean>;

View File

@@ -0,0 +1,42 @@
import { BaseLiteralType } from '../base/literal.js';
import { IS_OF_TYPE, SUBTYPE, UNIQUE_NAME } from '../../symbols.js';
import type { FieldOptions, Validation } from '../../types.js';
/**
* VineBoolean represents a boolean value in the validation schema.
*/
export declare class VineBoolean extends BaseLiteralType<boolean | string | number, boolean, boolean> {
/**
* Default collection of boolean rules
*/
static rules: {
boolean: (options: {
strict?: boolean;
}) => Validation<{
strict?: boolean;
}>;
};
protected options: FieldOptions & {
strict?: boolean;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of boolean type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => boolean;
constructor(options?: Partial<FieldOptions> & {
strict?: boolean;
}, validations?: Validation<any>[]);
/**
* Clones the VineBoolean schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,8 @@
/**
* Validates the value to be a boolean
*/
export declare const booleanRule: (options: {
strict?: boolean;
}) => import("../../types.js").Validation<{
strict?: boolean;
}>;

View File

@@ -0,0 +1,96 @@
import Macroable from '@poppinss/macroable';
import { VineAny } from './any/main.js';
import { VineEnum } from './enum/main.js';
import { VineDate } from './date/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 { ITYPE, OTYPE, COTYPE } from '../symbols.js';
import type { UndefinedOptional, DateFieldOptions, 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 declare class SchemaBuilder extends Macroable {
/**
* Define a sub-object as a union
*/
group: typeof group;
/**
* Define a union value
*/
union: typeof union;
/**
* Define a string value
*/
string(): VineString;
/**
* Define a boolean value
*/
boolean(options?: {
strict: boolean;
}): VineBoolean;
/**
* Validate a checkbox to be checked
*/
accepted(): VineAccepted;
/**
* Define a number value
*/
number(options?: {
strict: boolean;
}): VineNumber;
/**
* Define a datetime value
*/
date(options?: DateFieldOptions): VineDate;
/**
* Define a schema type in which the input value
* matches the pre-defined value
*/
literal<const Value>(value: Value): VineLiteral<Value>;
/**
* Define an object with known properties. You may call "allowUnknownProperties"
* to merge unknown properties.
*/
object<Properties extends Record<string, SchemaTypes>>(properties: Properties): VineObject<Properties, UndefinedOptional<{ [K in keyof Properties]: Properties[K][typeof ITYPE]; }>, UndefinedOptional<{ [K_1 in keyof Properties]: Properties[K_1][typeof OTYPE]; }>, UndefinedOptional<{ [K_2 in keyof Properties as CamelCase<K_2 & string>]: Properties[K_2][typeof COTYPE]; }>>;
/**
* Define an array field and validate its children elements.
*/
array<Schema extends SchemaTypes>(schema: Schema): VineArray<Schema>;
/**
* Define an array field with known length and each children
* element may have its own schema.
*/
tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]): VineTuple<Schema, { [K in keyof Schema]: Schema[K][typeof ITYPE]; }, { [K_1 in keyof Schema]: Schema[K_1][typeof OTYPE]; }, { [K_2 in keyof Schema]: Schema[K_2][typeof COTYPE]; }>;
/**
* 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): VineRecord<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>;
/**
* Allow the field value to be anything
*/
any(): VineAny;
/**
* Define a union of unique schema types.
*/
unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]): VineUnionOfTypes<Schema>;
}

View File

@@ -0,0 +1,27 @@
/**
* Credit - https://blog.beraliv.dev/2022-07-14-camel-case
*/
type Separator = '_' | '-';
type FilterEmptyWord<Word, T extends unknown[], S extends 'start' | 'end'> = Word extends '' ? T : {
start: [Word, ...T];
end: [...T, Word];
}[S];
type SplitBySeparator<S> = S extends `${infer Word}${Separator}${infer Rest}` ? FilterEmptyWord<Word, SplitBySeparator<Rest>, 'start'> : FilterEmptyWord<S, [], 'start'>;
type IsRepeatedSeparator<Ch, Validated> = Ch extends Separator ? Validated extends `${string}${Separator}` ? true : false : false;
type RemoveRepeatedSeparator<NotValidated, Validated = ''> = NotValidated extends `${infer Ch}${infer Rest}` ? IsRepeatedSeparator<Ch, Validated> extends true ? RemoveRepeatedSeparator<Rest, Validated> : RemoveRepeatedSeparator<Rest, `${Validated & string}${Ch}`> : Validated;
type IsUppercase<Ch extends string> = [Ch] extends [Uppercase<Ch>] ? true : false;
type SplitByCapital<S, Word extends string = '', RemainingWords extends unknown[] = []> = S extends '' ? FilterEmptyWord<Word, RemainingWords, 'end'> : S extends `${infer Ch}${infer Rest}` ? IsUppercase<Ch> extends true ? SplitByCapital<Rest, Ch, FilterEmptyWord<Word, RemainingWords, 'end'>> : SplitByCapital<Rest, `${Word}${Ch}`, RemainingWords> : [];
type WhichApproach<S> = S extends `${string}${Separator}${string}` ? 'separatorBased' : 'capitalBased';
type Words<S> = {
separatorBased: SplitBySeparator<RemoveRepeatedSeparator<S>>;
capitalBased: IsUppercase<S & string> extends true ? [S] : SplitByCapital<S>;
}[WhichApproach<S>];
type WordCase<S, C extends 'pascal' | 'lower'> = {
pascal: Capitalize<WordCase<S, 'lower'> & string>;
lower: Lowercase<S & string>;
}[C];
type PascalCasify<T, R extends unknown[] = []> = T extends [infer Head, ...infer Rest] ? PascalCasify<Rest, [...R, WordCase<Head, 'pascal'>]> : R;
type CamelCasify<T> = T extends [infer Head, ...infer Rest] ? PascalCasify<Rest, [WordCase<Head, 'lower'>]> : [];
type Join<T, S extends string = ''> = T extends [infer Word, ...infer Rest] ? Join<Rest, `${S}${Word & string}`> : S;
export type CamelCase<S extends string> = Join<CamelCasify<Words<S>>>;
export {};

View File

@@ -0,0 +1,200 @@
import { BaseLiteralType } from '../base/literal.js';
import { IS_OF_TYPE, SUBTYPE, UNIQUE_NAME } from '../../symbols.js';
import type { Validation, FieldOptions, FieldContext, DateFieldOptions, DateEqualsOptions } from '../../types.js';
/**
* VineDate represents a Date object created by parsing a
* string or number value as a date.
*/
export declare class VineDate extends BaseLiteralType<string | number, Date, Date> {
/**
* Available VineDate rules
*/
static rules: {
equals: (options: {
expectedValue: string | ((field: FieldContext) => string);
} & DateEqualsOptions) => Validation<{
expectedValue: string | ((field: FieldContext) => string);
} & DateEqualsOptions>;
after: (options: {
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => Validation<{
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
afterOrEqual: (options: {
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => Validation<{
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
before: (options: {
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => Validation<{
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
beforeOrEqual: (options: {
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => Validation<{
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
sameAs: (options: {
otherField: string;
} & DateEqualsOptions) => Validation<{
otherField: string;
} & DateEqualsOptions>;
notSameAs: (options: {
otherField: string;
} & DateEqualsOptions) => Validation<{
otherField: string;
} & DateEqualsOptions>;
afterField: (options: {
otherField: string;
} & DateEqualsOptions) => Validation<{
otherField: string;
} & DateEqualsOptions>;
afterOrSameAs: (options: {
otherField: string;
} & DateEqualsOptions) => Validation<{
otherField: string;
} & DateEqualsOptions>;
beforeField: (options: {
otherField: string;
} & DateEqualsOptions) => Validation<{
otherField: string;
} & DateEqualsOptions>;
beforeOrSameAs: (options: {
otherField: string;
} & DateEqualsOptions) => Validation<{
otherField: string;
} & DateEqualsOptions>;
weekend: (options?: undefined) => Validation<undefined>;
weekday: (options?: undefined) => Validation<undefined>;
};
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
/**
* Checks if the value is of date type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => boolean;
protected options: FieldOptions & DateFieldOptions;
constructor(options?: Partial<FieldOptions> & DateFieldOptions, validations?: Validation<any>[]);
/**
* The equals rule compares the input value to be same
* as the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
equals(expectedValue: string | ((field: FieldContext) => string), options?: DateEqualsOptions): this;
/**
* The after rule compares the input value to be after
* the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
after(expectedValue: 'today' | 'tomorrow' | (string & {
_?: never;
}) | ((field: FieldContext) => string), options?: DateEqualsOptions): this;
/**
* The after or equal rule compares the input value to be
* after or equal to the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
afterOrEqual(expectedValue: 'today' | 'tomorrow' | (string & {
_?: never;
}) | ((field: FieldContext) => string), options?: DateEqualsOptions): this;
/**
* The before rule compares the input value to be before
* the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
before(expectedValue: 'today' | 'yesterday' | (string & {
_?: never;
}) | ((field: FieldContext) => string), options?: DateEqualsOptions): this;
/**
* The before rule compares the input value to be before
* the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
beforeOrEqual(expectedValue: 'today' | 'yesterday' | (string & {
_?: never;
}) | ((field: FieldContext) => string), options?: DateEqualsOptions): this;
/**
* The sameAs rule expects the input value to be same
* as the value of the other field.
*
* By default, the comparions of day, month and years are performed
*/
sameAs(otherField: string, options?: DateEqualsOptions): this;
/**
* The notSameAs rule expects the input value to be different
* from the other field's value
*
* By default, the comparions of day, month and years are performed
*/
notSameAs(otherField: string, options?: DateEqualsOptions): this;
/**
* The afterField rule expects the input value to be after
* the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
afterField(otherField: string, options?: DateEqualsOptions): this;
/**
* The afterOrSameAs rule expects the input value to be after
* or equal to the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
afterOrSameAs(otherField: string, options?: DateEqualsOptions): this;
/**
* The beforeField rule expects the input value to be before
* the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
beforeField(otherField: string, options?: DateEqualsOptions): this;
/**
* The beforeOrSameAs rule expects the input value to be before
* or same as the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
beforeOrSameAs(otherField: string, options?: DateEqualsOptions): this;
/**
* The weekend rule ensures the date falls on a weekend
*/
weekend(): this;
/**
* The weekday rule ensures the date falls on a weekday
*/
weekday(): this;
/**
* Clones the VineDate schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,152 @@
import type { DateEqualsOptions, DateFieldOptions, FieldContext } from '../../types.js';
export declare const DEFAULT_DATE_FORMATS: string[];
/**
* Validates the value to be a string or number formatted
* as per the expected date-time format.
*/
export declare const dateRule: (options: Partial<DateFieldOptions>) => import("../../types.js").Validation<Partial<DateFieldOptions>>;
/**
* The equals rule compares the input value to be same
* as the expected value.
*
* By default, the comparions of day, month and years are performed
*/
export declare const equalsRule: (options: {
expectedValue: string | ((field: FieldContext) => string);
} & DateEqualsOptions) => import("../../types.js").Validation<{
expectedValue: string | ((field: FieldContext) => string);
} & DateEqualsOptions>;
/**
* The after rule compares the input value to be after
* the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
export declare const afterRule: (options: {
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => import("../../types.js").Validation<{
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
/**
* The after or equal rule compares the input value to be
* after or equal to the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
export declare const afterOrEqualRule: (options: {
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => import("../../types.js").Validation<{
expectedValue: "today" | "tomorrow" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
/**
* The before rule compares the input value to be before
* the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
export declare const beforeRule: (options: {
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => import("../../types.js").Validation<{
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
/**
* The before or equal rule compares the input value to be
* before or equal to the expected value.
*
* By default, the comparions of day, month and years are performed.
*/
export declare const beforeOrEqualRule: (options: {
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions) => import("../../types.js").Validation<{
expectedValue: "today" | "yesterday" | (string & {
_?: never;
}) | ((field: FieldContext) => string);
} & DateEqualsOptions>;
/**
* The sameAs rule expects the input value to be same
* as the value of the other field.
*
* By default, the comparions of day, month and years are performed
*/
export declare const sameAsRule: (options: {
otherField: string;
} & DateEqualsOptions) => import("../../types.js").Validation<{
otherField: string;
} & DateEqualsOptions>;
/**
* The notSameAs rule expects the input value to be different
* from the other field's value
*
* By default, the comparions of day, month and years are performed
*/
export declare const notSameAsRule: (options: {
otherField: string;
} & DateEqualsOptions) => import("../../types.js").Validation<{
otherField: string;
} & DateEqualsOptions>;
/**
* The afterField rule expects the input value to be after
* the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
export declare const afterFieldRule: (options: {
otherField: string;
} & DateEqualsOptions) => import("../../types.js").Validation<{
otherField: string;
} & DateEqualsOptions>;
/**
* The afterOrSameAs rule expects the input value to be after
* or same as the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
export declare const afterOrSameAsRule: (options: {
otherField: string;
} & DateEqualsOptions) => import("../../types.js").Validation<{
otherField: string;
} & DateEqualsOptions>;
/**
* The beforeField rule expects the input value to be before
* the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
export declare const beforeFieldRule: (options: {
otherField: string;
} & DateEqualsOptions) => import("../../types.js").Validation<{
otherField: string;
} & DateEqualsOptions>;
/**
* The beforeOrSameAs rule expects the input value to be before
* or same as the other field's value.
*
* By default, the comparions of day, month and years are performed
*/
export declare const beforeOrSameAsRule: (options: {
otherField: string;
} & DateEqualsOptions) => import("../../types.js").Validation<{
otherField: string;
} & DateEqualsOptions>;
/**
* The weekend rule ensures the date falls on a weekend
*/
export declare const weekendRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* The weekday rule ensures the date falls on a weekday
*/
export declare const weekdayRule: (options?: undefined) => import("../../types.js").Validation<undefined>;

View File

@@ -0,0 +1,34 @@
import { BaseLiteralType } from '../base/literal.js';
import type { FieldContext, FieldOptions, Validation } from '../../types.js';
import { SUBTYPE } from '../../symbols.js';
/**
* VineEnum represents a enum data type that performs validation
* against a pre-defined choices list.
*/
export declare class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType<Values[number], Values[number], Values[number]> {
#private;
/**
* Default collection of enum rules
*/
static rules: {
enum: (options: {
choices: readonly any[] | ((field: FieldContext) => readonly any[]);
}) => Validation<{
choices: readonly any[] | ((field: FieldContext) => readonly any[]);
}>;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
/**
* Returns the enum choices
*/
getChoices(): Values | ((field: FieldContext) => Values);
constructor(values: Values | ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[]);
/**
* Clones the VineEnum schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,33 @@
import { BaseLiteralType } from '../base/literal.js';
import type { EnumLike, FieldOptions, Validation } from '../../types.js';
import { SUBTYPE } from '../../symbols.js';
/**
* VineNativeEnum represents a enum data type that performs validation
* against a pre-defined choices list.
*
* The choices list is derived from TypeScript enum data type or an
* object
*/
export declare class VineNativeEnum<Values extends EnumLike> extends BaseLiteralType<Values[keyof Values], Values[keyof Values], Values[keyof Values]> {
#private;
/**
* Default collection of enum rules
*/
static rules: {
enum: (options: {
choices: readonly any[] | ((field: import("@vinejs/compiler/types").FieldContext) => readonly any[]);
}) => Validation<{
choices: readonly any[] | ((field: import("@vinejs/compiler/types").FieldContext) => readonly any[]);
}>;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]);
/**
* Clones the VineNativeEnum schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,10 @@
import { FieldContext } from '@vinejs/compiler/types';
/**
* Enum rule is used to validate the field's value to be one
* from the pre-defined choices.
*/
export declare const enumRule: (options: {
choices: readonly any[] | ((field: FieldContext) => readonly any[]);
}) => import("../../types.js").Validation<{
choices: readonly any[] | ((field: FieldContext) => readonly any[]);
}>;

View File

@@ -0,0 +1,29 @@
import { BaseLiteralType } from '../base/literal.js';
import type { FieldOptions, Validation } from '../../types.js';
import { SUBTYPE } from '../../symbols.js';
/**
* VineLiteral represents a type that matches an exact value
*/
export declare class VineLiteral<Value> extends BaseLiteralType<Value, Value, Value> {
#private;
/**
* Default collection of literal rules
*/
static rules: {
equals: (options: {
expectedValue: any;
}) => Validation<{
expectedValue: any;
}>;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
constructor(value: Value, options?: FieldOptions, validations?: Validation<any>[]);
/**
* Clones the VineLiteral schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,9 @@
/**
* Verifies two equals are equal considering the HTML forms
* serialization behavior.
*/
export declare const equalsRule: (options: {
expectedValue: any;
}) => import("../../types.js").Validation<{
expectedValue: any;
}>;

View File

@@ -0,0 +1,105 @@
import { BaseLiteralType } from '../base/literal.js';
import { FieldOptions, Validation } from '../../types.js';
import { IS_OF_TYPE, SUBTYPE, UNIQUE_NAME } from '../../symbols.js';
/**
* VineNumber represents a numeric value in the validation schema.
*/
export declare class VineNumber extends BaseLiteralType<string | number, number, number> {
protected options: FieldOptions & {
strict?: boolean;
};
/**
* Default collection of number rules
*/
static rules: {
in: (options: {
values: number[];
}) => Validation<{
values: number[];
}>;
max: (options: {
max: number;
}) => Validation<{
max: number;
}>;
min: (options: {
min: number;
}) => Validation<{
min: number;
}>;
range: (options: {
min: number;
max: number;
}) => Validation<{
min: number;
max: number;
}>;
number: (options: {
strict?: boolean;
}) => Validation<{
strict?: boolean;
}>;
decimal: (options: {
range: [number, number?];
}) => Validation<{
range: [number, number?];
}>;
negative: (options?: undefined) => Validation<undefined>;
positive: (options?: undefined) => Validation<undefined>;
withoutDecimals: (options?: undefined) => Validation<undefined>;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of number type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => boolean;
constructor(options?: Partial<FieldOptions> & {
strict?: boolean;
}, validations?: Validation<any>[]);
/**
* Enforce a minimum value for the number input
*/
min(value: number): this;
/**
* Enforce a maximum value for the number input
*/
max(value: number): this;
/**
* Enforce value to be within the range of minimum and maximum output.
*/
range(value: [min: number, max: number]): this;
/**
* Enforce the value be a positive number
*/
positive(): this;
/**
* Enforce the value be a negative number
*/
negative(): this;
/**
* Enforce the value to have fixed or range
* of decimal places
*/
decimal(range: number | [number, number]): this;
/**
* Enforce the value to be an integer (aka without decimals)
*/
withoutDecimals(): this;
/**
* Clones the VineNumber schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
/**
* Enforce the value to be in a list of allowed values
*/
in(values: number[]): this;
}

View File

@@ -0,0 +1,63 @@
/**
* Enforce the value to be a number or a string representation
* of a number
*/
export declare const numberRule: (options: {
strict?: boolean;
}) => import("../../types.js").Validation<{
strict?: boolean;
}>;
/**
* Enforce a minimum value on a number field
*/
export declare const minRule: (options: {
min: number;
}) => import("../../types.js").Validation<{
min: number;
}>;
/**
* Enforce a maximum value on a number field
*/
export declare const maxRule: (options: {
max: number;
}) => import("../../types.js").Validation<{
max: number;
}>;
/**
* Enforce a range of values on a number field.
*/
export declare const rangeRule: (options: {
min: number;
max: number;
}) => import("../../types.js").Validation<{
min: number;
max: number;
}>;
/**
* Enforce the value is a positive number
*/
export declare const positiveRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Enforce the value is a negative number
*/
export declare const negativeRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Enforce the value to have a fixed or range of decimals
*/
export declare const decimalRule: (options: {
range: [number, number?];
}) => import("../../types.js").Validation<{
range: [number, number?];
}>;
/**
* Enforce the value to not have decimal places
*/
export declare const withoutDecimalsRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Enforce the value to be in a list of allowed values
*/
export declare const inRule: (options: {
values: number[];
}) => import("../../types.js").Validation<{
values: number[];
}>;

View File

@@ -0,0 +1,18 @@
import type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types';
import { OTYPE, COTYPE, PARSE, ITYPE } from '../../symbols.js';
import type { ParserOptions, SchemaTypes } from '../../types.js';
/**
* Group conditional represents a sub-set of object wrapped
* inside a conditional
*/
export declare class GroupConditional<Properties extends Record<string, SchemaTypes>, Input, Output, CamelCaseOutput> {
#private;
[ITYPE]: Input;
[OTYPE]: Output;
[COTYPE]: CamelCaseOutput;
constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties);
/**
* Compiles to a union conditional
*/
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number];
}

View File

@@ -0,0 +1,29 @@
import { ObjectGroupNode, RefsStore } from '@vinejs/compiler/types';
import { GroupConditional } from './conditional.js';
import { ITYPE, 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 declare class ObjectGroup<Conditional extends GroupConditional<any, any, any, any>> {
#private;
[ITYPE]: Conditional[typeof ITYPE];
[OTYPE]: Conditional[typeof OTYPE];
[COTYPE]: Conditional[typeof COTYPE];
constructor(conditionals: Conditional[]);
/**
* Clones the ObjectGroup schema type.
*/
clone(): 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;
/**
* Compiles the group
*/
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode;
}

View File

@@ -0,0 +1,15 @@
import { ObjectGroup } from './group.js';
import { CamelCase } from '../camelcase_types.js';
import { GroupConditional } from './conditional.js';
import { OTYPE, COTYPE, ITYPE } from '../../symbols.js';
import type { FieldContext, SchemaTypes, UndefinedOptional } from '../../types.js';
/**
* Create an object group. Groups are used to conditionally merge properties
* to an existing object.
*/
export declare function group<Conditional extends GroupConditional<any, any, any, any>>(conditionals: Conditional[]): ObjectGroup<Conditional>;
export declare namespace group {
var _a: <Properties extends Record<string, SchemaTypes>>(conditon: (value: Record<string, unknown>, field: FieldContext) => any, properties: Properties) => GroupConditional<Properties, UndefinedOptional<{ [K in keyof Properties]: Properties[K][typeof ITYPE]; }>, UndefinedOptional<{ [K_1 in keyof Properties]: Properties[K_1][typeof OTYPE]; }>, UndefinedOptional<{ [K_2 in keyof Properties as CamelCase<K_2 & string>]: Properties[K_2][typeof COTYPE]; }>>;
var _b: <Properties extends Record<string, SchemaTypes>>(properties: Properties) => GroupConditional<Properties, UndefinedOptional<{ [K in keyof Properties]: Properties[K][typeof ITYPE]; }>, UndefinedOptional<{ [K_1 in keyof Properties]: Properties[K_1][typeof OTYPE]; }>, UndefinedOptional<{ [K_2 in keyof Properties as CamelCase<K_2 & string>]: Properties[K_2][typeof COTYPE]; }>>;
export { _a as if, _b as else };
}

View File

@@ -0,0 +1,80 @@
import type { ObjectNode, RefsStore } from '@vinejs/compiler/types';
import { ObjectGroup } from './group.js';
import { GroupConditional } from './conditional.js';
import { BaseType, BaseModifiersType } from '../base/main.js';
import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE, ITYPE } from '../../symbols.js';
import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js';
/**
* Converts schema properties to camelCase
*/
export declare class VineCamelCaseObject<Schema extends VineObject<any, any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE], Schema[typeof COTYPE], Schema[typeof COTYPE]> {
#private;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of object type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => boolean;
constructor(schema: Schema);
/**
* Clone object
*/
clone(): this;
/**
* Compiles the schema type to a compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode;
}
/**
* VineObject represents an object value in the validation
* schema.
*/
export declare class VineObject<Properties extends Record<string, SchemaTypes>, Input, Output, CamelCaseOutput> extends BaseType<Input, Output, CamelCaseOutput> {
#private;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of object type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => boolean;
constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]);
/**
* 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;
/**
* Copy unknown properties to the final output.
*/
allowUnknownProperties<Value>(): VineObject<Properties, Input & {
[K: string]: Value;
}, 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, any>>>(group: Group): VineObject<Properties, Input & Group[typeof ITYPE], Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]>;
/**
* Clone object
*/
clone(): this;
/**
* Applies camelcase transform
*/
toCamelCase(): VineCamelCaseObject<this>;
/**
* Compiles the schema type to a compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode;
}

View File

@@ -0,0 +1,74 @@
import { RefsStore, RecordNode } from '@vinejs/compiler/types';
import { BaseType } from '../base/main.js';
import { ITYPE, OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js';
import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js';
import { validateKeysRule } from './rules.js';
/**
* VineRecord represents an object of key-value pair in which
* keys are unknown
*/
export declare class VineRecord<Schema extends SchemaTypes> extends BaseType<{
[K: string]: Schema[typeof ITYPE];
}, {
[K: string]: Schema[typeof OTYPE];
}, {
[K: string]: Schema[typeof COTYPE];
}> {
#private;
/**
* Default collection of record rules
*/
static rules: {
maxLength: (options: {
max: number;
}) => Validation<{
max: number;
}>;
minLength: (options: {
min: number;
}) => Validation<{
min: number;
}>;
fixedLength: (options: {
size: number;
}) => Validation<{
size: number;
}>;
validateKeys: (options: (keys: string[], field: import("@vinejs/compiler/types").FieldContext) => void) => Validation<(keys: string[], field: import("@vinejs/compiler/types").FieldContext) => void>;
};
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of object type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => boolean;
constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]);
/**
* Enforce a minimum length on an object field
*/
minLength(expectedLength: number): this;
/**
* Enforce a maximum length on an object field
*/
maxLength(expectedLength: number): this;
/**
* Enforce a fixed length on an object field
*/
fixedLength(expectedLength: number): this;
/**
* Register a callback to validate the object keys
*/
validateKeys(...args: Parameters<typeof validateKeysRule>): this;
/**
* Clones the VineRecord schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
/**
* Compiles to record data type
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode;
}

View File

@@ -0,0 +1,29 @@
import { FieldContext } from '@vinejs/compiler/types';
/**
* Enforce a minimum length on an object field
*/
export declare const minLengthRule: (options: {
min: number;
}) => import("../../types.js").Validation<{
min: number;
}>;
/**
* Enforce a maximum length on an object field
*/
export declare const maxLengthRule: (options: {
max: number;
}) => import("../../types.js").Validation<{
max: number;
}>;
/**
* Enforce a fixed length on an object field
*/
export declare const fixedLengthRule: (options: {
size: number;
}) => import("../../types.js").Validation<{
size: number;
}>;
/**
* Register a callback to validate the object keys
*/
export declare const validateKeysRule: (options: (keys: string[], field: FieldContext) => void) => import("../../types.js").Validation<(keys: string[], field: FieldContext) => void>;

View File

@@ -0,0 +1,258 @@
import { BaseLiteralType } from '../base/literal.js';
import { IS_OF_TYPE, SUBTYPE, UNIQUE_NAME } from '../../symbols.js';
import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions } from '../../types.js';
import { urlRule, uuidRule, emailRule, mobileRule, passportRule, creditCardRule, postalCodeRule, normalizeUrlRule } from './rules.js';
/**
* VineString represents a string value in the validation schema.
*/
export declare class VineString extends BaseLiteralType<string, string, string> {
static rules: {
in: (options: {
choices: string[] | ((field: FieldContext) => string[]);
}) => Validation<{
choices: string[] | ((field: FieldContext) => string[]);
}>;
jwt: (options?: undefined) => Validation<undefined>;
url: (options?: import("validator/lib/isURL.js").IsURLOptions | undefined) => Validation<import("validator/lib/isURL.js").IsURLOptions | undefined>;
iban: (options?: undefined) => Validation<undefined>;
uuid: (options?: {
version?: (1 | 2 | 3 | 4 | 5)[];
} | undefined) => Validation<{
version?: (1 | 2 | 3 | 4 | 5)[];
} | undefined>;
ulid: (options?: undefined) => Validation<undefined>;
trim: (options?: undefined) => Validation<undefined>;
email: (options?: import("validator/lib/isEmail.js").IsEmailOptions | undefined) => Validation<import("validator/lib/isEmail.js").IsEmailOptions | undefined>;
alpha: (options?: AlphaOptions | undefined) => Validation<AlphaOptions | undefined>;
ascii: (options?: undefined) => Validation<undefined>;
notIn: (options: {
list: string[] | ((field: FieldContext) => string[]);
}) => Validation<{
list: string[] | ((field: FieldContext) => string[]);
}>;
regex: (options: RegExp) => Validation<RegExp>;
escape: (options?: undefined) => Validation<undefined>;
sameAs: (options: {
otherField: string;
}) => Validation<{
otherField: string;
}>;
mobile: (options?: import("../../types.js").MobileOptions | ((field: FieldContext) => import("../../types.js").MobileOptions | undefined) | undefined) => Validation<import("../../types.js").MobileOptions | ((field: FieldContext) => import("../../types.js").MobileOptions | undefined) | undefined>;
string: (options?: undefined) => Validation<undefined>;
hexCode: (options?: undefined) => Validation<undefined>;
passport: (options: import("../../types.js").PassportOptions | ((field: FieldContext) => import("../../types.js").PassportOptions)) => Validation<import("../../types.js").PassportOptions | ((field: FieldContext) => import("../../types.js").PassportOptions)>;
endsWith: (options: {
substring: string;
}) => Validation<{
substring: string;
}>;
confirmed: (options?: {
confirmationField: string;
} | undefined) => Validation<{
confirmationField: string;
} | undefined>;
activeUrl: (options?: undefined) => Validation<undefined>;
minLength: (options: {
min: number;
}) => Validation<{
min: number;
}>;
notSameAs: (options: {
otherField: string;
}) => Validation<{
otherField: string;
}>;
maxLength: (options: {
max: number;
}) => Validation<{
max: number;
}>;
ipAddress: (options?: {
version: 4 | 6;
} | undefined) => Validation<{
version: 4 | 6;
} | undefined>;
creditCard: (options?: import("../../types.js").CreditCardOptions | ((field: FieldContext) => import("../../types.js").CreditCardOptions | void | undefined) | undefined) => Validation<import("../../types.js").CreditCardOptions | ((field: FieldContext) => import("../../types.js").CreditCardOptions | void | undefined) | undefined>;
postalCode: (options?: import("../../types.js").PostalCodeOptions | ((field: FieldContext) => import("../../types.js").PostalCodeOptions | void | undefined) | undefined) => Validation<import("../../types.js").PostalCodeOptions | ((field: FieldContext) => import("../../types.js").PostalCodeOptions | void | undefined) | undefined>;
startsWith: (options: {
substring: string;
}) => Validation<{
substring: string;
}>;
toUpperCase: (options?: string | string[] | undefined) => Validation<string | string[] | undefined>;
toLowerCase: (options?: string | string[] | undefined) => Validation<string | string[] | undefined>;
toCamelCase: (options?: undefined) => Validation<undefined>;
fixedLength: (options: {
size: number;
}) => Validation<{
size: number;
}>;
coordinates: (options?: undefined) => Validation<undefined>;
normalizeUrl: (options?: import("normalize-url").Options | undefined) => Validation<import("normalize-url").Options | undefined>;
alphaNumeric: (options?: AlphaOptions | undefined) => Validation<AlphaOptions | undefined>;
normalizeEmail: (options?: import("validator").NormalizeEmailOptions | undefined) => Validation<import("validator").NormalizeEmailOptions | undefined>;
};
/**
* The subtype of the literal schema field
*/
[SUBTYPE]: string;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of string type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => value is string;
constructor(options?: FieldOptions, validations?: Validation<any>[]);
/**
* Validates the value to be a valid URL
*/
url(...args: Parameters<typeof urlRule>): this;
/**
* Validates the value to be an active URL
*/
activeUrl(): this;
/**
* Validates the value to be a valid email address
*/
email(...args: Parameters<typeof emailRule>): this;
/**
* Validates the value to be a valid mobile number
*/
mobile(...args: Parameters<typeof mobileRule>): this;
/**
* Validates the value to be a valid IP address.
*/
ipAddress(version?: 4 | 6): this;
/**
* Validates the value to be a valid hex color code
*/
hexCode(): this;
/**
* Validates the value against a regular expression
*/
regex(expression: RegExp): this;
/**
* Validates the value to contain only letters
*/
alpha(options?: AlphaOptions): this;
/**
* Validates the value to contain only letters and
* numbers
*/
alphaNumeric(options?: AlphaNumericOptions): this;
/**
* Enforce a minimum length on a string field
*/
minLength(expectedLength: number): this;
/**
* Enforce a maximum length on a string field
*/
maxLength(expectedLength: number): this;
/**
* Enforce a fixed length on a string field
*/
fixedLength(expectedLength: number): this;
/**
* Ensure the field under validation is confirmed by
* having another field with the same name.
*/
confirmed(options?: {
confirmationField: string;
}): this;
/**
* Trims whitespaces around the string value
*/
trim(): this;
/**
* Normalizes the email address
*/
normalizeEmail(options?: NormalizeEmailOptions): this;
/**
* Converts the field value to UPPERCASE.
*/
toUpperCase(): this;
/**
* Converts the field value to lowercase.
*/
toLowerCase(): this;
/**
* Converts the field value to camelCase.
*/
toCamelCase(): this;
/**
* Escape string for HTML entities
*/
escape(): this;
/**
* Normalize a URL
*/
normalizeUrl(...args: Parameters<typeof normalizeUrlRule>): this;
/**
* Ensure the value starts with the pre-defined substring
*/
startsWith(substring: string): this;
/**
* Ensure the value ends with the pre-defined substring
*/
endsWith(substring: string): this;
/**
* Ensure the value ends with the pre-defined substring
*/
sameAs(otherField: string): this;
/**
* Ensure the value ends with the pre-defined substring
*/
notSameAs(otherField: string): this;
/**
* Ensure the field's value under validation is a subset of the pre-defined list.
*/
in(choices: string[] | ((field: FieldContext) => string[])): this;
/**
* Ensure the field's value under validation is not inside the pre-defined list.
*/
notIn(list: string[] | ((field: FieldContext) => string[])): this;
/**
* Validates the value to be a valid credit card number
*/
creditCard(...args: Parameters<typeof creditCardRule>): this;
/**
* Validates the value to be a valid passport number
*/
passport(...args: Parameters<typeof passportRule>): this;
/**
* Validates the value to be a valid postal code
*/
postalCode(...args: Parameters<typeof postalCodeRule>): this;
/**
* Validates the value to be a valid UUID
*/
uuid(...args: Parameters<typeof uuidRule>): this;
/**
* Validates the value to be a valid ULID
*/
ulid(): this;
/**
* Validates the value contains ASCII characters only
*/
ascii(): this;
/**
* Validates the value to be a valid IBAN number
*/
iban(): this;
/**
* Validates the value to be a valid JWT token
*/
jwt(): this;
/**
* Ensure the value is a string with latitude and longitude coordinates
*/
coordinates(): this;
/**
* Clones the VineString schema type. The applied options
* and validations are copied to the new instance
*/
clone(): this;
}

View File

@@ -0,0 +1,195 @@
import type { FieldContext } from '@vinejs/compiler/types';
import type { AlphaOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions } from '../../types.js';
/**
* Validates the value to be a string
*/
export declare const stringRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Validates the value to be a valid email address
*/
export declare const emailRule: (options?: import("validator/lib/isEmail.js").IsEmailOptions | undefined) => import("../../types.js").Validation<import("validator/lib/isEmail.js").IsEmailOptions | undefined>;
/**
* Validates the value to be a valid mobile number
*/
export declare const mobileRule: (options?: MobileOptions | ((field: FieldContext) => MobileOptions | undefined) | undefined) => import("../../types.js").Validation<MobileOptions | ((field: FieldContext) => MobileOptions | undefined) | undefined>;
/**
* Validates the value to be a valid IP address.
*/
export declare const ipAddressRule: (options?: {
version: 4 | 6;
} | undefined) => import("../../types.js").Validation<{
version: 4 | 6;
} | undefined>;
/**
* Validates the value against a regular expression
*/
export declare const regexRule: (options: RegExp) => import("../../types.js").Validation<RegExp>;
/**
* Validates the value to be a valid hex color code
*/
export declare const hexCodeRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Validates the value to be a valid URL
*/
export declare const urlRule: (options?: import("validator/lib/isURL.js").IsURLOptions | undefined) => import("../../types.js").Validation<import("validator/lib/isURL.js").IsURLOptions | undefined>;
/**
* Validates the value to be an active URL
*/
export declare const activeUrlRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Validates the value to contain only letters
*/
export declare const alphaRule: (options?: AlphaOptions | undefined) => import("../../types.js").Validation<AlphaOptions | undefined>;
/**
* Validates the value to contain only letters and numbers
*/
export declare const alphaNumericRule: (options?: AlphaOptions | undefined) => import("../../types.js").Validation<AlphaOptions | undefined>;
/**
* Enforce a minimum length on a string field
*/
export declare const minLengthRule: (options: {
min: number;
}) => import("../../types.js").Validation<{
min: number;
}>;
/**
* Enforce a maximum length on a string field
*/
export declare const maxLengthRule: (options: {
max: number;
}) => import("../../types.js").Validation<{
max: number;
}>;
/**
* Enforce a fixed length on a string field
*/
export declare const fixedLengthRule: (options: {
size: number;
}) => import("../../types.js").Validation<{
size: number;
}>;
/**
* Ensure the value ends with the pre-defined substring
*/
export declare const endsWithRule: (options: {
substring: string;
}) => import("../../types.js").Validation<{
substring: string;
}>;
/**
* Ensure the value starts with the pre-defined substring
*/
export declare const startsWithRule: (options: {
substring: string;
}) => import("../../types.js").Validation<{
substring: string;
}>;
/**
* Ensure the field's value under validation is the same as the other field's value
*/
export declare const sameAsRule: (options: {
otherField: string;
}) => import("../../types.js").Validation<{
otherField: string;
}>;
/**
* Ensure the field's value under validation is different from another field's value
*/
export declare const notSameAsRule: (options: {
otherField: string;
}) => import("../../types.js").Validation<{
otherField: string;
}>;
/**
* Ensure the field under validation is confirmed by
* having another field with the same name
*/
export declare const confirmedRule: (options?: {
confirmationField: string;
} | undefined) => import("../../types.js").Validation<{
confirmationField: string;
} | undefined>;
/**
* Trims whitespaces around the string value
*/
export declare const trimRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Normalizes the email address
*/
export declare const normalizeEmailRule: (options?: import("validator").NormalizeEmailOptions | undefined) => import("../../types.js").Validation<import("validator").NormalizeEmailOptions | undefined>;
/**
* Converts the field value to UPPERCASE.
*/
export declare const toUpperCaseRule: (options?: string | string[] | undefined) => import("../../types.js").Validation<string | string[] | undefined>;
/**
* Converts the field value to lowercase.
*/
export declare const toLowerCaseRule: (options?: string | string[] | undefined) => import("../../types.js").Validation<string | string[] | undefined>;
/**
* Converts the field value to camelCase.
*/
export declare const toCamelCaseRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Escape string for HTML entities
*/
export declare const escapeRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Normalize a URL
*/
export declare const normalizeUrlRule: (options?: import("normalize-url").Options | undefined) => import("../../types.js").Validation<import("normalize-url").Options | undefined>;
/**
* Ensure the field's value under validation is a subset of the pre-defined list.
*/
export declare const inRule: (options: {
choices: string[] | ((field: FieldContext) => string[]);
}) => import("../../types.js").Validation<{
choices: string[] | ((field: FieldContext) => string[]);
}>;
/**
* Ensure the field's value under validation is not inside the pre-defined list.
*/
export declare const notInRule: (options: {
list: string[] | ((field: FieldContext) => string[]);
}) => import("../../types.js").Validation<{
list: string[] | ((field: FieldContext) => string[]);
}>;
/**
* Validates the value to be a valid credit card number
*/
export declare const creditCardRule: (options?: CreditCardOptions | ((field: FieldContext) => CreditCardOptions | void | undefined) | undefined) => import("../../types.js").Validation<CreditCardOptions | ((field: FieldContext) => CreditCardOptions | void | undefined) | undefined>;
/**
* Validates the value to be a valid passport number
*/
export declare const passportRule: (options: PassportOptions | ((field: FieldContext) => PassportOptions)) => import("../../types.js").Validation<PassportOptions | ((field: FieldContext) => PassportOptions)>;
/**
* Validates the value to be a valid postal code
*/
export declare const postalCodeRule: (options?: PostalCodeOptions | ((field: FieldContext) => PostalCodeOptions | void | undefined) | undefined) => import("../../types.js").Validation<PostalCodeOptions | ((field: FieldContext) => PostalCodeOptions | void | undefined) | undefined>;
/**
* Validates the value to be a valid UUID
*/
export declare const uuidRule: (options?: {
version?: (1 | 2 | 3 | 4 | 5)[];
} | undefined) => import("../../types.js").Validation<{
version?: (1 | 2 | 3 | 4 | 5)[];
} | undefined>;
/**
* Validates the value to be a valid ULID
*/
export declare const ulidRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Validates the value contains ASCII characters only
*/
export declare const asciiRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Validates the value to be a valid IBAN number
*/
export declare const ibanRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Validates the value to be a valid JWT token
*/
export declare const jwtRule: (options?: undefined) => import("../../types.js").Validation<undefined>;
/**
* Ensure the value is a string with latitude and longitude coordinates
*/
export declare const coordinatesRule: (options?: undefined) => import("../../types.js").Validation<undefined>;

View File

@@ -0,0 +1,42 @@
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 declare class VineTuple<Schema extends SchemaTypes[], Input extends any[], Output extends any[], CamelCaseOutput extends any[]> extends BaseType<Input, Output, CamelCaseOutput> {
#private;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of array type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => value is any[];
constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]);
/**
* Copy unknown properties to the final output.
*/
allowUnknownProperties<Value>(): VineTuple<Schema, [
...Input,
...Value[]
], [
...Output,
...Value[]
], [
...CamelCaseOutput,
...Value[]
]>;
/**
* Clone object
*/
clone(): this;
/**
* Compiles to array data type
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode;
}

View File

@@ -0,0 +1,13 @@
import { VineUnion } from './main.js';
import { UnionConditional } from './conditional.js';
import type { FieldContext, SchemaTypes } from '../../types.js';
/**
* Create a new union schema type. A union is a collection of conditionals
* and schema associated with it.
*/
export declare function union<Conditional extends UnionConditional<any>>(conditionals: Conditional[]): VineUnion<Conditional>;
export declare namespace union {
var _a: <Schema extends SchemaTypes>(conditon: (value: Record<string, unknown>, field: FieldContext) => any, schema: Schema) => UnionConditional<Schema>;
var _b: <Schema extends SchemaTypes>(schema: Schema) => UnionConditional<Schema>;
export { _a as if, _b as else };
}

View File

@@ -0,0 +1,18 @@
import { ConditionalFn, RefsStore, UnionNode } from '@vinejs/compiler/types';
import { ITYPE, 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 declare class UnionConditional<Schema extends SchemaTypes> {
#private;
[ITYPE]: Schema[typeof ITYPE];
[OTYPE]: Schema[typeof OTYPE];
[COTYPE]: Schema[typeof COTYPE];
constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema);
/**
* Compiles to a union conditional
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode['conditions'][number];
}

View File

@@ -0,0 +1,28 @@
import { RefsStore, UnionNode } from '@vinejs/compiler/types';
import { UnionConditional } from './conditional.js';
import { ITYPE, OTYPE, COTYPE, PARSE } 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 declare class VineUnion<Conditional extends UnionConditional<SchemaTypes>> implements ConstructableSchema<Conditional[typeof ITYPE], Conditional[typeof OTYPE], Conditional[typeof COTYPE]> {
#private;
[ITYPE]: Conditional[typeof ITYPE];
[OTYPE]: Conditional[typeof OTYPE];
[COTYPE]: Conditional[typeof COTYPE];
constructor(conditionals: Conditional[]);
/**
* 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;
/**
* Clones the VineUnion schema type.
*/
clone(): this;
/**
* Compiles to a union
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode;
}

View File

@@ -0,0 +1,27 @@
import type { RefsStore, UnionNode } from '@vinejs/compiler/types';
import { ITYPE, OTYPE, COTYPE, PARSE } 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 declare class VineUnionOfTypes<Schema extends SchemaTypes> implements ConstructableSchema<Schema[typeof ITYPE], Schema[typeof OTYPE], Schema[typeof COTYPE]> {
#private;
[ITYPE]: Schema[typeof ITYPE];
[OTYPE]: Schema[typeof OTYPE];
[COTYPE]: Schema[typeof COTYPE];
constructor(schemas: Schema[]);
/**
* 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;
/**
* Clones the VineUnionOfTypes schema type.
*/
clone(): this;
/**
* Compiles to a union
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode;
}

View File

@@ -0,0 +1,33 @@
/**
* The symbol to define a unique name for the schema type
*/
export declare const UNIQUE_NAME: unique symbol;
/**
* The symbol to check if a value is of the given schema
* type
*/
export declare const IS_OF_TYPE: unique symbol;
/**
* The symbol for the compile method
*/
export declare const PARSE: unique symbol;
/**
* The symbol for the opaque input type
*/
export declare const ITYPE: unique symbol;
/**
* The symbol for the opaque type
*/
export declare const OTYPE: unique symbol;
/**
* The symbol for the camelcase opaque type
*/
export declare const COTYPE: unique symbol;
/**
* The symbol to generate a validation rule from rule builder
*/
export declare const VALIDATION: unique symbol;
/**
* The symbol for the subtype of a literal field
*/
export declare const SUBTYPE: unique symbol;

245
frontend/node_modules/@vinejs/vine/build/src/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,245 @@
import type dayjs from 'dayjs';
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 { PostalCodeLocale } from 'validator/lib/isPostalCode.js';
import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js';
import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js';
import type { ParseFn, RefsStore, TupleNode, ArrayNode, UnionNode, RecordNode, ObjectNode, TransformFn, LiteralNode, FieldContext, MessagesProviderContact, ErrorReporterContract as BaseReporter } from '@vinejs/compiler/types';
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, ITYPE } from './symbols.js';
/**
* Compiler nodes emitted by Vine
*/
export type CompilerNodes = (LiteralNode & {
subtype: string;
}) | ObjectNode | ArrayNode | UnionNode | RecordNode | TupleNode;
/**
* 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<Inputs, Output, CamelCaseOutput> {
[ITYPE]: Inputs;
[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, 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;
};
/**
* A set of options accepted by the date field
*/
export type DateFieldOptions = {
formats?: dayjs.OptionType;
};
/**
* A set of options accepted by the equals rule
* on the date field
*/
export type DateEqualsOptions = {
compare?: dayjs.OpUnitType;
format?: dayjs.OptionType;
};
/**
* 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];
export type InferInput<Schema extends {
[ITYPE]: any;
}> = Schema[typeof ITYPE];
/**
* Comparison operators supported by requiredWhen
* rule
*/
export type NumericComparisonOperators = '>' | '<' | '>=' | '<=';
export type ArrayComparisonOperators = 'in' | 'notIn';
export type ComparisonOperators = ArrayComparisonOperators | NumericComparisonOperators | '=' | '!=';
type PickUndefined<T> = {
[K in keyof T]: undefined extends T[K] ? K : never;
}[keyof T];
type PickNotUndefined<T> = {
[K in keyof T]: undefined extends T[K] ? never : K;
}[keyof T];
type Id<T> = T extends infer U ? {
[K in keyof U]: U[K];
} : never;
export type UndefinedOptional<T> = Id<{
[K in PickUndefined<T>]?: T[K];
} & {
[K in PickNotUndefined<T>]: T[K];
}>;

Some files were not shown because too many files have changed in this diff Show More