This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+7
View File
@@ -0,0 +1,7 @@
import { RequestConstructorContract } from '@ioc:Adonis/Core/Request';
import { validator, ValidatorResolvedConfig } from '@ioc:Adonis/Core/Validator';
/**
* Extends the request class by adding `validate` method
* to it
*/
export default function extendRequest(Request: RequestConstructorContract, validate: (typeof validator)['validate'], config: ValidatorResolvedConfig): void;
+58
View File
@@ -0,0 +1,58 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Extends the request class by adding `validate` method
* to it
*/
function extendRequest(Request, validate, config) {
Request.macro('validate', async function validateRequest(Validator) {
/**
* Merging request body, files and the params. The params are nested, since
* it's possible that request body and params may have the same object
* properties.
*/
const validatorNode = typeof Validator === 'function' ? new Validator(this.ctx) : Validator;
const data = validatorNode.data || {
...this.all(),
...this.allFiles(),
params: this.ctx.params,
};
/**
* Choosing the correct reporter for the given HTTP request. This is how it works
*
* - The first preference is given to the inline reporter
* - Otherwise use the negotiator
*/
const reporter = validatorNode.reporter ? validatorNode.reporter : config.negotiator(this);
/**
* Creating a new profiler action to profile the validation
*/
const profilerAction = this.ctx.profiler.profile('request:validate');
/**
* Merge user defined messages with the default
* messages
*/
let messages = validatorNode.messages;
if (config.messages) {
messages = { ...config.messages(this.ctx), ...messages };
}
try {
const validated = await validate({ data, reporter, ...validatorNode, messages });
profilerAction.end({ status: 'success' });
return validated;
}
catch (error) {
profilerAction.end({ status: 'error' });
throw error;
}
});
}
exports.default = extendRequest;
+53
View File
@@ -0,0 +1,53 @@
/**
* Exposes the API to build a template by writing compiled output
* to the buffer.
*/
export declare class CompilerBuffer {
private lines;
private indentation;
private wrappingBlocks;
/**
* Returns the indentation spaces
*/
private getIndentationSpaces;
/**
* Indent code by 2 spaces
*/
indent(): this;
/**
* Dedent code by 2 spaces
*/
dedent(): this;
/**
* Write a statement to the buffer
*/
writeStatement(line: string, multiline?: boolean): this;
/**
* Write an expression to the buffer. Colon is appended to
* expressions.
*/
writeExpression(line: string, multiline?: boolean): this;
/**
* Write a comment to the buffer
*/
writeComment(line: string, multiline?: boolean): this;
/**
* Write a new empty line to the buffer
*/
newLine(): this;
/**
* Define the wrapping code for the output string. To have
* proper indentation on the output, it is recommended to defined
* the wrapping blocks upfront.
*/
wrappingCode(blocks: [string, string]): this;
/**
* Return the string representation of the buffer
*/
toString(): string;
/**
* Same as `toString` but cleans up the internal stored
* values.
*/
flush(): string;
}
+120
View File
@@ -0,0 +1,120 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompilerBuffer = void 0;
/**
* Exposes the API to build a template by writing compiled output
* to the buffer.
*/
class CompilerBuffer {
constructor() {
this.lines = [];
this.indentation = 0;
this.wrappingBlocks = [];
}
/**
* Returns the indentation spaces
*/
getIndentationSpaces() {
return new Array(this.indentation + 1).join(' ');
}
/**
* Indent code by 2 spaces
*/
indent() {
this.indentation += 2;
return this;
}
/**
* Dedent code by 2 spaces
*/
dedent() {
if (this.indentation === 0) {
return this;
}
this.indentation -= 2;
return this;
}
/**
* Write a statement to the buffer
*/
writeStatement(line, multiline = false) {
if (multiline) {
line.split('\n').forEach((one) => this.writeStatement(one));
return this;
}
this.lines.push(`${this.getIndentationSpaces()}${line}`);
return this;
}
/**
* Write an expression to the buffer. Colon is appended to
* expressions.
*/
writeExpression(line, multiline = false) {
if (multiline) {
const lines = line.split('\n');
lines.forEach((one, index) => {
const colon = lines.length === index + 1 ? ';' : '';
this.lines.push(`${this.getIndentationSpaces()}${one}${colon}`);
});
return this;
}
this.lines.push(`${this.getIndentationSpaces()}${line};`);
return this;
}
/**
* Write a comment to the buffer
*/
writeComment(line, multiline = false) {
if (multiline) {
line.split('\n').forEach((one) => this.writeComment(one));
return this;
}
this.lines.push(`${this.getIndentationSpaces()}// ${line}`);
return this;
}
/**
* Write a new empty line to the buffer
*/
newLine() {
this.lines.push('');
return this;
}
/**
* Define the wrapping code for the output string. To have
* proper indentation on the output, it is recommended to defined
* the wrapping blocks upfront.
*/
wrappingCode(blocks) {
this.wrappingBlocks.push(blocks);
this.indent();
return this;
}
/**
* Return the string representation of the buffer
*/
toString() {
const start = this.wrappingBlocks.map((block) => block[0]);
const end = this.wrappingBlocks.map((block) => block[1]);
return start.concat(this.lines).concat(end).join('\n');
}
/**
* Same as `toString` but cleans up the internal stored
* values.
*/
flush() {
const value = this.toString();
this.lines = [];
this.wrappingBlocks = [];
this.indentation = 0;
return value;
}
}
exports.CompilerBuffer = CompilerBuffer;
+55
View File
@@ -0,0 +1,55 @@
import { SchemaArray, ValidationField } from '@ioc:Adonis/Core/Validator';
import { Compiler } from '../index';
import { CompilerBuffer } from '../Buffer';
/**
* Exposes the API to compile the array node to a set of inline
* Javascript instructions.
*/
export declare class ArrayCompiler {
private field;
private node;
private compiler;
private references;
constructor(field: ValidationField, node: SchemaArray, compiler: Compiler, references: {
outVariable: string;
referenceVariable: string;
parentPointer: ValidationField[];
});
/**
* Declaring the out variable as an empty array. As the validations
* will progress, this object will receive new properties
*/
private declareOutVariable;
/**
* Add the if statement to ensure that the runtime value is an
* array, before we attempt to validate it's members
*/
private startIfGuard;
/**
* Ends the previously started if guard
*/
private endIfGuard;
/**
* Start the for loop to loop over the array entries. We use a `for of`
* loop, since their are one or more children async rules
*/
private startAsyncForLoop;
/**
* Start the for loop to loop over the array entries.
*/
private startForLoop;
/**
* Ends the previously started for loop
*/
private endForLoop;
/**
* Returns a boolean telling if any of the children of a given node
* has async rules. This helps in optimizing the for loop for
* the array.
*/
private hasAsyncChildren;
/**
* Converts the array node to compiled Javascript statement.
*/
compile(buffer: CompilerBuffer): void;
}
+180
View File
@@ -0,0 +1,180 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArrayCompiler = void 0;
const Literal_1 = require("./Literal");
/**
* Exposes the API to compile the array node to a set of inline
* Javascript instructions.
*/
class ArrayCompiler {
constructor(field, node, compiler, references) {
this.field = field;
this.node = node;
this.compiler = compiler;
this.references = references;
}
/**
* Declaring the out variable as an empty array. As the validations
* will progress, this object will receive new properties
*/
declareOutVariable(buffer, outVariable, outValue, constAssigment) {
const referenceExpression = this.compiler.pointerToExpression(this.field);
if (constAssigment) {
buffer.writeExpression(`const ${outVariable} = ${this.references.outVariable}[${referenceExpression}] = ${outValue}`);
}
else {
buffer.writeExpression(`${this.references.outVariable}[${referenceExpression}] = ${outValue}`);
}
}
/**
* Add the if statement to ensure that the runtime value is an
* array, before we attempt to validate it's members
*/
startIfGuard(buffer, variableName) {
buffer.writeStatement(`if (${this.compiler.getVariableExistsName(variableName)} && Array.isArray(${variableName})) {`);
buffer.indent();
}
/**
* Ends the previously started if guard
*/
endIfGuard(buffer) {
buffer.dedent();
buffer.writeStatement('}');
}
/**
* Start the for loop to loop over the array entries. We use a `for of`
* loop, since their are one or more children async rules
*/
startAsyncForLoop(buffer, variableName, indexVariable) {
buffer.writeStatement(`for (let [${indexVariable}] of ${variableName}.entries()) {`);
buffer.indent();
}
/**
* Start the for loop to loop over the array entries.
*/
startForLoop(buffer, variableName, indexVariable) {
buffer.writeStatement(`for (let ${indexVariable} = 0; ${indexVariable} < ${variableName}.length; ${indexVariable}++) {`);
buffer.indent();
}
/**
* Ends the previously started for loop
*/
endForLoop(buffer) {
buffer.dedent();
buffer.writeStatement('}');
}
/**
* Returns a boolean telling if any of the children of a given node
* has async rules. This helps in optimizing the for loop for
* the array.
*/
hasAsyncChildren(node) {
if (node.rules.find((rule) => rule.async)) {
return true;
}
if (node.type === 'array' && node.each) {
return this.hasAsyncChildren(node.each);
}
if (node.type === 'object' && node.children) {
const children = Object.keys(node.children);
for (let child of children) {
if (this.hasAsyncChildren(node.children[child])) {
return true;
}
}
}
return false;
}
/**
* Converts the array node to compiled Javascript statement.
*/
compile(buffer) {
if (!this.node.rules.length && !this.node.each) {
return;
}
/**
* Parsing the object as a literal node with `array` subtype.
*/
const literal = new Literal_1.LiteralCompiler(this.field, {
type: 'literal',
subtype: 'array',
nullable: this.node.nullable,
optional: this.node.optional,
rules: this.node.rules,
}, this.compiler, this.references);
/**
* Disable output variable since we start with an empty array and
* only collect the validated properties.
*/
literal.disableOutVariable = true;
/**
* Always declare the value variable so that we can reference it to validate
* the children of the array.
*/
literal.forceValueDeclaration = true;
literal.compile(buffer);
const outVariable = `out_${this.compiler.outVariableCounter++}`;
/**
* Do not output the compiled code for validating children, when no children
* have been defined on the array
*/
if (!this.node.each) {
buffer.writeStatement(`if (${this.compiler.getVariableExistsName(literal.variableName)}${this.node.nullable ? ` || ${literal.variableName} === null` : ''}) {`);
buffer.indent();
this.declareOutVariable(buffer, outVariable, literal.variableName, false);
buffer.dedent();
buffer.writeStatement('}');
return;
}
const hasAsyncChildren = this.hasAsyncChildren(this.node.each);
buffer.newLine();
/**
* Add a guard if statement to only validate children when the field
* value is a valid array
*/
this.startIfGuard(buffer, literal.variableName);
const indexVariable = `index_${this.compiler.arrayIndexVariableCounter++}`;
/**
* Declaring the out variable as an empty array
*/
this.declareOutVariable(buffer, outVariable, '[]', true);
/**
* Add the for loop
*/
if (hasAsyncChildren) {
this.startAsyncForLoop(buffer, literal.variableName, indexVariable);
}
else {
this.startForLoop(buffer, literal.variableName, indexVariable);
}
/**
* Parse members
*/
buffer.newLine();
this.compiler.compileNode({ name: indexVariable, type: 'identifier' }, this.node.each, buffer, this.references.parentPointer.concat(this.field), literal.variableName, outVariable);
/**
* End for loop and if guard
*/
this.endForLoop(buffer);
this.endIfGuard(buffer);
/**
* Entertain null values
*/
if (this.node.nullable) {
buffer.writeStatement(`else if (${literal.variableName} === null) {`);
buffer.indent();
this.declareOutVariable(buffer, outVariable, 'null', false);
buffer.dedent();
buffer.writeStatement(`}`);
}
}
}
exports.ArrayCompiler = ArrayCompiler;
+52
View File
@@ -0,0 +1,52 @@
import { ValidationField, SchemaLiteral } from '@ioc:Adonis/Core/Validator';
import { Compiler } from '../index';
import { CompilerBuffer } from '../Buffer';
/**
* Exposes the API to compile the literal node to a set of inline
* Javascript instructions.
*/
export declare class LiteralCompiler {
private field;
private node;
private compiler;
private references;
disableOutVariable: boolean;
forceValueDeclaration: boolean;
/**
* Name of the variable set for the literal node
*/
variableName: string;
constructor(field: ValidationField, node: SchemaLiteral, compiler: Compiler, references: {
outVariable: string;
referenceVariable: string;
parentPointer: ValidationField[];
});
/**
* Initiate the variable name that hold the value of the current
* field
*/
private initiateVariableName;
/**
* Writes the compiled statement to declare the value variable
*/
private declareValueVariable;
private declareExistsVariable;
/**
* Writes the compiled statement for the mutation function. The mutate function is
* passed to the validation definition.
*/
private declareMutationFunction;
/**
* Writes the compiled statement to declare the options that are passed to all
* the validation functions for this field.
*/
private declareValidationOptions;
/**
* Writes the compiled statement to assign the out value.
*/
private assignOutValue;
/**
* Converts the literal node to compiled Javascript statement.
*/
compile(buffer: CompilerBuffer): void;
}
+126
View File
@@ -0,0 +1,126 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.LiteralCompiler = void 0;
/**
* Exposes the API to compile the literal node to a set of inline
* Javascript instructions.
*/
class LiteralCompiler {
constructor(field, node, compiler, references) {
this.field = field;
this.node = node;
this.compiler = compiler;
this.references = references;
this.disableOutVariable = false;
this.forceValueDeclaration = false;
}
/**
* Initiate the variable name that hold the value of the current
* field
*/
initiateVariableName() {
this.variableName = this.variableName || `val_${this.compiler.referenceVariableCounter++}`;
}
/**
* Writes the compiled statement to declare the value variable
*/
declareValueVariable(buffer) {
const referenceExpression = this.compiler.pointerToExpression(this.field);
buffer.writeComment(`Validate ${this.references.referenceVariable}[${referenceExpression}]`);
buffer.writeExpression(`let ${this.variableName} = ${this.references.referenceVariable}[${referenceExpression}]`);
}
declareExistsVariable(buffer) {
buffer.writeExpression(this.compiler.getVariableExistsDeclaration(this.variableName), true);
}
/**
* Writes the compiled statement for the mutation function. The mutate function is
* passed to the validation definition.
*/
declareMutationFunction(buffer) {
buffer.writeStatement(this.compiler.getMutationFnDeclararationExpression(this.variableName), true);
}
/**
* Writes the compiled statement to declare the options that are passed to all
* the validation functions for this field.
*/
declareValidationOptions(buffer) {
const pointerExpressions = this.references.parentPointer.concat(this.field);
const pointerExpression = this.compiler.pointersToExpression(pointerExpressions);
let ar;
const hasDynamicPointers = pointerExpressions.find(({ type }) => type === 'identifier');
if (hasDynamicPointers) {
ar = this.compiler.pointersToExpression(pointerExpressions.map(({ name, type }) => {
return type === 'identifier' ? { name: '*', type: 'literal' } : { name, type };
}));
}
buffer.writeExpression(this.compiler.getOptionsDeclarationExpression(this.variableName, this.compiler.pointerToExpression(this.field), this.references.referenceVariable, pointerExpression, ar), true);
}
/**
* Writes the compiled statement to assign the out value.
*/
assignOutValue(buffer) {
const referenceVariable = this.compiler.pointerToExpression(this.field);
buffer.writeStatement(`if (${this.compiler.getVariableExistsName(this.variableName)}${this.node.nullable ? ` || ${this.variableName} === null` : ''}) {`);
buffer.indent();
buffer.writeExpression(`${this.references.outVariable}[${referenceVariable}] = ${this.variableName}`);
buffer.dedent();
buffer.writeStatement('}');
}
/**
* Converts the literal node to compiled Javascript statement.
*/
compile(buffer) {
/**
* Return early when no validation rules are defined on the node. However, we check
* for `forceValueDeclaration` flag to see if we should declare the value
* variable or not
*/
if (!this.node.rules.length) {
if (this.forceValueDeclaration) {
this.initiateVariableName();
this.declareValueVariable(buffer);
this.declareExistsVariable(buffer);
}
return;
}
/**
* Define variable name
*/
this.initiateVariableName();
this.declareValueVariable(buffer);
/**
* Define variable to know if value is undefined or null
*/
this.declareExistsVariable(buffer);
/**
* Define mutation function
*/
this.declareMutationFunction(buffer);
/**
* Define options
*/
this.declareValidationOptions(buffer);
/**
* Write expressions for each validation call for the defined
* rules
*/
this.node.rules.forEach((rule) => {
buffer.writeExpression(this.compiler.getValidationCallableExpression(this.variableName, rule));
});
/**
* Do not define the out variable when disabled
*/
if (!this.disableOutVariable) {
this.assignOutValue(buffer);
}
}
}
exports.LiteralCompiler = LiteralCompiler;
+37
View File
@@ -0,0 +1,37 @@
import { ValidationField, SchemaObject } from '@ioc:Adonis/Core/Validator';
import { Compiler } from '../index';
import { CompilerBuffer } from '../Buffer';
/**
* Exposes the API to compile the object node to a set of inline
* Javascript instructions.
*/
export declare class ObjectCompiler {
private field;
private node;
private compiler;
private references;
constructor(field: ValidationField, node: SchemaObject, compiler: Compiler, references: {
outVariable: string;
referenceVariable: string;
parentPointer: ValidationField[];
});
/**
* Declaring the out variable as an empty object. As the validations
* will progress, this object will receive new properties
*/
private declareOutVariable;
/**
* Adds a guard that ensures that the runtime value of the field
* is a valid object, before we attempt to validate it's
* children.
*/
private startIfGuard;
/**
* Ends the previously started if guard
*/
private endIfGuard;
/**
* Converts the object node to compiled Javascript statement.
*/
compile(buffer: CompilerBuffer): void;
}
+114
View File
@@ -0,0 +1,114 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectCompiler = void 0;
const Literal_1 = require("./Literal");
/**
* Exposes the API to compile the object node to a set of inline
* Javascript instructions.
*/
class ObjectCompiler {
constructor(field, node, compiler, references) {
this.field = field;
this.node = node;
this.compiler = compiler;
this.references = references;
}
/**
* Declaring the out variable as an empty object. As the validations
* will progress, this object will receive new properties
*/
declareOutVariable(buffer, outVariable, outValue, constAssigment) {
const referenceExpression = this.compiler.pointerToExpression(this.field);
if (constAssigment) {
buffer.writeExpression(`const ${outVariable} = ${this.references.outVariable}[${referenceExpression}] = ${outValue}`);
}
else {
buffer.writeExpression(`${this.references.outVariable}[${referenceExpression}] = ${outValue}`);
}
}
/**
* Adds a guard that ensures that the runtime value of the field
* is a valid object, before we attempt to validate it's
* children.
*/
startIfGuard(buffer, variableName) {
buffer.writeStatement(`if (${this.compiler.getVariableExistsName(variableName)} && ${this.compiler.COMPILER_REFERENCES.isObject}(${variableName})) {`);
buffer.indent();
}
/**
* Ends the previously started if guard
*/
endIfGuard(buffer) {
buffer.dedent();
buffer.writeStatement('}');
}
/**
* Converts the object node to compiled Javascript statement.
*/
compile(buffer) {
const children = this.node.children ? Object.keys(this.node.children) : null;
/**
* Parsing the object as a literal node with `object` subtype.
*/
const literal = new Literal_1.LiteralCompiler(this.field, {
type: 'literal',
subtype: 'object',
nullable: this.node.nullable,
optional: this.node.optional,
rules: this.node.rules,
}, this.compiler, this.references);
/**
* Disable the output variable assignment. Since we do not copy the original
* object as it is and instead create a fresh object and only set
* validated fields on it
*/
literal.disableOutVariable = true;
literal.forceValueDeclaration = true;
literal.compile(buffer);
const outVariable = `out_${this.compiler.outVariableCounter++}`;
/**
* Set output variable right away when no children are defined
* or any children are accepted. There is no need to build
* the object gradually.
*/
if (!children || children.length === 0) {
buffer.writeStatement(`if (${this.compiler.getVariableExistsName(literal.variableName)}${this.node.nullable ? ` || ${literal.variableName} === null` : ''}) {`);
buffer.indent();
this.declareOutVariable(buffer, outVariable, children ? '{}' : literal.variableName, false);
buffer.dedent();
buffer.writeStatement('}');
return;
}
/**
* The object members validation is wrapped inside the if guard
*/
buffer.newLine();
this.startIfGuard(buffer, literal.variableName);
this.declareOutVariable(buffer, outVariable, '{}', true);
buffer.newLine();
/**
* Recursively parse children of the object
*/
this.compiler.compileTree(this.node.children || {}, buffer, this.references.parentPointer.concat(this.field), literal.variableName, outVariable);
this.endIfGuard(buffer);
/**
* Entertain null values
*/
if (this.node.nullable) {
buffer.writeStatement(`else if (${literal.variableName} === null) {`);
buffer.indent();
this.declareOutVariable(buffer, outVariable, 'null', false);
buffer.dedent();
buffer.writeStatement(`}`);
}
}
}
exports.ObjectCompiler = ObjectCompiler;
+83
View File
@@ -0,0 +1,83 @@
import { ParsedRule, SchemaArray, SchemaObject, SchemaLiteral, ValidationField, ParsedSchemaTree, CompilerOutput } from '@ioc:Adonis/Core/Validator';
import { CompilerBuffer } from './Buffer';
/**
* Compiler exposes the API to compile the schema tree into a set of Javascript
* instructions.
*/
export declare class Compiler {
private schema;
/**
* Reference counters. They are required for node compilers to
* create safe and unique variable names
*/
outVariableCounter: number;
referenceVariableCounter: number;
arrayIndexVariableCounter: number;
/**
* The name of certain properties referenced inside
* the compiled output
*/
COMPILER_REFERENCES: {
validations: string;
exists: string;
isObject: string;
reportError: string;
};
constructor(schema: ParsedSchemaTree);
/**
* Returns the name of the options object for a given variable
*/
getVariableOptionsName(variableName: string): string;
/**
* Returns the name of the mutation function for a given variable
*/
getVariableMutationName(variableName: string): string;
/**
* The variable name to hold the boolean if value is undefined or not
*/
getVariableExistsName(variableName: string): string;
/**
* Returns the declaration for the undefined and the null check
*/
getVariableExistsDeclaration(variableName: string): string;
/**
* Returns the expression to declare the mutation function for a given
* field.
*/
getMutationFnDeclararationExpression(variableName: string): string;
/**
* Returns the expression to declare the options
*/
getOptionsDeclarationExpression(variableName: string, field: string, tip: string, pointer: string, arrayExpressionPointer?: string): string;
/**
* Returns the method call expression for executing validation
* a given rule
*/
getValidationCallableExpression(variableName: string, rule: ParsedRule): string;
/**
* Converts a pointer to a Javascript expression
*/
pointerToExpression(pointer: ValidationField): string;
/**
* Converts an array of pointers to a Javascript expression
*/
pointersToExpression(pointer: ValidationField[]): string;
/**
* Compiles a given node inside the schema tree. The compiled
* output is written to the buffer
*/
compileNode(field: string | ValidationField, node: SchemaArray | SchemaLiteral | SchemaObject, buffer: CompilerBuffer, parentPointer: ValidationField[], referenceVariable?: string, outVariable?: string): void;
/**
* Compiles all nodes for the schema tree recursively. The compiled
* output is written to the buffer.
*/
compileTree(tree: ParsedSchemaTree, buffer: CompilerBuffer, parentPointer: ValidationField[], referenceVariable?: string, outVariable?: string): void;
/**
* Compiles the tree and returns the compiled code as a string.
*/
compileAsString(): string;
/**
* Compiles the schema tree to an executable function
*/
compile<T extends any>(): CompilerOutput<T>;
}
+221
View File
@@ -0,0 +1,221 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Compiler = void 0;
const Buffer_1 = require("./Buffer");
const Array_1 = require("./Nodes/Array");
const Object_1 = require("./Nodes/Object");
const Literal_1 = require("./Nodes/Literal");
/**
* Compiler exposes the API to compile the schema tree into a set of Javascript
* instructions.
*/
class Compiler {
constructor(schema) {
this.schema = schema;
/**
* Reference counters. They are required for node compilers to
* create safe and unique variable names
*/
this.outVariableCounter = 0;
this.referenceVariableCounter = 0;
this.arrayIndexVariableCounter = 0;
/**
* The name of certain properties referenced inside
* the compiled output
*/
this.COMPILER_REFERENCES = {
validations: 'validations',
exists: 'helpers.exists',
isObject: 'helpers.isObject',
reportError: 'errorReporter',
};
}
/**
* Returns the name of the options object for a given variable
*/
getVariableOptionsName(variableName) {
return `${variableName}_options`;
}
/**
* Returns the name of the mutation function for a given variable
*/
getVariableMutationName(variableName) {
return `mutate_${variableName}`;
}
/**
* The variable name to hold the boolean if value is undefined or not
*/
getVariableExistsName(variableName) {
return `${variableName}_exists`;
}
/**
* Returns the declaration for the undefined and the null check
*/
getVariableExistsDeclaration(variableName) {
return `let ${this.getVariableExistsName(variableName)} = ${this.COMPILER_REFERENCES.exists}(${variableName})`;
}
/**
* Returns the expression to declare the mutation function for a given
* field.
*/
getMutationFnDeclararationExpression(variableName) {
return `function ${this.getVariableMutationName(variableName)} (newValue) {
${variableName} = newValue;
${this.getVariableExistsName(variableName)} = ${this.COMPILER_REFERENCES.exists}(${variableName});
}`;
}
/**
* Returns the expression to declare the options
*/
getOptionsDeclarationExpression(variableName, field, tip, pointer, arrayExpressionPointer) {
const arrayExpressionPointerItem = arrayExpressionPointer
? `\n arrayExpressionPointer: ${arrayExpressionPointer},`
: '';
return `const ${this.getVariableOptionsName(variableName)} = {
root,
refs,
field: ${field},
tip: ${tip},
pointer: ${pointer},${arrayExpressionPointerItem}
mutate: ${this.getVariableMutationName(variableName)},
${this.COMPILER_REFERENCES.reportError}
}`;
}
/**
* Returns the method call expression for executing validation
* a given rule
*/
getValidationCallableExpression(variableName, rule) {
const compiledOptions = JSON.stringify(rule.compiledOptions);
const options = this.getVariableOptionsName(variableName);
/**
* Use `validateAsync` when rule is async, otherwise use `validate`
*/
const methodCall = rule.async
? `await ${this.COMPILER_REFERENCES.validations}.${rule.name}.validate`
: `${this.COMPILER_REFERENCES.validations}.${rule.name}.validate`;
/**
* If rule doesn't want to get executed on undefined and null values, then make
* sure to add the `exists` guard first
*/
const existsGuard = rule.allowUndefineds
? ''
: `${this.getVariableExistsName(variableName)} && `;
const callableExpression = `${methodCall}(${variableName}, ${compiledOptions}, ${options})`;
return `${existsGuard}${callableExpression}`;
}
/**
* Converts a pointer to a Javascript expression
*/
pointerToExpression(pointer) {
return pointer.type === 'literal' ? `'${pointer.name}'` : pointer.name;
}
/**
* Converts an array of pointers to a Javascript expression
*/
pointersToExpression(pointer) {
let hasIdentifiers = false;
const pointerExpression = pointer
.map((one) => {
if (one.type === 'identifier') {
hasIdentifiers = true;
return `\$\{${one.name}}`;
}
return one.name;
})
.join('.');
return hasIdentifiers ? `\`${pointerExpression}\`` : `'${pointerExpression}'`;
}
/**
* Compiles a given node inside the schema tree. The compiled
* output is written to the buffer
*/
compileNode(field, node, buffer, parentPointer, referenceVariable, outVariable) {
field = typeof field === 'string' ? { name: field, type: 'literal' } : field;
/**
* Reference object for node compilers
*/
const references = {
outVariable: outVariable || 'out',
referenceVariable: referenceVariable || 'root',
parentPointer,
};
switch (node.type) {
case 'literal':
new Literal_1.LiteralCompiler(field, node, this, references).compile(buffer);
break;
case 'object':
new Object_1.ObjectCompiler(field, node, this, references).compile(buffer);
break;
case 'array':
new Array_1.ArrayCompiler(field, node, this, references).compile(buffer);
break;
}
}
/**
* Compiles all nodes for the schema tree recursively. The compiled
* output is written to the buffer.
*/
compileTree(tree, buffer, parentPointer, referenceVariable, outVariable) {
Object.keys(tree).forEach((field) => {
this.compileNode(field, tree[field], buffer, parentPointer, referenceVariable, outVariable);
});
}
/**
* Compiles the tree and returns the compiled code as a string.
*/
compileAsString() {
const buffer = new Buffer_1.CompilerBuffer();
/**
* We wrap the buffer output inside an async function with following arguments.
*
* - `root` is the object to validate
* - `validate` is the function to validate using synchronous rules
* - `validateAsync` is the function to validate using asynchronous rules
* - `isObject` checks whether the value is a valid Javascript object
* - `exists` checks whether the value is defined or not.
*/
buffer.wrappingCode([
'return async function (root, validations, errorReporter, helpers, refs) {',
'}',
]);
/**
* Declaring the out variable. The compiler code will write the
* validated properties to this variable
*/
buffer.writeExpression('const out = {}');
/**
* Parse the schema
*/
this.compileTree(this.schema, buffer, []);
/**
* Return the out value
*/
buffer.writeExpression(`
if (errorReporter.hasErrors) {
throw errorReporter.toError();
}
return out`, true);
buffer.dedent();
/**
* Return the buffer string
*/
return buffer.flush();
}
/**
* Compiles the schema tree to an executable function
*/
compile() {
return new Function(this.compileAsString())();
}
}
exports.Compiler = Compiler;
+32
View File
@@ -0,0 +1,32 @@
import { ApiErrorNode, MessagesBagContract, ErrorReporterContract } from '@ioc:Adonis/Core/Validator';
import { ValidationException } from '../ValidationException';
/**
* The API Error reporter formats messages as an array of objects
*/
export declare class ApiErrorReporter implements ErrorReporterContract<{
errors: ApiErrorNode[];
}> {
private messages;
private bail;
private errors;
/**
* A boolean to know if an error has been reported or
* not
*/
hasErrors: boolean;
constructor(messages: MessagesBagContract, bail: boolean);
/**
* Report a new error
*/
report(pointer: string, rule: string, message: string, arrayExpressionPointer?: string, args?: any): void;
/**
* Returns an instance of [[ValidationException]]
*/
toError(): ValidationException;
/**
* Return errors
*/
toJSON(): {
errors: ApiErrorNode[];
};
}
+60
View File
@@ -0,0 +1,60 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiErrorReporter = void 0;
const ValidationException_1 = require("../ValidationException");
/**
* The API Error reporter formats messages as an array of objects
*/
class ApiErrorReporter {
constructor(messages, bail) {
this.messages = messages;
this.bail = bail;
this.errors = [];
/**
* A boolean to know if an error has been reported or
* not
*/
this.hasErrors = false;
}
/**
* Report a new error
*/
report(pointer, rule, message, arrayExpressionPointer, args) {
this.hasErrors = true;
this.errors.push({
rule,
field: pointer,
message: this.messages.get(pointer, rule, message, arrayExpressionPointer, args),
...(args ? { args } : {}),
});
/**
* Raise exception right away when `bail=true`.
*/
if (this.bail) {
throw this.toError();
}
}
/**
* Returns an instance of [[ValidationException]]
*/
toError() {
return new ValidationException_1.ValidationException(false, this.toJSON());
}
/**
* Return errors
*/
toJSON() {
return {
errors: this.errors,
};
}
}
exports.ApiErrorReporter = ApiErrorReporter;
+32
View File
@@ -0,0 +1,32 @@
import { JsonApiErrorNode, MessagesBagContract, ErrorReporterContract } from '@ioc:Adonis/Core/Validator';
import { ValidationException } from '../ValidationException';
/**
* The JsonApiErrorReporter formats error messages as per the JSON API spec.
*/
export declare class JsonApiErrorReporter implements ErrorReporterContract<{
errors: JsonApiErrorNode[];
}> {
private messages;
private bail;
private errors;
/**
* A boolean to know if an error has been reported or
* not
*/
hasErrors: boolean;
constructor(messages: MessagesBagContract, bail: boolean);
/**
* Report a new error
*/
report(pointer: string, rule: string, message: string, arrayExpressionPointer?: string, args?: any): void;
/**
* Returns an instance of [[ValidationException]]
*/
toError(): ValidationException;
/**
* Return errors
*/
toJSON(): {
errors: JsonApiErrorNode[];
};
}
+62
View File
@@ -0,0 +1,62 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonApiErrorReporter = void 0;
const ValidationException_1 = require("../ValidationException");
/**
* The JsonApiErrorReporter formats error messages as per the JSON API spec.
*/
class JsonApiErrorReporter {
constructor(messages, bail) {
this.messages = messages;
this.bail = bail;
this.errors = [];
/**
* A boolean to know if an error has been reported or
* not
*/
this.hasErrors = false;
}
/**
* Report a new error
*/
report(pointer, rule, message, arrayExpressionPointer, args) {
this.hasErrors = true;
this.errors.push({
code: rule,
source: {
pointer,
},
title: this.messages.get(pointer, rule, message, arrayExpressionPointer, args),
...(args ? { meta: args } : {}),
});
/**
* Raise exception right away when `bail=true`.
*/
if (this.bail) {
throw this.toError();
}
}
/**
* Returns an instance of [[ValidationException]]
*/
toError() {
return new ValidationException_1.ValidationException(false, this.toJSON());
}
/**
* Return errors
*/
toJSON() {
return {
errors: this.errors,
};
}
}
exports.JsonApiErrorReporter = JsonApiErrorReporter;
+33
View File
@@ -0,0 +1,33 @@
import { VanillaErrorNode, MessagesBagContract, ErrorReporterContract } from '@ioc:Adonis/Core/Validator';
import { ValidationException } from '../ValidationException';
/**
* The vanilla error reporter to stores an array of messages in
* reference to a given field. Tailored for displaying messages
* next to a form field.
*/
export declare class VanillaErrorReporter implements ErrorReporterContract<VanillaErrorNode> {
private messages;
private bail;
/**
* Collected errors
*/
private errors;
/**
* A boolean to know if an error has been reported or
* not
*/
hasErrors: boolean;
constructor(messages: MessagesBagContract, bail: boolean);
/**
* Report a new error
*/
report(pointer: string, rule: string, message: string, arrayExpressionPointer?: string, args?: any): void;
/**
* Returns an instance of [[ValidationException]]
*/
toError(): ValidationException;
/**
* Return errors
*/
toJSON(): VanillaErrorNode;
}
+59
View File
@@ -0,0 +1,59 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.VanillaErrorReporter = void 0;
const ValidationException_1 = require("../ValidationException");
/**
* The vanilla error reporter to stores an array of messages in
* reference to a given field. Tailored for displaying messages
* next to a form field.
*/
class VanillaErrorReporter {
constructor(messages, bail) {
this.messages = messages;
this.bail = bail;
/**
* Collected errors
*/
this.errors = {};
/**
* A boolean to know if an error has been reported or
* not
*/
this.hasErrors = false;
}
/**
* Report a new error
*/
report(pointer, rule, message, arrayExpressionPointer, args) {
this.hasErrors = true;
this.errors[pointer] = this.errors[pointer] || [];
this.errors[pointer].push(this.messages.get(pointer, rule, message, arrayExpressionPointer, args));
/**
* Raise exception right away when `bail=true`.
*/
if (this.bail) {
throw this.toError();
}
}
/**
* Returns an instance of [[ValidationException]]
*/
toError() {
return new ValidationException_1.ValidationException(true, this.toJSON());
}
/**
* Return errors
*/
toJSON() {
return this.errors;
}
}
exports.VanillaErrorReporter = VanillaErrorReporter;
+3
View File
@@ -0,0 +1,3 @@
export { ApiErrorReporter } from './Api';
export { VanillaErrorReporter } from './Vanilla';
export { JsonApiErrorReporter } from './JsonApi';
+17
View File
@@ -0,0 +1,17 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonApiErrorReporter = exports.VanillaErrorReporter = exports.ApiErrorReporter = void 0;
var Api_1 = require("./Api");
Object.defineProperty(exports, "ApiErrorReporter", { enumerable: true, get: function () { return Api_1.ApiErrorReporter; } });
var Vanilla_1 = require("./Vanilla");
Object.defineProperty(exports, "VanillaErrorReporter", { enumerable: true, get: function () { return Vanilla_1.VanillaErrorReporter; } });
var JsonApi_1 = require("./JsonApi");
Object.defineProperty(exports, "JsonApiErrorReporter", { enumerable: true, get: function () { return JsonApi_1.JsonApiErrorReporter; } });
+18
View File
@@ -0,0 +1,18 @@
import { MessagesBagContract, CustomMessages } from '@ioc:Adonis/Core/Validator';
/**
* Message bag exposes the API to pull the most appropriate message for a
* given validation failure.
*/
export declare class MessagesBag implements MessagesBagContract {
private messages;
private wildCardCallback;
constructor(messages: CustomMessages);
/**
* Transform message by replace placeholders with runtime values
*/
private transform;
/**
* Returns the most appropriate message for the validation failure.
*/
get(pointer: string, rule: string, message: string, arrayExpressionPointer?: string, args?: any): string;
}
+62
View File
@@ -0,0 +1,62 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessagesBag = void 0;
const helpers_1 = require("@poppinss/utils/build/helpers");
/**
* Message bag exposes the API to pull the most appropriate message for a
* given validation failure.
*/
class MessagesBag {
constructor(messages) {
this.messages = messages;
this.wildCardCallback = typeof this.messages['*'] === 'function' ? this.messages['*'] : undefined;
}
/**
* Transform message by replace placeholders with runtime values
*/
transform(message, rule, pointer, args) {
/**
* No interpolation required
*/
if (!message.includes('{{')) {
return message;
}
return (0, helpers_1.interpolate)(message, { rule, field: pointer, options: args || {} });
}
/**
* Returns the most appropriate message for the validation failure.
*/
get(pointer, rule, message, arrayExpressionPointer, args) {
let validationMessage = this.messages[`${pointer}.${rule}`];
/**
* Fetch message for the array expression pointer if it exists
*/
if (!validationMessage && arrayExpressionPointer) {
validationMessage = this.messages[`${arrayExpressionPointer}.${rule}`];
}
/**
* Fallback to the message for the rule
*/
if (!validationMessage) {
validationMessage = this.messages[rule];
}
/**
* Transform and return message. The wildcard callback is invoked when custom message
* is not defined
*/
return validationMessage
? this.transform(validationMessage, rule, pointer, args)
: this.wildCardCallback
? this.wildCardCallback(pointer, rule, arrayExpressionPointer, args)
: message;
}
}
exports.MessagesBag = MessagesBag;
+11
View File
@@ -0,0 +1,11 @@
import { Rules, Rule } from '@ioc:Adonis/Core/Validator';
/**
* Returns a function that can be used to target
* validations
*/
export declare function getRuleFn(name: string): (...args: any) => Rule;
/**
* A key value pair to define a rule on a given field
*/
declare const rules: Rules;
export { rules };
+53
View File
@@ -0,0 +1,53 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rules = exports.getRuleFn = void 0;
const validations = __importStar(require("../Validations"));
/**
* Returns a function that can be used to target
* validations
*/
function getRuleFn(name) {
return function ruleFn(...args) {
return { name, options: args[0] === undefined ? [] : args };
};
}
exports.getRuleFn = getRuleFn;
/**
* A key value pair to define a rule on a given field
*/
const rules = Object.keys(validations).reduce((result, name) => {
result[name] = getRuleFn(name);
return result;
}, {});
exports.rules = rules;
+6
View File
@@ -0,0 +1,6 @@
import { Schema } from '@ioc:Adonis/Core/Validator';
/**
* List of available schema methods. One can add custom types by
* using the extend method
*/
export declare const schema: Schema;
+272
View File
@@ -0,0 +1,272 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.schema = void 0;
const utils_1 = require("../utils");
/**
* String schema type
*/
function string(options, rules) {
if (!rules && Array.isArray(options)) {
rules = options;
options = {};
}
return (0, utils_1.getLiteralType)('string', false, false, options, rules || []);
}
string.optional = function optionalString(options, rules) {
if (!rules && Array.isArray(options)) {
rules = options;
options = {};
}
return (0, utils_1.getLiteralType)('string', true, false, options, rules || []);
};
string.nullable = function nullableString(options, rules) {
if (!rules && Array.isArray(options)) {
rules = options;
options = {};
}
return (0, utils_1.getLiteralType)('string', false, true, options, rules || []);
};
string.nullableAndOptional = function nullableAndOptionalString(options, rules) {
if (!rules && Array.isArray(options)) {
rules = options;
options = {};
}
return (0, utils_1.getLiteralType)('string', true, true, options, rules || []);
};
/**
* Boolean schema type
*/
function boolean(rules) {
return (0, utils_1.getLiteralType)('boolean', false, false, undefined, rules || []);
}
boolean.optional = function optionalBoolean(rules) {
return (0, utils_1.getLiteralType)('boolean', true, false, undefined, rules || []);
};
boolean.nullable = function nullableBoolean(rules) {
return (0, utils_1.getLiteralType)('boolean', false, true, undefined, rules || []);
};
boolean.nullableAndOptional = function nullableAndOptionalBoolean(rules) {
return (0, utils_1.getLiteralType)('boolean', true, true, undefined, rules || []);
};
/**
* Number schema type
*/
function number(rules) {
return (0, utils_1.getLiteralType)('number', false, false, undefined, rules || []);
}
number.optional = function optionalNumber(rules) {
return (0, utils_1.getLiteralType)('number', true, false, undefined, rules || []);
};
number.nullable = function nullableNumber(rules) {
return (0, utils_1.getLiteralType)('number', false, true, undefined, rules || []);
};
number.nullableAndOptional = function nullableAndOptionalNumber(rules) {
return (0, utils_1.getLiteralType)('number', true, true, undefined, rules || []);
};
/**
* Date schema type
*/
function date(options, rules) {
return (0, utils_1.getLiteralType)('date', false, false, options, rules || []);
}
date.optional = function optionalDate(options, rules) {
return (0, utils_1.getLiteralType)('date', true, false, options, rules || []);
};
date.nullable = function nullableDate(options, rules) {
return (0, utils_1.getLiteralType)('date', false, true, options, rules || []);
};
date.nullableAndOptional = function nullableAndOptionalDate(options, rules) {
return (0, utils_1.getLiteralType)('date', true, true, options, rules || []);
};
/**
* Object schema type
*/
function object(rules) {
return {
members(schema) {
return (0, utils_1.getObjectType)(false, false, Object.keys(schema).reduce((result, field) => {
result[field] = schema[field].getTree();
return result;
}, {}), rules || []);
},
anyMembers() {
return (0, utils_1.getObjectType)(false, false, null, rules || []);
},
};
}
object.optional = function optionalObject(rules) {
return {
members(schema) {
return (0, utils_1.getObjectType)(true, false, Object.keys(schema).reduce((result, field) => {
result[field] = schema[field].getTree();
return result;
}, {}), rules || []);
},
anyMembers() {
return (0, utils_1.getObjectType)(true, false, null, rules || []);
},
};
};
object.nullable = function nullableObject(rules) {
return {
members(schema) {
return (0, utils_1.getObjectType)(false, true, Object.keys(schema).reduce((result, field) => {
result[field] = schema[field].getTree();
return result;
}, {}), rules || []);
},
anyMembers() {
return (0, utils_1.getObjectType)(false, true, null, rules || []);
},
};
};
object.nullableAndOptional = function nullableAndOptionalObject(rules) {
return {
members(schema) {
return (0, utils_1.getObjectType)(true, true, Object.keys(schema).reduce((result, field) => {
result[field] = schema[field].getTree();
return result;
}, {}), rules || []);
},
anyMembers() {
return (0, utils_1.getObjectType)(true, true, null, rules || []);
},
};
};
/**
* Array schema type
*/
function array(rules) {
return {
members(schema) {
return (0, utils_1.getArrayType)(false, false, schema.getTree(), rules || []);
},
anyMembers() {
return (0, utils_1.getArrayType)(false, false, null, rules || []);
},
};
}
array.optional = function optionalArray(rules) {
return {
members(schema) {
return (0, utils_1.getArrayType)(true, false, schema.getTree(), rules || []);
},
anyMembers() {
return (0, utils_1.getArrayType)(true, false, null, rules || []);
},
};
};
array.nullable = function nullableArray(rules) {
return {
members(schema) {
return (0, utils_1.getArrayType)(false, true, schema.getTree(), rules || []);
},
anyMembers() {
return (0, utils_1.getArrayType)(false, true, null, rules || []);
},
};
};
array.nullableAndOptional = function nullableAndOptionalArray(rules) {
return {
members(schema) {
return (0, utils_1.getArrayType)(true, true, schema.getTree(), rules || []);
},
anyMembers() {
return (0, utils_1.getArrayType)(true, true, null, rules || []);
},
};
};
/**
* Enum schema type
*/
function oneOf(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enum', false, false, enumOptions, rules || []);
}
oneOf.optional = function optionalEnum(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enum', true, false, enumOptions, rules || []);
};
oneOf.nullable = function nullableEnum(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enum', false, true, enumOptions, rules || []);
};
oneOf.nullableAndOptional = function nullableAndOptionalEnum(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enum', true, true, enumOptions, rules || []);
};
/**
* Enum set schema type
*/
function enumSet(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enumSet', false, false, enumOptions, rules || []);
}
enumSet.optional = function optionalEnumSet(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enumSet', true, false, enumOptions, rules || []);
};
enumSet.nullable = function nullableEnumSet(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enumSet', false, true, enumOptions, rules || []);
};
enumSet.nullableAndOptional = function nullableAndOptionalEnumSet(enumOptions, rules) {
return (0, utils_1.getLiteralType)('enumSet', true, true, enumOptions, rules || []);
};
/**
* File schema type
*/
function file(options, rules) {
return (0, utils_1.getLiteralType)('file', false, false, options, rules || []);
}
file.optional = function optionalFile(options, rules) {
return (0, utils_1.getLiteralType)('file', true, false, options, rules || []);
};
file.nullable = function nullableFile(options, rules) {
return (0, utils_1.getLiteralType)('file', false, true, options, rules || []);
};
file.nullableAndOptional = function nullableAndOptionalFile(options, rules) {
return (0, utils_1.getLiteralType)('file', true, true, options, rules || []);
};
/**
* Define refs, which are resolved at runtime vs the compile time
*/
function refs(schemaRefs) {
return Object.keys(schemaRefs).reduce((result, key) => {
result[key] = {
__$isRef: true,
value: schemaRefs[key],
key: key,
};
return result;
}, {});
}
/**
* List of available schema methods. One can add custom types by
* using the extend method
*/
exports.schema = {
string,
boolean,
number,
date,
object,
array,
enum: oneOf,
enumSet: enumSet,
file,
refs,
/**
* Create a new schema compiled schema tree
*/
create(tree) {
return {
props: {},
tree: Object.keys(tree).reduce((result, field) => {
result[field] = tree[field].getTree();
return result;
}, {}),
};
},
};
@@ -0,0 +1,15 @@
import { Exception } from '@poppinss/utils';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
/**
* Validation exception raised by the error reporters. The handle method is called
* automatically during an HTTP request by AdonisJS to self handle the exception
*/
export declare class ValidationException extends Exception {
flashToSession: boolean;
messages?: any;
constructor(flashToSession: boolean, messages?: any);
/**
* Handle exception.
*/
handle(error: ValidationException, ctx: HttpContextContract): Promise<void>;
}
@@ -0,0 +1,49 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationException = void 0;
const utils_1 = require("@poppinss/utils");
/**
* Validation exception raised by the error reporters. The handle method is called
* automatically during an HTTP request by AdonisJS to self handle the exception
*/
class ValidationException extends utils_1.Exception {
constructor(flashToSession, messages) {
super('Validation Exception', 422, 'E_VALIDATION_FAILURE');
this.flashToSession = flashToSession;
this.messages = messages;
}
/**
* Handle exception.
*/
async handle(error, ctx) {
/**
* Return the error messages as it is when `flashToSession` is explicitly disabled
* or session module is not installed
*/
if (!error.flashToSession || !ctx['session']) {
return ctx.response.status(error.status).send(error.messages);
}
const session = ctx['session'];
/**
* Flash all input, except the `_csrf`.
*/
session.flashExcept(['_csrf', '_method']);
/**
* Flash errors
*/
ctx['session'].flash('errors', error.messages);
/**
* Redirect back with the query string
*/
ctx.response.redirect('back', true);
}
}
exports.ValidationException = ValidationException;
@@ -0,0 +1,7 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure that the value of one or more properties inside an array are distinct
*/
export declare const distinct: SyncValidation<{
field: string;
}>;
@@ -0,0 +1,55 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.distinct = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'distinct';
const DEFAULT_MESSAGE = 'distinct validation failed';
/**
* Ensure that the value of one or more properties inside an array are distinct
*/
exports.distinct = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['array'], ([field]) => {
if (typeof field !== 'string' || !field) {
throw new Error(`${RULE_NAME}: expects a "field" property`);
}
return {
compiledOptions: {
field,
},
};
}),
validate(values, { field }, { errorReporter, pointer, arrayExpressionPointer }) {
if (!Array.isArray(values)) {
return;
}
const processed = new Set();
for (let item of values) {
/**
* If field is a `*`, then we are dealing with top level array nodes
*/
const value = field === '*' ? item : item[field];
/**
* Value already exists, hence a duplicate
*/
if (processed.has(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
field: field === '*' ? processed.size : field,
index: processed.size,
});
processed.clear();
break;
}
else {
processed.add(value);
}
}
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/offset';
/**
* Ensure the value is one of the defined choices
*/
export declare const after: SyncValidation<CompileReturnType>;
+26
View File
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.after = void 0;
const offset_1 = require("./helpers/offset");
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'after';
const DEFAULT_MESSAGE = 'after date validation failed';
/**
* Ensure the value is one of the defined choices
*/
exports.after = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['date'], (options) => {
return (0, offset_1.compile)(RULE_NAME, '>', options);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, offset_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/field';
/**
* Ensure the date is after the defined field.
*/
export declare const afterField: SyncValidation<CompileReturnType>;
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.afterField = void 0;
const helpers_1 = require("../../Validator/helpers");
const field_1 = require("./helpers/field");
const RULE_NAME = 'afterField';
const DEFAULT_MESSAGE = 'after date validation failed';
/**
* Ensure the date is after the defined field.
*/
exports.afterField = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], (options, _, __, rulesTree) => {
return (0, field_1.compile)(RULE_NAME, '>', options, rulesTree);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, field_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/offset';
/**
* Ensure the value is one of the defined choices
*/
export declare const afterOrEqual: SyncValidation<CompileReturnType>;
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.afterOrEqual = void 0;
const helpers_1 = require("../../Validator/helpers");
const offset_1 = require("./helpers/offset");
const RULE_NAME = 'afterOrEqual';
const DEFAULT_MESSAGE = 'afterOrEqual date validation failed';
/**
* Ensure the value is one of the defined choices
*/
exports.afterOrEqual = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['date'], (options) => {
return (0, offset_1.compile)(RULE_NAME, '>=', options);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, offset_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/field';
/**
* Ensure the date is after the defined field.
*/
export declare const afterOrEqualToField: SyncValidation<CompileReturnType>;
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.afterOrEqualToField = void 0;
const helpers_1 = require("../../Validator/helpers");
const field_1 = require("./helpers/field");
const RULE_NAME = 'afterOrEqualToField';
const DEFAULT_MESSAGE = 'after or equal to date validation failed';
/**
* Ensure the date is after the defined field.
*/
exports.afterOrEqualToField = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], (options, _, __, rulesTree) => {
return (0, field_1.compile)(RULE_NAME, '>=', options, rulesTree);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, field_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/offset';
/**
* Ensure the value is one of the defined choices
*/
export declare const before: SyncValidation<CompileReturnType>;
+26
View File
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.before = void 0;
const offset_1 = require("./helpers/offset");
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'before';
const DEFAULT_MESSAGE = 'before date validation failed';
/**
* Ensure the value is one of the defined choices
*/
exports.before = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['date'], (options) => {
return (0, offset_1.compile)(RULE_NAME, '<', options);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, offset_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/field';
/**
* Ensure the date is after the defined field.
*/
export declare const beforeField: SyncValidation<CompileReturnType>;
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.beforeField = void 0;
const helpers_1 = require("../../Validator/helpers");
const field_1 = require("./helpers/field");
const RULE_NAME = 'beforeField';
const DEFAULT_MESSAGE = 'before date validation failed';
/**
* Ensure the date is after the defined field.
*/
exports.beforeField = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], (options, _, __, rulesTree) => {
return (0, field_1.compile)(RULE_NAME, '<', options, rulesTree);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, field_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/offset';
/**
* Ensure the value is one of the defined choices
*/
export declare const beforeOrEqual: SyncValidation<CompileReturnType>;
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.beforeOrEqual = void 0;
const offset_1 = require("./helpers/offset");
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'beforeOrEqual';
const DEFAULT_MESSAGE = 'beforeOrEqual date validation failed';
/**
* Ensure the value is one of the defined choices
*/
exports.beforeOrEqual = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['date'], (options) => {
return (0, offset_1.compile)(RULE_NAME, '<=', options);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, offset_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { CompileReturnType } from './helpers/field';
/**
* Ensure the date is after the defined field.
*/
export declare const beforeOrEqualToField: SyncValidation<CompileReturnType>;
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.beforeOrEqualToField = void 0;
const helpers_1 = require("../../Validator/helpers");
const field_1 = require("./helpers/field");
const RULE_NAME = 'beforeOrEqualToField';
const DEFAULT_MESSAGE = 'before or equal to date validation failed';
/**
* Ensure the date is after the defined field.
*/
exports.beforeOrEqualToField = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], (options, _, __, rulesTree) => {
return (0, field_1.compile)(RULE_NAME, '<=', options, rulesTree);
}),
validate(value, compiledOptions, runtimeOptions) {
return (0, field_1.validate)(RULE_NAME, DEFAULT_MESSAGE, value, compiledOptions, runtimeOptions);
},
};
@@ -0,0 +1,19 @@
import { ValidationRuntimeOptions } from '@ioc:Adonis/Core/Validator';
/**
* Return type of the compile function
*/
export type CompileReturnType = {
operator: '>' | '<' | '>=' | '<=';
field: string;
format?: string;
};
/**
* Compiles a date field comparison rule
*/
export declare function compile(ruleName: string, operator: '>' | '<' | '>=' | '<=', [field]: any[], rulesTree: any): {
compiledOptions: CompileReturnType;
};
/**
* Validates date field comparison rule
*/
export declare function validate(ruleName: string, errorMessage: string, value: any, { field, operator, format }: CompileReturnType, { root, tip, errorReporter, pointer, arrayExpressionPointer }: ValidationRuntimeOptions): void;
@@ -0,0 +1,75 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = exports.compile = void 0;
const luxon_1 = require("luxon");
const toLuxon_1 = require("./toLuxon");
const helpers_1 = require("../../../Validator/helpers");
/**
* Returns a luxon date time instance based upon the unit, duration and operator
*/
function compareDateTime(lhs, rhs, operator) {
switch (operator) {
case '>':
return lhs > rhs;
case '<':
return lhs < rhs;
case '>=':
return lhs >= rhs;
case '<=':
return lhs <= rhs;
}
}
/**
* Compiles a date field comparison rule
*/
function compile(ruleName, operator, [field], rulesTree) {
if (!field) {
throw new Error(`${ruleName}: expects a comparison "field"`);
}
return {
compiledOptions: {
operator,
field,
format: rulesTree.date?.format,
},
};
}
exports.compile = compile;
/**
* Validates date field comparison rule
*/
function validate(ruleName, errorMessage, value, { field, operator, format }, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
/**
* Skip when value is not a date time instance. One must use date schema
* type
*/
if (luxon_1.DateTime.isDateTime(value) === false) {
return;
}
const comparisonValue = (0, toLuxon_1.toLuxon)((0, helpers_1.getFieldValue)(field, root, tip), format);
/**
* Raise error when comparison field is not a valid date
*/
if (!comparisonValue || !comparisonValue.isValid) {
errorReporter.report(pointer, ruleName, errorMessage, arrayExpressionPointer, {
otherField: field,
otherFieldValue: comparisonValue,
});
return;
}
if (!compareDateTime(value, comparisonValue, operator)) {
errorReporter.report(pointer, ruleName, errorMessage, arrayExpressionPointer, {
otherField: field,
otherFieldValue: comparisonValue,
});
}
}
exports.validate = validate;
@@ -0,0 +1,23 @@
import { ValidationRuntimeOptions, DurationUnits } from '@ioc:Adonis/Core/Validator';
/**
* Return type of the compile function
*/
export type CompileReturnType = {
operator: '>' | '<' | '>=' | '<=';
offset?: {
duration: number;
unit: DurationUnits;
hasDayDuration: boolean;
};
ref?: string;
};
/**
* Compiles an offset based date rule
*/
export declare function compile(ruleName: string, operator: '>' | '<' | '>=' | '<=', [duration, unit]: any[]): {
compiledOptions: CompileReturnType;
};
/**
* Validates offset based date rules
*/
export declare function validate(ruleName: string, errorMessage: string, value: any, compiledOptions: CompileReturnType, { errorReporter, pointer, arrayExpressionPointer, refs }: ValidationRuntimeOptions): void;
@@ -0,0 +1,143 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = exports.compile = void 0;
const luxon_1 = require("luxon");
const helpers_1 = require("../../../Validator/helpers");
/**
* Returns a luxon date time instance based upon the unit, duration and operator
*/
function getDateTime(operator, { unit, duration }) {
if (operator === '>' || operator === '>=') {
return luxon_1.DateTime.local().plus({ [unit]: duration });
}
return luxon_1.DateTime.local().minus({ [unit]: duration });
}
/**
* Returns a luxon date time instance based upon the unit, duration and operator
*/
function compareDateTime(lhs, rhs, operator, options) {
if (options && options.hasDayDuration) {
if (operator === '>') {
return lhs.startOf('day') > rhs.startOf('day');
}
else if (operator === '>=') {
return lhs.startOf('day') >= rhs.startOf('day');
}
else if (operator === '<') {
return lhs.startOf('day') < rhs.startOf('day');
}
else if (operator === '<=') {
return lhs.startOf('day') <= rhs.startOf('day');
}
}
if (operator === '>') {
return lhs > rhs;
}
else if (operator === '>=') {
return lhs >= rhs;
}
else if (operator === '<') {
return lhs < rhs;
}
else if (operator === '<=') {
return lhs <= rhs;
}
}
/**
* Compiles an offset based date rule
*/
function compile(ruleName, operator, [duration, unit]) {
/**
* Choices are defined as a ref
*/
if ((0, helpers_1.isRef)(duration)) {
return {
compiledOptions: { ref: duration.key, operator },
};
}
/**
* Converting "today" keyword to offset
*/
if (duration === 'today') {
return {
compiledOptions: {
operator,
offset: {
duration: 0,
unit: 'days',
hasDayDuration: true,
},
},
};
}
/**
* Converting "tomorrow", "yesterday" keywords to offset
*/
if (['tomorrow', 'yesterday'].includes(duration)) {
return {
compiledOptions: {
operator,
offset: {
duration: 1,
unit: 'days',
hasDayDuration: true,
},
},
};
}
/**
* Ensure value is an array or a ref
*/
if (!duration || !unit) {
throw new Error(`"${ruleName}": expects a date offset "duration" and "unit" or a "ref"`);
}
/**
* Ensure interval is a valid number
*/
if (typeof duration !== 'number') {
throw new Error(`"${ruleName}": expects "duration" to be a number`);
}
return {
compiledOptions: {
operator,
offset: { duration, unit, hasDayDuration: ['day', 'days'].includes(unit) },
},
};
}
exports.compile = compile;
/**
* Validates offset based date rules
*/
function validate(ruleName, errorMessage, value, compiledOptions, { errorReporter, pointer, arrayExpressionPointer, refs }) {
let comparisonDate;
/**
* Do not run validation when original value is not a dateTime instance.
*/
if (luxon_1.DateTime.isDateTime(value) === false) {
return;
}
/**
* Resolve datetime to compare against
*/
if (compiledOptions.ref) {
comparisonDate = refs[compiledOptions.ref].value;
}
else if (compiledOptions.offset) {
comparisonDate = getDateTime(compiledOptions.operator, compiledOptions.offset);
}
(0, helpers_1.enforceDateTime)(comparisonDate, `"${ruleName}": expects "refs.${compiledOptions.ref}" to be an instance of luxon DateTime object`);
if (!compareDateTime(value, comparisonDate, compiledOptions.operator, compiledOptions.offset)) {
errorReporter.report(pointer, ruleName, errorMessage, arrayExpressionPointer, {
[ruleName]: comparisonDate.toISO(),
});
}
}
exports.validate = validate;
@@ -0,0 +1,5 @@
import { DateTime } from 'luxon';
/**
* Convers a value to an instance of datetime
*/
export declare function toLuxon(value: any, format: string | undefined): DateTime | undefined;
@@ -0,0 +1,43 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.toLuxon = void 0;
const luxon_1 = require("luxon");
/**
* A list of pre-defined formats and their luxon specific methods
*/
const PREDEFINED_FORMATS = {
rfc2822: 'fromRFC2822',
http: 'fromHTTP',
sql: 'fromSQL',
iso: 'fromISO',
};
/**
* Convers a value to an instance of datetime
*/
function toLuxon(value, format) {
let dateTime;
/**
* If value is a date instance or a string, then convert it to an instance
* of luxon.DateTime.
*/
if (value instanceof Date === true) {
dateTime = luxon_1.DateTime.fromJSDate(value);
}
else if (luxon_1.DateTime.isDateTime(value)) {
dateTime = value;
}
else if (typeof value === 'string') {
const formatterFn = PREDEFINED_FORMATS[format || 'iso'];
dateTime = formatterFn ? luxon_1.DateTime[formatterFn](value) : luxon_1.DateTime.fromFormat(value, format);
}
return dateTime;
}
exports.toLuxon = toLuxon;
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensures that the field value has been confirmed using `{{field}}_confirmation` field.
* Useful for password confirmation.
*/
export declare const confirmed: SyncValidation;
@@ -0,0 +1,50 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.confirmed = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'confirmed';
const DEFAULT_MESSAGE = 'confirmed validation failed';
/**
* Ensures that the field value has been confirmed using `{{field}}_confirmation` field.
* Useful for password confirmation.
*/
exports.confirmed = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['string', 'boolean', 'number', 'enum'], (args) => {
const res = {
compiledOptions: {
confirmationFieldName: args[0],
},
};
return res;
}),
validate(value, { confirmationFieldName }, { errorReporter, field, pointer, arrayExpressionPointer, root, tip }) {
if (!(0, helpers_1.exists)(value)) {
return;
}
confirmationFieldName = confirmationFieldName || `${field}_confirmation`;
/**
* We check to same value is not the type. Since it's possible that the original
* value is casted using a sub rule like `number`. However, the confirmed
* value is still a string.
*
* For example:
* age: schema.number([ rules.confirmed() ])
*
* Over HTTP the `age` and the `age_confirmation` field will both be strings. However,
* the `number` rule will cast the `age` to a number. So the type check with the
* confirmed rule will fail.
*/
// eslint-disable-next-line eqeqeq
if ((0, helpers_1.getFieldValue)(confirmationFieldName, root, tip) != value) {
errorReporter.report((0, helpers_1.resolveAbsoluteName)(confirmationFieldName, pointer), RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
}
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const nullable: SyncValidation;
@@ -0,0 +1,30 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.nullable = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'nullable';
const DEFAULT_MESSAGE = 'nullable validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.nullable = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], () => {
return {
allowUndefineds: true,
};
}),
validate(value, _, { errorReporter, pointer, arrayExpressionPointer }) {
if (value === undefined || value === '') {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
}
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const required: SyncValidation;
@@ -0,0 +1,30 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.required = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'required';
const DEFAULT_MESSAGE = 'required validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.required = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], () => {
return {
allowUndefineds: true,
};
}),
validate(value, _, { errorReporter, pointer, arrayExpressionPointer }) {
if (!(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
}
},
};
@@ -0,0 +1,8 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const requiredIfExists: SyncValidation<{
field: string;
}>;
@@ -0,0 +1,39 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredIfExists = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfExists';
const DEFAULT_MESSAGE = 'requiredIfExists validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.requiredIfExists = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([field]) => {
if (!field) {
throw new Error(`"${RULE_NAME}": expects a "field"`);
}
return {
allowUndefineds: true,
compiledOptions: {
field,
},
};
}),
validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
const otherFieldExists = (0, helpers_1.exists)((0, helpers_1.getFieldValue)(compiledOptions.field, root, tip));
if (otherFieldExists && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
otherField: compiledOptions.field,
});
}
},
};
@@ -0,0 +1,8 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const requiredIfExistsAll: SyncValidation<{
fields: string[];
}>;
@@ -0,0 +1,45 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredIfExistsAll = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfExistsAll';
const DEFAULT_MESSAGE = 'requiredIfExistsAll validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.requiredIfExistsAll = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([fields]) => {
if (!fields) {
throw new Error(`"${RULE_NAME}": expects an array of "fields"`);
}
if (!Array.isArray(fields)) {
throw new Error(`"${RULE_NAME}": expects "fields" to be an array`);
}
return {
allowUndefineds: true,
compiledOptions: {
fields,
},
};
}),
validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
const allFieldsExists = compiledOptions.fields.every((field) => {
const otherFieldValue = (0, helpers_1.getFieldValue)(field, root, tip);
return (0, helpers_1.exists)(otherFieldValue);
});
if (allFieldsExists && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
otherFields: compiledOptions.fields,
});
}
},
};
@@ -0,0 +1,8 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const requiredIfExistsAny: SyncValidation<{
fields: string[];
}>;
@@ -0,0 +1,45 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredIfExistsAny = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfExistsAny';
const DEFAULT_MESSAGE = 'requiredIfExistsAny validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.requiredIfExistsAny = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([fields]) => {
if (!fields) {
throw new Error(`"${RULE_NAME}": expects an array of "fields"`);
}
if (!Array.isArray(fields)) {
throw new Error(`"${RULE_NAME}": expects "fields" to be an array`);
}
return {
allowUndefineds: true,
compiledOptions: {
fields,
},
};
}),
validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
const anyFieldExists = compiledOptions.fields.find((field) => {
const otherFieldValue = (0, helpers_1.getFieldValue)(field, root, tip);
return (0, helpers_1.exists)(otherFieldValue);
});
if (anyFieldExists && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
otherFields: compiledOptions.fields,
});
}
},
};
@@ -0,0 +1,8 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const requiredIfNotExists: SyncValidation<{
field: string;
}>;
@@ -0,0 +1,40 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredIfNotExists = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfNotExists';
const DEFAULT_MESSAGE = 'requiredIfNotExists validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.requiredIfNotExists = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([field]) => {
if (!field) {
throw new Error(`"${RULE_NAME}": expects a "field"`);
}
return {
allowUndefineds: true,
compiledOptions: {
field,
},
};
}),
validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
const otherFieldValue = (0, helpers_1.getFieldValue)(compiledOptions.field, root, tip);
const otherFieldMissing = !(0, helpers_1.exists)(otherFieldValue);
if (otherFieldMissing && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
otherField: compiledOptions.field,
});
}
},
};
@@ -0,0 +1,8 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const requiredIfNotExistsAll: SyncValidation<{
fields: string[];
}>;
@@ -0,0 +1,45 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredIfNotExistsAll = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfNotExistsAll';
const DEFAULT_MESSAGE = 'requiredIfNotExistsAll validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.requiredIfNotExistsAll = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([fields]) => {
if (!fields) {
throw new Error(`"${RULE_NAME}": expects an array of "fields"`);
}
if (!Array.isArray(fields)) {
throw new Error(`"${RULE_NAME}": expects "fields" to be an array`);
}
return {
allowUndefineds: true,
compiledOptions: {
fields,
},
};
}),
validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
const allFieldsMissing = compiledOptions.fields.every((field) => {
const otherFieldValue = (0, helpers_1.getFieldValue)(field, root, tip);
return !(0, helpers_1.exists)(otherFieldValue);
});
if (allFieldsMissing && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
otherFields: compiledOptions.fields,
});
}
},
};
@@ -0,0 +1,8 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
export declare const requiredIfNotExistsAny: SyncValidation<{
fields: string[];
}>;
@@ -0,0 +1,45 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredIfNotExistsAny = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfNotExistsAny';
const DEFAULT_MESSAGE = 'requiredIfNotExistsAny validation failed';
/**
* Ensure the value exists. `null`, `undefined` and `empty string`
* fails the validation
*/
exports.requiredIfNotExistsAny = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([fields]) => {
if (!fields) {
throw new Error(`"${RULE_NAME}": expects an array of "fields"`);
}
if (!Array.isArray(fields)) {
throw new Error(`"${RULE_NAME}": expects "fields" to be an array`);
}
return {
allowUndefineds: true,
compiledOptions: {
fields,
},
};
}),
validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
const anyFieldMissing = compiledOptions.fields.find((field) => {
const otherFieldValue = (0, helpers_1.getFieldValue)(field, root, tip);
return !(0, helpers_1.exists)(otherFieldValue);
});
if (anyFieldMissing && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
otherFields: compiledOptions.fields,
});
}
},
};
@@ -0,0 +1,81 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Return value of the compile function
*/
type CompileReturnType = {
operator: keyof typeof OPERATORS;
field: string;
comparisonValues?: any | any[];
ref?: string;
};
/**
* Available operators
*/
declare const OPERATORS: {
/**
* Handles the "in" operator. Also ensures, the comparison values are an
* array or a ref.
*/
in: {
compile(comparisonValues: any): void;
passes: (value: any, comparisonValues: any[]) => boolean;
};
/**
* Handles the "notIn" operator. Also ensures, the comparison values are an
* array or a ref.
*/
notIn: {
compile(comparisonValues: any[]): void;
passes: (value: any, comparisonValues: any[]) => boolean;
};
/**
* Handles the "=" operator. No compile time checks are required here
*/
'=': {
passes: (value: any, comparisonValue: any) => boolean;
};
/**
* Handles the "!=" operator. No compile time checks are required here
*/
'!=': {
passes: (value: any, comparisonValue: any) => boolean;
};
/**
* Handles the ">" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'>': {
compile(comparisonValue: number): void;
passes: (value: number, comparisonValue: number) => boolean;
};
/**
* Handles the "<" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'<': {
compile(comparisonValue: number): void;
passes: (value: number, comparisonValue: number) => boolean;
};
/**
* Handles the ">=" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'>=': {
compile(comparisonValue: number): void;
passes: (value: number, comparisonValue: number) => boolean;
};
/**
* Handles the "<=" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'<=': {
compile(comparisonValue: number): void;
passes: (value: number, comparisonValue: number) => boolean;
};
};
/**
* Ensure the value exists when defined expectation passed.
* `null`, `undefined` and `empty string` fails the validation.
*/
export declare const requiredWhen: SyncValidation<CompileReturnType>;
export {};
@@ -0,0 +1,193 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.requiredWhen = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredWhen';
const DEFAULT_MESSAGE = 'requiredWhen validation failed';
/**
* Available operators
*/
const OPERATORS = {
/**
* Handles the "in" operator. Also ensures, the comparison values are an
* array or a ref.
*/
'in': {
compile(comparisonValues) {
if (!Array.isArray(comparisonValues)) {
throw new Error(`"${RULE_NAME}": "in" operator expects an array of "comparisonValues"`);
}
},
passes: (value, comparisonValues) => {
return comparisonValues.includes(value);
},
},
/**
* Handles the "notIn" operator. Also ensures, the comparison values are an
* array or a ref.
*/
'notIn': {
compile(comparisonValues) {
if (!Array.isArray(comparisonValues)) {
throw new Error(`"${RULE_NAME}": "notIn" operator expects an array of "comparisonValues"`);
}
},
passes: (value, comparisonValues) => {
return !comparisonValues.includes(value);
},
},
/**
* Handles the "=" operator. No compile time checks are required here
*/
'=': {
passes: (value, comparisonValue) => {
return value === comparisonValue;
},
},
/**
* Handles the "!=" operator. No compile time checks are required here
*/
'!=': {
passes: (value, comparisonValue) => {
return value !== comparisonValue;
},
},
/**
* Handles the ">" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'>': {
compile(comparisonValue) {
if (typeof comparisonValue !== 'number') {
throw new Error(`"${RULE_NAME}": ">" operator expects "comparisonValue" to be a number`);
}
},
passes: (value, comparisonValue) => {
return value > comparisonValue;
},
},
/**
* Handles the "<" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'<': {
compile(comparisonValue) {
if (typeof comparisonValue !== 'number') {
throw new Error(`"${RULE_NAME}": "<" operator expects "comparisonValue" to be a number`);
}
},
passes: (value, comparisonValue) => {
return value < comparisonValue;
},
},
/**
* Handles the ">=" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'>=': {
compile(comparisonValue) {
if (typeof comparisonValue !== 'number') {
throw new Error(`"${RULE_NAME}": ">=" operator expects "comparisonValue" to be a number`);
}
},
passes: (value, comparisonValue) => {
return value >= comparisonValue;
},
},
/**
* Handles the "<=" operator. Ensures `comparisonValue` is a number
* or a ref
*/
'<=': {
compile(comparisonValue) {
if (typeof comparisonValue !== 'number') {
throw new Error(`"${RULE_NAME}": "<=" operator expects "comparisonValue" to be a number`);
}
},
passes: (value, comparisonValue) => {
return value <= comparisonValue;
},
},
};
/**
* Ensure the value exists when defined expectation passed.
* `null`, `undefined` and `empty string` fails the validation.
*/
exports.requiredWhen = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([field, operator, comparisonValues]) => {
/**
* Ensure "field", "operator" and "comparisonValues" are defined
*/
if (!field || !operator || comparisonValues === undefined) {
throw new Error(`"${RULE_NAME}": expects a "field", "operator" and "comparisonValue"`);
}
/**
* Ensure "operator" is defined
*/
if (!OPERATORS[operator]) {
throw new Error(`"${RULE_NAME}": expects "operator" to be one of the allowed values`);
}
/**
* Value is a ref
*/
if ((0, helpers_1.isRef)(comparisonValues)) {
return {
allowUndefineds: true,
compiledOptions: {
operator,
field,
ref: comparisonValues.key,
},
};
}
/**
* Compile the options for a given operator when they
* implement a compile function
*/
if (typeof OPERATORS[operator].compile === 'function') {
OPERATORS[operator].compile(comparisonValues);
}
return {
allowUndefineds: true,
compiledOptions: {
operator,
field,
comparisonValues,
},
};
}),
validate(value, compiledOptions, { errorReporter, pointer, arrayExpressionPointer, root, tip, refs }) {
let comparisonValues;
/**
* Resolve comparisonValues
*/
if (compiledOptions.ref) {
comparisonValues = refs[compiledOptions.ref].value;
}
else {
comparisonValues = compiledOptions.comparisonValues;
}
/**
* Finding if field should be required
*/
const shouldBeRequired = OPERATORS[compiledOptions.operator].passes((0, helpers_1.getFieldValue)(compiledOptions.field, root, tip), comparisonValues);
/**
* Validation
*/
if (shouldBeRequired && !(0, helpers_1.exists)(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
operator: compiledOptions.operator,
otherField: compiledOptions.field,
values: comparisonValues,
});
}
},
};
+46
View File
@@ -0,0 +1,46 @@
export { distinct } from './array/distinct';
export { after } from './date/after';
export { afterOrEqual } from './date/afterOrEqual';
export { afterField } from './date/afterField';
export { afterOrEqualToField } from './date/afterOrEqualToField';
export { before } from './date/before';
export { beforeOrEqual } from './date/beforeOrEqual';
export { beforeField } from './date/beforeField';
export { beforeOrEqualToField } from './date/beforeOrEqualToField';
export { confirmed } from './existence/confirmed';
export { required } from './existence/required';
export { nullable } from './existence/nullable';
export { requiredIfExists } from './existence/requiredIfExists';
export { requiredIfExistsAll } from './existence/requiredIfExistsAll';
export { requiredIfExistsAny } from './existence/requiredIfExistsAny';
export { requiredIfNotExists } from './existence/requiredIfNotExists';
export { requiredIfNotExistsAll } from './existence/requiredIfNotExistsAll';
export { requiredIfNotExistsAny } from './existence/requiredIfNotExistsAny';
export { requiredWhen } from './existence/requiredWhen';
export { notIn } from './miscellaneous/notIn';
export { unsigned } from './number/unsigned';
export { range } from './number/range';
export { array } from './primitives/array';
export { boolean } from './primitives/boolean';
export { date } from './primitives/date';
export { oneOf as enum } from './primitives/enum';
export { enumSet } from './primitives/enumSet';
export { file } from './primitives/file';
export { number } from './primitives/number';
export { object } from './primitives/object';
export { string } from './primitives/string';
export { alpha } from './string/alpha';
export { alphaNum } from './string/alphaNum';
export { regex } from './string/regex';
export { escape } from './string/escape';
export { trim } from './string/trim';
export { email } from './string/email';
export { normalizeEmail } from './string/normalizeEmail';
export { url } from './string/url';
export { normalizeUrl } from './string/normalizeUrl';
export { ip } from './string/ip';
export { uuid } from './string/uuid';
export { mobile } from './string/mobile';
export { maxLength } from './string-and-array/maxLength';
export { minLength } from './string-and-array/minLength';
export { equalTo } from './string/equalTo';
+103
View File
@@ -0,0 +1,103 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.equalTo = exports.minLength = exports.maxLength = exports.mobile = exports.uuid = exports.ip = exports.normalizeUrl = exports.url = exports.normalizeEmail = exports.email = exports.trim = exports.escape = exports.regex = exports.alphaNum = exports.alpha = exports.string = exports.object = exports.number = exports.file = exports.enumSet = exports.enum = exports.date = exports.boolean = exports.array = exports.range = exports.unsigned = exports.notIn = exports.requiredWhen = exports.requiredIfNotExistsAny = exports.requiredIfNotExistsAll = exports.requiredIfNotExists = exports.requiredIfExistsAny = exports.requiredIfExistsAll = exports.requiredIfExists = exports.nullable = exports.required = exports.confirmed = exports.beforeOrEqualToField = exports.beforeField = exports.beforeOrEqual = exports.before = exports.afterOrEqualToField = exports.afterField = exports.afterOrEqual = exports.after = exports.distinct = void 0;
var distinct_1 = require("./array/distinct");
Object.defineProperty(exports, "distinct", { enumerable: true, get: function () { return distinct_1.distinct; } });
var after_1 = require("./date/after");
Object.defineProperty(exports, "after", { enumerable: true, get: function () { return after_1.after; } });
var afterOrEqual_1 = require("./date/afterOrEqual");
Object.defineProperty(exports, "afterOrEqual", { enumerable: true, get: function () { return afterOrEqual_1.afterOrEqual; } });
var afterField_1 = require("./date/afterField");
Object.defineProperty(exports, "afterField", { enumerable: true, get: function () { return afterField_1.afterField; } });
var afterOrEqualToField_1 = require("./date/afterOrEqualToField");
Object.defineProperty(exports, "afterOrEqualToField", { enumerable: true, get: function () { return afterOrEqualToField_1.afterOrEqualToField; } });
var before_1 = require("./date/before");
Object.defineProperty(exports, "before", { enumerable: true, get: function () { return before_1.before; } });
var beforeOrEqual_1 = require("./date/beforeOrEqual");
Object.defineProperty(exports, "beforeOrEqual", { enumerable: true, get: function () { return beforeOrEqual_1.beforeOrEqual; } });
var beforeField_1 = require("./date/beforeField");
Object.defineProperty(exports, "beforeField", { enumerable: true, get: function () { return beforeField_1.beforeField; } });
var beforeOrEqualToField_1 = require("./date/beforeOrEqualToField");
Object.defineProperty(exports, "beforeOrEqualToField", { enumerable: true, get: function () { return beforeOrEqualToField_1.beforeOrEqualToField; } });
var confirmed_1 = require("./existence/confirmed");
Object.defineProperty(exports, "confirmed", { enumerable: true, get: function () { return confirmed_1.confirmed; } });
var required_1 = require("./existence/required");
Object.defineProperty(exports, "required", { enumerable: true, get: function () { return required_1.required; } });
var nullable_1 = require("./existence/nullable");
Object.defineProperty(exports, "nullable", { enumerable: true, get: function () { return nullable_1.nullable; } });
var requiredIfExists_1 = require("./existence/requiredIfExists");
Object.defineProperty(exports, "requiredIfExists", { enumerable: true, get: function () { return requiredIfExists_1.requiredIfExists; } });
var requiredIfExistsAll_1 = require("./existence/requiredIfExistsAll");
Object.defineProperty(exports, "requiredIfExistsAll", { enumerable: true, get: function () { return requiredIfExistsAll_1.requiredIfExistsAll; } });
var requiredIfExistsAny_1 = require("./existence/requiredIfExistsAny");
Object.defineProperty(exports, "requiredIfExistsAny", { enumerable: true, get: function () { return requiredIfExistsAny_1.requiredIfExistsAny; } });
var requiredIfNotExists_1 = require("./existence/requiredIfNotExists");
Object.defineProperty(exports, "requiredIfNotExists", { enumerable: true, get: function () { return requiredIfNotExists_1.requiredIfNotExists; } });
var requiredIfNotExistsAll_1 = require("./existence/requiredIfNotExistsAll");
Object.defineProperty(exports, "requiredIfNotExistsAll", { enumerable: true, get: function () { return requiredIfNotExistsAll_1.requiredIfNotExistsAll; } });
var requiredIfNotExistsAny_1 = require("./existence/requiredIfNotExistsAny");
Object.defineProperty(exports, "requiredIfNotExistsAny", { enumerable: true, get: function () { return requiredIfNotExistsAny_1.requiredIfNotExistsAny; } });
var requiredWhen_1 = require("./existence/requiredWhen");
Object.defineProperty(exports, "requiredWhen", { enumerable: true, get: function () { return requiredWhen_1.requiredWhen; } });
var notIn_1 = require("./miscellaneous/notIn");
Object.defineProperty(exports, "notIn", { enumerable: true, get: function () { return notIn_1.notIn; } });
var unsigned_1 = require("./number/unsigned");
Object.defineProperty(exports, "unsigned", { enumerable: true, get: function () { return unsigned_1.unsigned; } });
var range_1 = require("./number/range");
Object.defineProperty(exports, "range", { enumerable: true, get: function () { return range_1.range; } });
var array_1 = require("./primitives/array");
Object.defineProperty(exports, "array", { enumerable: true, get: function () { return array_1.array; } });
var boolean_1 = require("./primitives/boolean");
Object.defineProperty(exports, "boolean", { enumerable: true, get: function () { return boolean_1.boolean; } });
var date_1 = require("./primitives/date");
Object.defineProperty(exports, "date", { enumerable: true, get: function () { return date_1.date; } });
var enum_1 = require("./primitives/enum");
Object.defineProperty(exports, "enum", { enumerable: true, get: function () { return enum_1.oneOf; } });
var enumSet_1 = require("./primitives/enumSet");
Object.defineProperty(exports, "enumSet", { enumerable: true, get: function () { return enumSet_1.enumSet; } });
var file_1 = require("./primitives/file");
Object.defineProperty(exports, "file", { enumerable: true, get: function () { return file_1.file; } });
var number_1 = require("./primitives/number");
Object.defineProperty(exports, "number", { enumerable: true, get: function () { return number_1.number; } });
var object_1 = require("./primitives/object");
Object.defineProperty(exports, "object", { enumerable: true, get: function () { return object_1.object; } });
var string_1 = require("./primitives/string");
Object.defineProperty(exports, "string", { enumerable: true, get: function () { return string_1.string; } });
var alpha_1 = require("./string/alpha");
Object.defineProperty(exports, "alpha", { enumerable: true, get: function () { return alpha_1.alpha; } });
var alphaNum_1 = require("./string/alphaNum");
Object.defineProperty(exports, "alphaNum", { enumerable: true, get: function () { return alphaNum_1.alphaNum; } });
var regex_1 = require("./string/regex");
Object.defineProperty(exports, "regex", { enumerable: true, get: function () { return regex_1.regex; } });
var escape_1 = require("./string/escape");
Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_1.escape; } });
var trim_1 = require("./string/trim");
Object.defineProperty(exports, "trim", { enumerable: true, get: function () { return trim_1.trim; } });
var email_1 = require("./string/email");
Object.defineProperty(exports, "email", { enumerable: true, get: function () { return email_1.email; } });
var normalizeEmail_1 = require("./string/normalizeEmail");
Object.defineProperty(exports, "normalizeEmail", { enumerable: true, get: function () { return normalizeEmail_1.normalizeEmail; } });
var url_1 = require("./string/url");
Object.defineProperty(exports, "url", { enumerable: true, get: function () { return url_1.url; } });
var normalizeUrl_1 = require("./string/normalizeUrl");
Object.defineProperty(exports, "normalizeUrl", { enumerable: true, get: function () { return normalizeUrl_1.normalizeUrl; } });
var ip_1 = require("./string/ip");
Object.defineProperty(exports, "ip", { enumerable: true, get: function () { return ip_1.ip; } });
var uuid_1 = require("./string/uuid");
Object.defineProperty(exports, "uuid", { enumerable: true, get: function () { return uuid_1.uuid; } });
var mobile_1 = require("./string/mobile");
Object.defineProperty(exports, "mobile", { enumerable: true, get: function () { return mobile_1.mobile; } });
var maxLength_1 = require("./string-and-array/maxLength");
Object.defineProperty(exports, "maxLength", { enumerable: true, get: function () { return maxLength_1.maxLength; } });
var minLength_1 = require("./string-and-array/minLength");
Object.defineProperty(exports, "minLength", { enumerable: true, get: function () { return minLength_1.minLength; } });
var equalTo_1 = require("./string/equalTo");
Object.defineProperty(exports, "equalTo", { enumerable: true, get: function () { return equalTo_1.equalTo; } });
@@ -0,0 +1,14 @@
import { SyncValidation, NodeSubType } from '@ioc:Adonis/Core/Validator';
/**
* Return type of the compile function
*/
type CompileReturnType = {
values?: (string | number)[];
ref?: string;
subtype: NodeSubType;
};
/**
* Ensure the value is one of the defined choices
*/
export declare const notIn: SyncValidation<CompileReturnType>;
export {};
@@ -0,0 +1,89 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.notIn = void 0;
const luxon_1 = require("luxon");
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'notIn';
const DEFAULT_MESSAGE = 'notIn validation failed';
const VERIFIERS = {
string(value, values) {
if (typeof value !== 'string') {
return true;
}
return !values.includes(value);
},
number(value, values) {
if (typeof value !== 'number') {
return true;
}
return !values.includes(value);
},
array(value, values) {
if (!Array.isArray(value)) {
return true;
}
return !value.find((one) => values.includes(one));
},
date(value, values) {
if (luxon_1.DateTime.isDateTime(value) === false) {
return true;
}
const isoDate = value.toISODate();
if (!isoDate) {
return true;
}
return !values.includes(isoDate);
},
};
/**
* Ensure the value is one of the defined choices
*/
exports.notIn = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['string', 'number', 'array', 'date'], ([values], _, subtype) => {
/**
* Choices are defined as a ref
*/
if ((0, helpers_1.isRef)(values)) {
return {
compiledOptions: { ref: values.key, subtype },
};
}
/**
* Ensure value is an array or a ref
*/
if (!values || !Array.isArray(values)) {
throw new Error(`"${RULE_NAME}": expects an array of "notIn values" or a "ref"`);
}
return { compiledOptions: { values, subtype } };
}),
validate(value, compiledOptions, { errorReporter, pointer, arrayExpressionPointer, refs }) {
let values = [];
/**
* Resolve values from the ref or use as it is, if defined as an array
*/
if (compiledOptions.ref) {
const runtimevalues = refs[compiledOptions.ref].value;
(0, helpers_1.enforceArray)(runtimevalues, `"${RULE_NAME}": expects "refs.${compiledOptions.ref}" to be an array`);
values = runtimevalues;
}
else if (compiledOptions.values) {
values = compiledOptions.values;
}
/**
* Validation
*/
if (!VERIFIERS[compiledOptions.subtype](value, values)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
values,
});
}
},
};
@@ -0,0 +1,5 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
export declare const range: SyncValidation<{
start: number;
stop: number;
}>;
+41
View File
@@ -0,0 +1,41 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.range = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'range';
const DEFAULT_MESSAGE = 'range validation failed';
exports.range = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['number'], ([start, stop]) => {
if (typeof start !== 'number') {
throw new Error(`The start value for "${RULE_NAME}" must be defined as number`);
}
if (typeof stop !== 'number') {
throw new Error(`The stop value for "${RULE_NAME}" must be defined as number`);
}
if (start > stop) {
throw new Error(`The start value for "${RULE_NAME}" must be lower than the stop value`);
}
return {
compiledOptions: {
start,
stop,
},
};
}),
validate(value, compiledOptions, { errorReporter, pointer, arrayExpressionPointer }) {
if (typeof value !== 'number') {
return;
}
if (value < compiledOptions.start || value > compiledOptions.stop) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, compiledOptions);
}
},
};
@@ -0,0 +1,2 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
export declare const unsigned: SyncValidation;
@@ -0,0 +1,25 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsigned = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'unsigned';
const DEFAULT_MESSAGE = 'unsigned validation failed';
exports.unsigned = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['number']),
validate(value, _, { errorReporter, arrayExpressionPointer, pointer }) {
if (typeof value !== 'number') {
return;
}
if (value < 0) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
}
},
};
@@ -0,0 +1,5 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure value is a valid array
*/
export declare const array: SyncValidation;
@@ -0,0 +1,25 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.array = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'array';
const DEFAULT_MESSAGE = 'array validation failed';
/**
* Ensure value is a valid array
*/
exports.array = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME),
validate(value, _, { pointer, arrayExpressionPointer, errorReporter }) {
if (!Array.isArray(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
}
},
};
@@ -0,0 +1,9 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure value is a valid boolean or a valid boolean representation
* as a number or a string.
*
* - 0,'0' are casted to false
* - 1,'1' are casted to true
*/
export declare const boolean: SyncValidation;
@@ -0,0 +1,49 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolean = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'boolean';
const BOOLEAN_POSITIVES = ['1', 1, 'on', 'true'];
const BOOLEAN_NEGATIVES = ['0', 0, 'off', 'false'];
const DEFAULT_MESSAGE = 'boolean validation failed';
/**
* Ensure value is a valid boolean or a valid boolean representation
* as a number or a string.
*
* - 0,'0' are casted to false
* - 1,'1' are casted to true
*/
exports.boolean = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME),
validate(value, _, { mutate, pointer, errorReporter, arrayExpressionPointer }) {
/**
* A valid boolean is passed at first place
*/
if (typeof value === 'boolean') {
return;
}
/**
* Value is a boolean representation in form of numeric or a string.
*/
if (BOOLEAN_POSITIVES.includes(value)) {
mutate(true);
return;
}
if (BOOLEAN_NEGATIVES.includes(value)) {
mutate(false);
return;
}
/**
* Report error
*/
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
},
};
@@ -0,0 +1,7 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value is a valid date instance
*/
export declare const date: SyncValidation<{
format?: string;
}>;
@@ -0,0 +1,57 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.date = void 0;
const helpers_1 = require("../../Validator/helpers");
const toLuxon_1 = require("../date/helpers/toLuxon");
const RULE_NAME = 'date';
const DEFAULT_MESSAGE = 'date validation failed';
const CANNOT_VALIDATE = 'cannot validate date instance against a date format';
/**
* Ensure the value is a valid date instance
*/
exports.date = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([options]) => {
return {
compiledOptions: { format: options && options.format },
};
}),
validate(value, compiledOptions, { mutate, errorReporter, pointer, arrayExpressionPointer }) {
const isDateInstance = value instanceof Date;
const dateTime = (0, toLuxon_1.toLuxon)(value, compiledOptions.format);
if (isDateInstance && compiledOptions.format) {
errorReporter.report(pointer, RULE_NAME, CANNOT_VALIDATE, arrayExpressionPointer, {
format: compiledOptions.format,
});
return;
}
/**
* If `dateTime` is still undefined, it means it is not an instance of
* date or a string and we must report the error and return early.
*/
if (!dateTime) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
format: compiledOptions.format,
});
return;
}
/**
* Report error for invalid dates
*/
if (!dateTime.isValid) {
errorReporter.report(pointer, `${RULE_NAME}.format`, dateTime.invalidExplanation, arrayExpressionPointer, { format: compiledOptions.format });
return;
}
/**
* Mutate original value to datetime
*/
mutate(dateTime);
},
};
@@ -0,0 +1,13 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Return type of the compile function
*/
type CompileReturnType = {
choices?: any[];
ref?: string;
};
/**
* Ensure the value is one of the defined choices
*/
export declare const oneOf: SyncValidation<CompileReturnType>;
export {};
@@ -0,0 +1,56 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.oneOf = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'enum';
const DEFAULT_MESSAGE = 'enum validation failed';
/**
* Ensure the value is one of the defined choices
*/
exports.oneOf = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([choices]) => {
/**
* Choices are defined as a ref
*/
if ((0, helpers_1.isRef)(choices)) {
return {
compiledOptions: { ref: choices.key },
};
}
/**
* Ensure value is an array or a ref
*/
if (!choices || !Array.isArray(choices)) {
throw new Error(`"${RULE_NAME}": expects an array of choices or a "ref"`);
}
return { compiledOptions: { choices: choices } };
}),
validate(value, compiledOptions, { errorReporter, pointer, arrayExpressionPointer, refs }) {
let choices = [];
/**
* Resolve choices from the ref or use as it is, if defined as an array
*/
if (compiledOptions.ref) {
const runtimeChoices = refs[compiledOptions.ref].value;
(0, helpers_1.enforceArray)(runtimeChoices, `"${RULE_NAME}": expects "refs.${compiledOptions.ref}" to be an array`);
choices = runtimeChoices;
}
else if (compiledOptions.choices) {
choices = compiledOptions.choices;
}
/**
* Validation
*/
if (!choices.includes(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, { choices });
}
},
};
@@ -0,0 +1,13 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Return type of the compile function
*/
type CompileReturnType = {
choices?: any[];
ref?: string;
};
/**
* Ensure the input array is a subset of defined choices
*/
export declare const enumSet: SyncValidation<CompileReturnType>;
export {};
@@ -0,0 +1,63 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.enumSet = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'enumSet';
const DEFAULT_MESSAGE = 'enumSet validation failed';
/**
* Ensure the input array is a subset of defined choices
*/
exports.enumSet = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([choices]) => {
/**
* Choices are defined as a ref
*/
if ((0, helpers_1.isRef)(choices)) {
return {
compiledOptions: { ref: choices.key },
};
}
/**
* Ensure value is an array or a ref
*/
if (!choices || !Array.isArray(choices)) {
throw new Error(`"${RULE_NAME}": expects an array of choices or a "ref"`);
}
return { compiledOptions: { choices: choices } };
}),
validate(value, compiledOptions, { errorReporter, pointer, refs, arrayExpressionPointer }) {
/**
* Ensure user defined value is an array
*/
if (!Array.isArray(value)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, compiledOptions);
return;
}
let choices = [];
/**
* Resolve choices from the ref or use as it is, if defined as an array
*/
if (compiledOptions.ref) {
const runtimeChoices = refs[compiledOptions.ref].value;
(0, helpers_1.enforceArray)(runtimeChoices, `"${RULE_NAME}": expects "refs.${compiledOptions.ref}" to be an array`);
choices = runtimeChoices;
}
else if (compiledOptions.choices) {
choices = compiledOptions.choices;
}
/**
* Ensure user defined values fall within the choices array
*/
if (!value.every((one) => choices.includes(one))) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, { choices });
}
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
import { FileValidationOptions } from '@ioc:Adonis/Core/BodyParser';
/**
* Ensure the value is a valid file instance
*/
export declare const file: SyncValidation<Partial<FileValidationOptions>>;
@@ -0,0 +1,62 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.file = void 0;
const helpers_1 = require("../../Validator/helpers");
const DEFAULT_MESSAGE = 'file validation failed';
const RULE_NAME = 'file';
/**
* Ensure the value is a valid file instance
*/
exports.file = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([options]) => {
const validationOptions = {};
if (options && options.size) {
validationOptions.size = options.size;
}
if (options && options.extnames) {
validationOptions.extnames = options.extnames;
}
return {
compiledOptions: validationOptions,
};
}),
validate(fileToValidate, compiledOptions, { errorReporter, pointer, arrayExpressionPointer }) {
/**
* Raise error when not a multipart file instance
*/
if (!fileToValidate.isMultipartFile) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, compiledOptions);
return;
}
/**
* Set size when it's defined in the options
*/
if (fileToValidate.sizeLimit === undefined && compiledOptions.size) {
fileToValidate.sizeLimit = compiledOptions.size;
}
/**
* Set extensions when it's defined in the options
*/
if (fileToValidate.allowedExtensions === undefined && compiledOptions.extnames) {
fileToValidate.allowedExtensions = compiledOptions.extnames;
}
/**
* Validate the file
*/
fileToValidate.validate();
/**
* Report errors
*/
fileToValidate.errors.forEach((error) => {
errorReporter.report(pointer, `${RULE_NAME}.${error.type}`, error.message, arrayExpressionPointer, compiledOptions);
});
},
};
@@ -0,0 +1,6 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the value is a valid number. Numeric string will be casted
* to valid numbers
*/
export declare const number: SyncValidation;
@@ -0,0 +1,50 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.number = void 0;
const helpers_1 = require("../../Validator/helpers");
const DEFAULT_MESSAGE = 'number validation failed';
const RULE_NAME = 'number';
/**
* Ensure the value is a valid number. Numeric string will be casted
* to valid numbers
*/
exports.number = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME),
validate(value, _, { mutate, errorReporter, pointer, arrayExpressionPointer }) {
if (typeof value === 'number') {
return;
}
/**
* Report error when value is not a number and neither a string
*/
if (typeof value !== 'string') {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
return;
}
/**
* Attempt to cast number like string to a number. In case of
* failure report the validation error
*/
const castedValue = Number(value);
if (isNaN(castedValue)) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
return;
}
if (castedValue === Infinity || castedValue === -Infinity) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
return;
}
/**
* Mutate the value
*/
mutate(castedValue);
},
};
@@ -0,0 +1,5 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure value is a valid object
*/
export declare const object: SyncValidation;
@@ -0,0 +1,25 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.object = void 0;
const helpers_1 = require("../../Validator/helpers");
const DEFAULT_MESSAGE = 'object validation failed';
const RULE_NAME = 'object';
/**
* Ensure value is a valid object
*/
exports.object = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME),
validate(value, _, { errorReporter, pointer, arrayExpressionPointer }) {
if (typeof value !== 'object' || Array.isArray(value) || value === null) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
}
},
};
@@ -0,0 +1,9 @@
import { SyncValidation } from '@ioc:Adonis/Core/Validator';
/**
* Ensure value is a valid string
* @type {SyncValidation}
*/
export declare const string: SyncValidation<{
escape: boolean;
trim: boolean;
}>;
@@ -0,0 +1,54 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.string = void 0;
const escape_1 = __importDefault(require("validator/lib/escape"));
const helpers_1 = require("../../Validator/helpers");
const DEFAULT_MESSAGE = 'string validation failed';
const RULE_NAME = 'string';
/**
* Ensure value is a valid string
* @type {SyncValidation}
*/
exports.string = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([options]) => {
return {
compiledOptions: {
escape: !!(options && options.escape),
trim: !!(options && options.trim),
},
};
}),
validate(value, compiledOptions, { pointer, errorReporter, arrayExpressionPointer, mutate }) {
if (typeof value !== 'string') {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer);
return;
}
let mutated = false;
/**
* Escape string
*/
if (compiledOptions.escape) {
mutated = true;
value = (0, escape_1.default)(value);
}
/**
* Trim whitespaces
*/
if (compiledOptions.trim) {
mutated = true;
value = value.trim();
}
mutated && mutate(value);
},
};
@@ -0,0 +1,9 @@
import { SyncValidation, NodeSubType } from '@ioc:Adonis/Core/Validator';
/**
* Ensure the length of an array of a string is under the
* defined length
*/
export declare const maxLength: SyncValidation<{
maxLength: number;
subtype: NodeSubType;
}>;
@@ -0,0 +1,44 @@
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.maxLength = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'maxLength';
const DEFAULT_MESSAGE = 'maxLength validation failed';
/**
* Ensure the length of an array of a string is under the
* defined length
*/
exports.maxLength = {
compile: (0, helpers_1.wrapCompile)(RULE_NAME, ['string', 'array'], ([limit], _, subtype) => {
if (typeof limit !== 'number') {
throw new Error(`The limit value for "${RULE_NAME}" must be defined as a number`);
}
return {
compiledOptions: {
maxLength: limit,
subtype: subtype,
},
};
}),
validate(value, compiledOptions, { errorReporter, pointer, arrayExpressionPointer }) {
if (compiledOptions.subtype === 'array' && !Array.isArray(value)) {
return;
}
else if (compiledOptions.subtype === 'string' && typeof value !== 'string') {
return;
}
if (value.length > compiledOptions.maxLength) {
errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
maxLength: compiledOptions.maxLength,
});
}
},
};

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