feat: Reinitialize frontend with SvelteKit and TypeScript

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

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

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

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

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

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,225 @@
import Macroable from '@poppinss/macroable';
import type { LiteralNode, RefsStore } from '@vinejs/compiler/types';
import { OTYPE, COTYPE, PARSE, ITYPE, SUBTYPE } from '../../symbols.js';
import type { Parser, Validation, RuleBuilder, Transformer, FieldContext, FieldOptions, ParserOptions, ConstructableSchema, ComparisonOperators, ArrayComparisonOperators, NumericComparisonOperators } from '../../types.js';
/**
* Base schema type with only modifiers applicable on all the schema types.
*/
declare abstract class BaseModifiersType<Input, Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Input, Output, CamelCaseOutput> {
/**
* Each subtype should implement the compile method that returns
* one of the known compiler nodes
*/
abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
/**
* The child class must implement the clone method
*/
abstract clone(): this;
/**
* Define the input type of the schema
*/
[ITYPE]: Input;
/**
* The output value of the field. The property points to a type only
* and not the real value.
*/
[OTYPE]: Output;
[COTYPE]: CamelCaseOutput;
/**
* Mark the field under validation as optional. An optional
* field allows both null and undefined values.
*/
optional(validations?: Validation<any>[]): OptionalModifier<this>;
/**
* Mark the field under validation to be null. The null value will
* be written to the output as well.
*
* If `optional` and `nullable` are used together, then both undefined
* and null values will be allowed.
*/
nullable(): NullableModifier<this>;
/**
* Apply transform on the final validated value. The transform method may
* convert the value to any new datatype.
*/
transform<TransformedOutput>(transformer: Transformer<this, TransformedOutput>): TransformModifier<this, TransformedOutput>;
}
/**
* Modifies the schema type to allow null values
*/
export declare class NullableModifier<Schema extends BaseModifiersType<any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE] | null, Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null> {
#private;
constructor(parent: Schema);
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the nullable modifier
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
/**
* Modifies the schema type to allow undefined values
*/
export declare class OptionalModifier<Schema extends BaseModifiersType<any, any, any>> extends BaseModifiersType<Schema[typeof ITYPE] | undefined | null, Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined> {
#private;
/**
* Optional modifier validations list
*/
validations: Validation<any>[];
constructor(parent: Schema, validations?: Validation<any>[]);
/**
* Shallow clones the validations. Since, there are no API's to mutate
* the validation options, we can safely copy them by reference.
*/
protected cloneValidations(): Validation<any>[];
/**
* Compiles validations
*/
protected compileValidations(refs: RefsStore): {
ruleFnId: `ref://${number}`;
implicit: boolean;
isAsync: boolean;
}[];
/**
* Push a validation to the validations chain.
*/
use(validation: Validation<any> | RuleBuilder): this;
/**
* Define a callback to conditionally require a field at
* runtime.
*
* The callback method should return "true" to mark the
* field as required, or "false" to skip the required
* validation
*/
requiredWhen<Operator extends ComparisonOperators>(otherField: string, operator: Operator, expectedValue: Operator extends ArrayComparisonOperators ? (string | number | boolean)[] : Operator extends NumericComparisonOperators ? number : string | number | boolean): this;
requiredWhen(callback: (field: FieldContext) => boolean): this;
/**
* Mark the field under validation as required when all
* the other fields are present with value other
* than `undefined` or `null`.
*/
requiredIfExists(fields: string | string[]): this;
/**
* Mark the field under validation as required when any
* one of the other fields are present with non-nullable
* value.
*/
requiredIfAnyExists(fields: string[]): this;
/**
* Mark the field under validation as required when all
* the other fields are missing or their value is
* `undefined` or `null`.
*/
requiredIfMissing(fields: string | string[]): this;
/**
* Mark the field under validation as required when any
* one of the other fields are missing.
*/
requiredIfAnyMissing(fields: string[]): this;
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the optional modifier
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
/**
* Modifies the schema type to allow custom transformed values
*/
export declare class TransformModifier<Schema extends BaseModifiersType<any, any, any>, Output> extends BaseModifiersType<Schema[typeof ITYPE], Output, Output> {
#private;
/**
* The output value of the field. The property points to a type only
* and not the real value.
*/
[OTYPE]: Output;
[COTYPE]: Output;
constructor(transform: Transformer<Schema, Output>, parent: Schema);
/**
* Creates a fresh instance of the underlying schema type
* and wraps it inside the transform modifier.
*/
clone(): this;
/**
* Compiles to compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
/**
* The base type for creating a custom literal type. Literal type
* is a schema type that has no children elements.
*/
export declare abstract class BaseLiteralType<Input, Output, CamelCaseOutput> extends BaseModifiersType<Input, Output, CamelCaseOutput> {
/**
* Specify the subtype of the literal schema field
*/
abstract [SUBTYPE]: string;
/**
* The child class must implement the clone method
*/
abstract clone(): this;
/**
* Field options
*/
protected options: FieldOptions;
/**
* Set of validations to run
*/
protected validations: Validation<any>[];
constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]);
/**
* Shallow clones the validations. Since, there are no API's to mutate
* the validation options, we can safely copy them by reference.
*/
protected cloneValidations(): Validation<any>[];
/**
* Shallow clones the options
*/
protected cloneOptions(): FieldOptions;
/**
* Compiles validations
*/
protected compileValidations(refs: RefsStore): {
ruleFnId: `ref://${number}`;
implicit: boolean;
isAsync: boolean;
}[];
/**
* Define a method to parse the input value. The method
* is invoked before any validation and hence you must
* perform type-checking to know the value you are
* working it.
*/
parse(callback: Parser): this;
/**
* Push a validation to the validations chain.
*/
use(validation: Validation<any> | RuleBuilder): this;
/**
* Enable/disable the bail mode. In bail mode, the field validations
* are stopped after the first error.
*/
bail(state: boolean): this;
/**
* Compiles the schema type to a compiler node
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode & {
subtype: string;
};
}
export {};

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,96 @@
import Macroable from '@poppinss/macroable';
import { VineAny } from './any/main.js';
import { VineEnum } from './enum/main.js';
import { VineDate } from './date/main.js';
import { union } from './union/builder.js';
import { VineTuple } from './tuple/main.js';
import { VineArray } from './array/main.js';
import { VineObject } from './object/main.js';
import { VineRecord } from './record/main.js';
import { VineString } from './string/main.js';
import { VineNumber } from './number/main.js';
import { VineBoolean } from './boolean/main.js';
import { VineLiteral } from './literal/main.js';
import { CamelCase } from './camelcase_types.js';
import { VineAccepted } from './accepted/main.js';
import { group } from './object/group_builder.js';
import { VineNativeEnum } from './enum/native_enum.js';
import { VineUnionOfTypes } from './union_of_types/main.js';
import { ITYPE, OTYPE, COTYPE } from '../symbols.js';
import type { UndefinedOptional, DateFieldOptions, EnumLike, FieldContext, SchemaTypes } from '../types.js';
/**
* Schema builder exposes methods to construct a Vine schema. You may
* add custom methods to it using macros.
*/
export declare class SchemaBuilder extends Macroable {
/**
* Define a sub-object as a union
*/
group: typeof group;
/**
* Define a union value
*/
union: typeof union;
/**
* Define a string value
*/
string(): VineString;
/**
* Define a boolean value
*/
boolean(options?: {
strict: boolean;
}): VineBoolean;
/**
* Validate a checkbox to be checked
*/
accepted(): VineAccepted;
/**
* Define a number value
*/
number(options?: {
strict: boolean;
}): VineNumber;
/**
* Define a datetime value
*/
date(options?: DateFieldOptions): VineDate;
/**
* Define a schema type in which the input value
* matches the pre-defined value
*/
literal<const Value>(value: Value): VineLiteral<Value>;
/**
* Define an object with known properties. You may call "allowUnknownProperties"
* to merge unknown properties.
*/
object<Properties extends Record<string, SchemaTypes>>(properties: Properties): VineObject<Properties, UndefinedOptional<{ [K in keyof Properties]: Properties[K][typeof ITYPE]; }>, UndefinedOptional<{ [K_1 in keyof Properties]: Properties[K_1][typeof OTYPE]; }>, UndefinedOptional<{ [K_2 in keyof Properties as CamelCase<K_2 & string>]: Properties[K_2][typeof COTYPE]; }>>;
/**
* Define an array field and validate its children elements.
*/
array<Schema extends SchemaTypes>(schema: Schema): VineArray<Schema>;
/**
* Define an array field with known length and each children
* element may have its own schema.
*/
tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]): VineTuple<Schema, { [K in keyof Schema]: Schema[K][typeof ITYPE]; }, { [K_1 in keyof Schema]: Schema[K_1][typeof OTYPE]; }, { [K_2 in keyof Schema]: Schema[K_2][typeof COTYPE]; }>;
/**
* Define an object field with key-value pair. The keys in
* a record are unknown and values can be of a specific
* schema type.
*/
record<Schema extends SchemaTypes>(schema: Schema): VineRecord<Schema>;
/**
* Define a field whose value matches the enum choices.
*/
enum<const Values extends readonly unknown[]>(values: Values | ((field: FieldContext) => Values)): VineEnum<Values>;
enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>;
/**
* Allow the field value to be anything
*/
any(): VineAny;
/**
* Define a union of unique schema types.
*/
unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]): VineUnionOfTypes<Schema>;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,29 @@
import { ObjectGroupNode, RefsStore } from '@vinejs/compiler/types';
import { GroupConditional } from './conditional.js';
import { ITYPE, OTYPE, COTYPE, PARSE } from '../../symbols.js';
import type { ParserOptions, UnionNoMatchCallback } from '../../types.js';
/**
* Object group represents a group with multiple conditionals, where each
* condition returns a set of object properties to merge into the
* existing object.
*/
export declare class ObjectGroup<Conditional extends GroupConditional<any, any, any, any>> {
#private;
[ITYPE]: Conditional[typeof ITYPE];
[OTYPE]: Conditional[typeof OTYPE];
[COTYPE]: Conditional[typeof COTYPE];
constructor(conditionals: Conditional[]);
/**
* Clones the ObjectGroup schema type.
*/
clone(): this;
/**
* Define a fallback method to invoke when all of the group conditions
* fail. You may use this method to report an error.
*/
otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this;
/**
* Compiles the group
*/
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,42 @@
import { RefsStore, TupleNode } from '@vinejs/compiler/types';
import { BaseType } from '../base/main.js';
import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js';
import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js';
/**
* VineTuple is an array with known length and may have different
* schema type for each array element.
*/
export declare class VineTuple<Schema extends SchemaTypes[], Input extends any[], Output extends any[], CamelCaseOutput extends any[]> extends BaseType<Input, Output, CamelCaseOutput> {
#private;
/**
* The property must be implemented for "unionOfTypes"
*/
[UNIQUE_NAME]: string;
/**
* Checks if the value is of array type. The method must be
* implemented for "unionOfTypes"
*/
[IS_OF_TYPE]: (value: unknown) => value is any[];
constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]);
/**
* Copy unknown properties to the final output.
*/
allowUnknownProperties<Value>(): VineTuple<Schema, [
...Input,
...Value[]
], [
...Output,
...Value[]
], [
...CamelCaseOutput,
...Value[]
]>;
/**
* Clone object
*/
clone(): this;
/**
* Compiles to array data type
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode;
}

View File

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

View File

@@ -0,0 +1,18 @@
import { ConditionalFn, RefsStore, UnionNode } from '@vinejs/compiler/types';
import { ITYPE, OTYPE, COTYPE, PARSE } from '../../symbols.js';
import type { ParserOptions, SchemaTypes } from '../../types.js';
/**
* Represents a union conditional type. A conditional is a predicate
* with a schema
*/
export declare class UnionConditional<Schema extends SchemaTypes> {
#private;
[ITYPE]: Schema[typeof ITYPE];
[OTYPE]: Schema[typeof OTYPE];
[COTYPE]: Schema[typeof COTYPE];
constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema);
/**
* Compiles to a union conditional
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode['conditions'][number];
}

View File

@@ -0,0 +1,28 @@
import { RefsStore, UnionNode } from '@vinejs/compiler/types';
import { UnionConditional } from './conditional.js';
import { ITYPE, OTYPE, COTYPE, PARSE } from '../../symbols.js';
import type { SchemaTypes, ParserOptions, ConstructableSchema, UnionNoMatchCallback } from '../../types.js';
/**
* Vine union represents a union data type. A union is a collection
* of conditionals and each condition has an associated schema
*/
export declare class VineUnion<Conditional extends UnionConditional<SchemaTypes>> implements ConstructableSchema<Conditional[typeof ITYPE], Conditional[typeof OTYPE], Conditional[typeof COTYPE]> {
#private;
[ITYPE]: Conditional[typeof ITYPE];
[OTYPE]: Conditional[typeof OTYPE];
[COTYPE]: Conditional[typeof COTYPE];
constructor(conditionals: Conditional[]);
/**
* Define a fallback method to invoke when all of the union conditions
* fail. You may use this method to report an error.
*/
otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this;
/**
* Clones the VineUnion schema type.
*/
clone(): this;
/**
* Compiles to a union
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode;
}

View File

@@ -0,0 +1,27 @@
import type { RefsStore, UnionNode } from '@vinejs/compiler/types';
import { ITYPE, OTYPE, COTYPE, PARSE } from '../../symbols.js';
import type { SchemaTypes, ParserOptions, ConstructableSchema, UnionNoMatchCallback } from '../../types.js';
/**
* Vine union represents a union data type. A union is a collection
* of conditionals and each condition has an associated schema
*/
export declare class VineUnionOfTypes<Schema extends SchemaTypes> implements ConstructableSchema<Schema[typeof ITYPE], Schema[typeof OTYPE], Schema[typeof COTYPE]> {
#private;
[ITYPE]: Schema[typeof ITYPE];
[OTYPE]: Schema[typeof OTYPE];
[COTYPE]: Schema[typeof COTYPE];
constructor(schemas: Schema[]);
/**
* Define a fallback method to invoke when all of the union conditions
* fail. You may use this method to report an error.
*/
otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this;
/**
* Clones the VineUnionOfTypes schema type.
*/
clone(): this;
/**
* Compiles to a union
*/
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode;
}

View File

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

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

@@ -0,0 +1,245 @@
import type dayjs from 'dayjs';
import type { Options as UrlOptions } from 'normalize-url';
import type { IsURLOptions } from 'validator/lib/isURL.js';
import type { IsEmailOptions } from 'validator/lib/isEmail.js';
import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js';
import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js';
import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js';
import type { ParseFn, RefsStore, TupleNode, ArrayNode, UnionNode, RecordNode, ObjectNode, TransformFn, LiteralNode, FieldContext, MessagesProviderContact, ErrorReporterContract as BaseReporter } from '@vinejs/compiler/types';
import type { helpers } from './vine/helpers.js';
import type { ValidationError } from './errors/validation_error.js';
import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE, ITYPE } from './symbols.js';
/**
* Compiler nodes emitted by Vine
*/
export type CompilerNodes = (LiteralNode & {
subtype: string;
}) | ObjectNode | ArrayNode | UnionNode | RecordNode | TupleNode;
/**
* Options accepted by the mobile number validation
*/
export type MobileOptions = {
locale?: MobilePhoneLocale[];
} & IsMobilePhoneOptions;
/**
* Options accepted by the email address validation
*/
export type EmailOptions = IsEmailOptions;
/**
* Options accepted by the normalize email
*/
export { NormalizeEmailOptions };
/**
* Options accepted by the URL validation
*/
export type URLOptions = IsURLOptions;
/**
* Options accepted by the credit card validation
*/
export type CreditCardOptions = {
provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[];
};
/**
* Options accepted by the passport validation
*/
export type PassportOptions = {
countryCode: (typeof helpers)['passportCountryCodes'][number][];
};
/**
* Options accepted by the postal code validation
*/
export type PostalCodeOptions = {
countryCode: PostalCodeLocale[];
};
/**
* Options accepted by the alpha rule
*/
export type AlphaOptions = {
allowSpaces?: boolean;
allowUnderscores?: boolean;
allowDashes?: boolean;
};
export type NormalizeUrlOptions = UrlOptions;
/**
* Options accepted by the alpha numeric rule
*/
export type AlphaNumericOptions = AlphaOptions;
/**
* Re-exporting selected types from compiler
*/
export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types';
/**
* Representation of a native enum like type
*/
export type EnumLike = {
[K: string]: string | number;
[number: number]: string;
};
/**
* Representation of fields and messages accepted by the messages
* provider
*/
export type ValidationMessages = Record<string, string>;
export type ValidationFields = Record<string, string>;
/**
* Constructable schema type refers to any type that can be
* constructed for type inference and compiler output
*/
export interface ConstructableSchema<Inputs, Output, CamelCaseOutput> {
[ITYPE]: Inputs;
[OTYPE]: Output;
[COTYPE]: CamelCaseOutput;
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes;
clone(): this;
/**
* Implement if you want schema type to be used with the unionOfTypes
*/
[UNIQUE_NAME]?: string;
[IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean;
}
export type SchemaTypes = ConstructableSchema<any, any, any>;
/**
* Representation of a function that performs validation.
* The function receives the following arguments.
*
* - the current value of the input field
* - runtime options
* - field context
*/
export type Validator<Options extends any> = (value: unknown, options: Options, field: FieldContext) => any | Promise<any>;
/**
* A validation rule is a combination of a validator and
* some metadata required at the time of compiling the
* rule.
*
* Think of this type as "Validator" + "metaData"
*/
export type ValidationRule<Options extends any> = {
validator: Validator<Options>;
isAsync: boolean;
implicit: boolean;
};
/**
* Validation is a combination of a validation rule and the options
* to supply to validator at the time of validating the field.
*
* Think of this type as "ValidationRule" + "options"
*/
export type Validation<Options extends any> = {
/**
* Options to pass to the validator function.
*/
options?: Options;
/**
* The rule to use
*/
rule: ValidationRule<Options>;
};
/**
* A rule builder is an object that implements the "VALIDATION"
* method and returns [[Validation]] type
*/
export interface RuleBuilder {
[VALIDATION](): Validation<any>;
}
/**
* The transform function to mutate the output value
*/
export type Transformer<Schema extends SchemaTypes, Output> = TransformFn<Exclude<Schema[typeof OTYPE], undefined>, Output>;
/**
* The parser function to mutate the input value
*/
export type Parser = ParseFn;
/**
* A set of options accepted by the field
*/
export type FieldOptions = {
allowNull: boolean;
bail: boolean;
isOptional: boolean;
parse?: Parser;
};
/**
* A set of options accepted by the date field
*/
export type DateFieldOptions = {
formats?: dayjs.OptionType;
};
/**
* A set of options accepted by the equals rule
* on the date field
*/
export type DateEqualsOptions = {
compare?: dayjs.OpUnitType;
format?: dayjs.OptionType;
};
/**
* Options accepted when compiling schema types.
*/
export type ParserOptions = {
toCamelCase: boolean;
};
/**
* Method to invoke when union has no match
*/
export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any;
/**
* Error reporters must implement the reporter contract interface
*/
export interface ErrorReporterContract extends BaseReporter {
createError(): ValidationError;
}
/**
* The validator function to validate metadata given to a validation
* pipeline
*/
export type MetaDataValidator = (meta: Record<string, any>) => void;
/**
* Options accepted during the validate call.
*/
export type ValidationOptions<MetaData extends Record<string, any> | undefined> = {
/**
* Messages provider is used to resolve error messages during
* the validation lifecycle
*/
messagesProvider?: MessagesProviderContact;
/**
* Validation errors are reported directly to an error reporter. The reporter
* can decide how to format and output errors.
*/
errorReporter?: () => ErrorReporterContract;
} & ([undefined] extends MetaData ? {
meta?: MetaData;
} : {
meta: MetaData;
});
/**
* Infers the schema type
*/
export type Infer<Schema extends {
[OTYPE]: any;
}> = Schema[typeof OTYPE];
export type InferInput<Schema extends {
[ITYPE]: any;
}> = Schema[typeof ITYPE];
/**
* Comparison operators supported by requiredWhen
* rule
*/
export type NumericComparisonOperators = '>' | '<' | '>=' | '<=';
export type ArrayComparisonOperators = 'in' | 'notIn';
export type ComparisonOperators = ArrayComparisonOperators | NumericComparisonOperators | '=' | '!=';
type PickUndefined<T> = {
[K in keyof T]: undefined extends T[K] ? K : never;
}[keyof T];
type PickNotUndefined<T> = {
[K in keyof T]: undefined extends T[K] ? never : K;
}[keyof T];
type Id<T> = T extends infer U ? {
[K in keyof U]: U[K];
} : never;
export type UndefinedOptional<T> = Id<{
[K in PickUndefined<T>]?: T[K];
} & {
[K in PickNotUndefined<T>]: T[K];
}>;

View File

View File

@@ -0,0 +1,14 @@
import type { Validation, Validator } from '../types.js';
/**
* Returns args for the validation function.
*/
type GetArgs<T> = undefined extends T ? [options?: T] : [options: T];
/**
* Convert a validator function to a rule that you can apply
* to any schema type using the `schema.use` method.
*/
export declare function createRule<Options = undefined>(validator: Validator<Options>, metaData?: {
implicit?: boolean;
isAsync?: boolean;
}): (...options: GetArgs<Options>) => Validation<Options>;
export {};

View File

@@ -0,0 +1,150 @@
import isURL from 'validator/lib/isURL.js';
import isIBAN from 'validator/lib/isIBAN.js';
import isEmail from 'validator/lib/isEmail.js';
import { type PostalCodeLocale } from 'validator/lib/isPostalCode.js';
import { type MobilePhoneLocale } from 'validator/lib/isMobilePhone.js';
import type { FieldContext } from '../types.js';
/**
* Collection of helpers used across the codebase to coerce
* and type-check values from HTML forms.
*/
export declare const helpers: {
/**
* Returns true when value is not null and neither
* undefined
*/
exists(value: any): boolean;
/**
* Returns true when value is null or value is undefined
*/
isMissing(value: any): boolean;
/**
* Returns true when the value is one of the following.
*
* true
* 1
* "1"
* "true"
* "on"
*/
isTrue(value: any): boolean;
/**
* Returns true when the value is one of the following.
*
* false
* 0
* "0"
* "false"
*/
isFalse(value: any): boolean;
/**
* Check if the value is a valid string. This method narrows
* the type of value to string.
*/
isString(value: unknown): value is string;
/**
* Check if the value is a plain JavaScript object. This method
* filters out null and Arrays and does not consider them as Objects.
*/
isObject<Value>(value: unknown): value is Record<PropertyKey, Value>;
/**
* Check if an object has all the mentioned keys
*/
hasKeys(value: Record<string, any>, keys: string[]): boolean;
/**
* Check if the value is an Array.
*/
isArray<Value>(value: unknown): value is Value[];
/**
* Check if the value is a number or a string representation of a number.
*/
isNumeric(value: any): boolean;
/**
* Casts the value to a number using the Number method.
* Returns NaN when unable to cast.
*/
asNumber(value: any): number;
/**
* Casts the value to a boolean.
*
* - [true, 1, "1", "true", "on"] will be converted to true.
* - [false, 0, "0", "false"] will be converted to false.
* - Everything else will return null. So make sure to handle that case.
*/
asBoolean(value: any): boolean | null;
isEmail: typeof isEmail.default;
isURL: typeof isURL.default;
isAlpha: typeof import("validator").isAlpha;
isAlphaNumeric: typeof import("validator").isAlphanumeric;
isIP: typeof import("validator").isIP;
isUUID: typeof import("validator").isUUID;
isAscii: typeof import("validator").isAscii;
isCreditCard: typeof import("validator").isCreditCard;
isIBAN: typeof isIBAN.default;
isJWT: typeof import("validator").isJWT;
isLatLong: typeof import("validator").isLatLong;
isMobilePhone: typeof import("validator").isMobilePhone;
isPassportNumber: typeof import("validator").isPassportNumber;
isPostalCode: typeof import("validator").isPostalCode;
isSlug: typeof import("validator").isSlug;
isDecimal: typeof import("validator").isDecimal;
mobileLocales: MobilePhoneLocale[];
postalCountryCodes: PostalCodeLocale[];
passportCountryCodes: readonly ["AM", "AR", "AT", "AU", "AZ", "BE", "BG", "BR", "BY", "CA", "CH", "CY", "CZ", "DE", "DK", "DZ", "ES", "FI", "FR", "GB", "GR", "HR", "HU", "IE", "IN", "ID", "IR", "IS", "IT", "JM", "JP", "KR", "KZ", "LI", "LT", "LU", "LV", "LY", "MT", "MZ", "MY", "MX", "NL", "NZ", "PH", "PK", "PL", "PT", "RO", "RU", "SE", "SL", "SK", "TH", "TR", "UA", "US"];
/**
* Check if the value is a valid ULID
*/
isULID(value: unknown): boolean;
/**
* Check if the value is a valid color hexcode
*/
isHexColor: (value: string) => boolean;
/**
* Check if a URL has valid `A` or `AAAA` DNS records
*/
isActiveURL: (url: string) => Promise<boolean>;
/**
* Check if all the elements inside the dataset are unique.
*
* In case of an array of objects, you must provide one or more keys
* for the fields that must be unique across the objects.
*
* ```ts
* helpers.isDistinct([1, 2, 4, 5]) // true
*
* // Null and undefined values are ignored
* helpers.isDistinct([1, null, 2, null, 4, 5]) // true
*
* helpers.isDistinct([
* {
* email: 'foo@bar.com',
* name: 'foo'
* },
* {
* email: 'baz@bar.com',
* name: 'baz'
* }
* ], 'email') // true
*
* helpers.isDistinct([
* {
* email: 'foo@bar.com',
* tenant_id: 1,
* name: 'foo'
* },
* {
* email: 'foo@bar.com',
* tenant_id: 2,
* name: 'baz'
* }
* ], ['email', 'tenant_id']) // true
* ```
*/
isDistinct: (dataSet: any[], fields?: string | string[]) => boolean;
/**
* Returns the nested value from the field root
* object or the sibling value from the field
* parent object
*/
getNestedValue(key: string, field: FieldContext): any;
};

View File

@@ -0,0 +1,131 @@
import { createRule } from './create_rule.js';
import { SchemaBuilder } from '../schema/builder.js';
import { VineValidator } from './validator.js';
import { ValidationError } from '../errors/validation_error.js';
import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, MessagesProviderContact } from '../types.js';
/**
* Validate user input with type-safety using a pre-compiled schema.
*/
export declare class Vine extends SchemaBuilder {
/**
* Messages provider to use on the validator
*/
messagesProvider: MessagesProviderContact;
/**
* Error reporter to use on the validator
*/
errorReporter: () => ErrorReporterContract;
/**
* Control whether or not to convert empty strings to null
*/
convertEmptyStringsToNull: boolean;
/**
* Helpers to perform type-checking or cast types keeping
* HTML forms serialization behavior in mind.
*/
helpers: {
exists(value: any): boolean;
isMissing(value: any): boolean;
isTrue(value: any): boolean;
isFalse(value: any): boolean;
isString(value: unknown): value is string;
isObject<Value>(value: unknown): value is Record<PropertyKey, Value>;
hasKeys(value: Record<string, any>, keys: string[]): boolean;
isArray<Value>(value: unknown): value is Value[];
isNumeric(value: any): boolean;
asNumber(value: any): number;
asBoolean(value: any): boolean | null;
isEmail: typeof import("validator/lib/isEmail.js").default;
isURL: typeof import("validator/lib/isURL.js").default;
isAlpha: typeof import("validator").isAlpha;
isAlphaNumeric: typeof import("validator").isAlphanumeric;
isIP: typeof import("validator").isIP;
isUUID: typeof import("validator").isUUID;
isAscii: typeof import("validator").isAscii;
isCreditCard: typeof import("validator").isCreditCard;
isIBAN: typeof import("validator/lib/isIBAN.js").default;
isJWT: typeof import("validator").isJWT;
isLatLong: typeof import("validator").isLatLong;
isMobilePhone: typeof import("validator").isMobilePhone;
isPassportNumber: typeof import("validator").isPassportNumber;
isPostalCode: typeof import("validator").isPostalCode;
isSlug: typeof import("validator").isSlug;
isDecimal: typeof import("validator").isDecimal;
mobileLocales: import("validator/lib/isMobilePhone.js").MobilePhoneLocale[];
postalCountryCodes: import("validator/lib/isPostalCode.js").PostalCodeLocale[];
passportCountryCodes: readonly ["AM", "AR", "AT", "AU", "AZ", "BE", "BG", "BR", "BY", "CA", "CH", "CY", "CZ", "DE", "DK", "DZ", "ES", "FI", "FR", "GB", "GR", "HR", "HU", "IE", "IN", "ID", "IR", "IS", "IT", "JM", "JP", "KR", "KZ", "LI", "LT", "LU", "LV", "LY", "MT", "MZ", "MY", "MX", "NL", "NZ", "PH", "PK", "PL", "PT", "RO", "RU", "SE", "SL", "SK", "TH", "TR", "UA", "US"];
isULID(value: unknown): boolean;
isHexColor: (value: string) => boolean;
isActiveURL: (url: string) => Promise<boolean>;
isDistinct: (dataSet: any[], fields?: string | string[]) => boolean;
getNestedValue(key: string, field: import("@vinejs/compiler/types").FieldContext): any;
};
/**
* Convert a validation function to a Vine schema rule
*/
createRule: typeof createRule;
/**
* Pre-compiles a schema into a validation function.
*
* ```ts
* const validate = vine.compile(schema)
* await validate({ data })
* ```
*/
compile<Schema extends SchemaTypes>(schema: Schema): VineValidator<Schema, Record<string, any> | undefined>;
/**
* Define a callback to validate the metadata given to the validator
* at runtime
*/
withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator): {
compile: <Schema extends SchemaTypes>(schema: Schema) => VineValidator<Schema, MetaData>;
};
/**
* Validate data against a schema. Optionally, you can define
* error messages, fields, a custom messages provider,
* or an error reporter.
*
* ```ts
* await vine.validate({ schema, data })
* await vine.validate({ schema, data, messages, fields })
*
* await vine.validate({ schema, data, messages, fields }, {
* errorReporter
* })
* ```
*/
validate<Schema extends SchemaTypes>(options: {
/**
* Schema to use for validation
*/
schema: Schema;
/**
* Data to validate
*/
data: any;
} & ValidationOptions<Record<string, any> | undefined>): Promise<Infer<Schema>>;
/**
* Validate data against a schema without throwing the
* "ValidationError" exception. Instead the validation
* errors are returned within the return value.
*
* ```ts
* await vine.tryValidate({ schema, data })
* await vine.tryValidate({ schema, data, messages, fields })
*
* await vine.tryValidate({ schema, data, messages, fields }, {
* errorReporter
* })
* ```
*/
tryValidate<Schema extends SchemaTypes>(options: {
/**
* Schema to use for validation
*/
schema: Schema;
/**
* Data to validate
*/
data: any;
} & ValidationOptions<Record<string, any> | undefined>): Promise<[ValidationError, null] | [null, Infer<Schema>]>;
}

View File

@@ -0,0 +1,72 @@
import type { MessagesProviderContact, Refs, RootNode } from '@vinejs/compiler/types';
import { ITYPE, OTYPE } from '../symbols.js';
import { ValidationError } from '../errors/validation_error.js';
import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract } from '../types.js';
/**
* Vine Validator exposes the API to validate data using a pre-compiled
* schema.
*/
export declare class VineValidator<Schema extends SchemaTypes, MetaData extends undefined | Record<string, any>> {
#private;
/**
* Reference to static types
*/
[ITYPE]: Schema[typeof ITYPE];
[OTYPE]: Schema[typeof OTYPE];
/**
* Messages provider to use on the validator
*/
messagesProvider: MessagesProviderContact;
/**
* Error reporter to use on the validator
*/
errorReporter: () => ErrorReporterContract;
/**
* Validate data against a schema. Optionally, you can share metaData with
* the validator
*
* ```ts
* await validator.validate(data)
* await validator.validate(data, { meta: {} })
*
* await validator.validate(data, {
* meta: { userId: auth.user.id },
* errorReporter,
* messagesProvider
* })
* ```
*/
validate: (data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>]) => Promise<Infer<Schema>>;
constructor(schema: Schema, options: {
convertEmptyStringsToNull: boolean;
metaDataValidator?: MetaDataValidator;
messagesProvider: MessagesProviderContact;
errorReporter: () => ErrorReporterContract;
});
/**
* Performs validation without throwing the validation
* exception. Instead, the validation errors are
* returned as the first argument.
*
*
* ```ts
* await validator.tryValidate(data)
* await validator.tryValidate(data, { meta: {} })
*
* await validator.tryValidate(data, {
* meta: { userId: auth.user.id },
* errorReporter,
* messagesProvider
* })
* ```
*
*/
tryValidate(data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>]): Promise<[ValidationError, null] | [null, Infer<Schema>]>;
/**
* Returns the compiled schema and refs.
*/
toJSON(): {
schema: RootNode;
refs: Refs;
};
}

149
frontend/node_modules/@vinejs/vine/package.json generated vendored Normal file
View File

@@ -0,0 +1,149 @@
{
"name": "@vinejs/vine",
"description": "Form data validation library for Node.js",
"version": "3.0.1",
"engines": {
"node": ">=18.16.0"
},
"main": "build/index.js",
"type": "module",
"files": [
"build",
"!build/benchmarks",
"!build/bin",
"!build/tests"
],
"exports": {
".": "./build/index.js",
"./defaults": "./build/src/defaults.js",
"./factories": "./build/factories/main.js",
"./types": "./build/src/types.js",
"./schema/base/*": "./build/src/schema/base/*.js"
},
"scripts": {
"pretest": "npm run lint",
"test": "c8 npm run quick:test",
"lint": "eslint",
"format": "prettier --write .",
"typecheck": "tsc --noEmit",
"clean": "del-cli build",
"precompile": "npm run lint && npm run clean",
"compile": "tsup-node && tsc --emitDeclarationOnly --declaration",
"build": "npm run compile",
"version": "npm run build",
"prepublishOnly": "npm run build",
"release": "npx release-it",
"benchmark": "node build/benchmarks/flat_object.js && node build/benchmarks/nested_object.js && node build/benchmarks/array.js && node build/benchmarks/union.js",
"quick:test": "node --import=ts-node-maintained/register/esm --enable-source-maps bin/test.ts"
},
"devDependencies": {
"@adonisjs/eslint-config": "^2.0.0",
"@adonisjs/prettier-config": "^1.4.4",
"@adonisjs/tsconfig": "^1.4.0",
"@japa/assert": "^4.0.1",
"@japa/expect-type": "^2.0.3",
"@japa/runner": "^4.2.0",
"@japa/snapshot": "^2.0.8",
"@release-it/conventional-changelog": "^10.0.0",
"@swc/core": "1.10.7",
"@types/dlv": "^1.1.5",
"@types/node": "^22.13.10",
"ajv": "^8.17.1",
"benchmark": "^2.1.4",
"c8": "^10.1.3",
"del-cli": "^6.0.0",
"eslint": "^9.22.0",
"joi": "^17.13.3",
"prettier": "^3.5.3",
"release-it": "^18.1.2",
"ts-node-maintained": "^10.9.5",
"tsup": "^8.4.0",
"typescript": "^5.8.2",
"valibot": "^0.42.1",
"yup": "^1.6.1",
"zod": "^3.24.2"
},
"dependencies": {
"@poppinss/macroable": "^1.0.4",
"@types/validator": "^13.12.2",
"@vinejs/compiler": "^3.0.0",
"camelcase": "^8.0.0",
"dayjs": "^1.11.13",
"dlv": "^1.1.3",
"normalize-url": "^8.0.1",
"validator": "^13.12.0"
},
"author": "virk,vinejs",
"license": "MIT",
"homepage": "https://github.com/vinejs/vine#readme",
"keywords": [
"validator",
"validation"
],
"repository": {
"type": "git",
"url": "git+https://github.com/vinejs/vine.git"
},
"bugs": {
"url": "https://github.com/vinejs/vine/issues"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"tsup": {
"entry": [
"./index.ts",
"./src/defaults.ts",
"./factories/main.ts",
"./src/types.ts",
"./benchmarks/flat_object.ts",
"./benchmarks/nested_object.ts",
"./benchmarks/array.ts",
"./benchmarks/union.ts"
],
"outDir": "./build",
"clean": true,
"format": "esm",
"dts": false,
"sourcemap": false,
"target": "esnext"
},
"release-it": {
"git": {
"requireCleanWorkingDir": true,
"requireUpstream": true,
"commitMessage": "chore(release): ${version}",
"tagAnnotation": "v${version}",
"push": true,
"tagName": "v${version}"
},
"github": {
"release": true
},
"npm": {
"publish": true,
"skipChecks": true
},
"plugins": {
"@release-it/conventional-changelog": {
"preset": {
"name": "angular"
}
}
}
},
"c8": {
"reporter": [
"text",
"html"
],
"exclude": [
"tests/**",
"factories/**",
"bin/**",
"benchmarks/**"
]
},
"prettier": "@adonisjs/prettier-config"
}