main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,85 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import vine from '@vinejs/vine';
import { Infer } from '@vinejs/vine/build/src/types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { vineResolver } from '..';
const schema = vine.compile(
vine.object({
username: vine.string().minLength(1),
password: vine.string().minLength(1),
}),
);
type FormData = Infer<typeof schema> & { unusedProperty: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: vineResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Zod", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(
'The username field must have at least 1 characters',
);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'The password field must have at least 1 characters',
);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View File

@@ -0,0 +1,59 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import vine from '@vinejs/vine';
import { Infer } from '@vinejs/vine/build/src/types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { vineResolver } from '..';
const schema = vine.compile(
vine.object({
username: vine.string().minLength(1),
password: vine.string().minLength(1),
}),
);
type FormData = Infer<typeof schema> & { unusedProperty: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: vineResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with Vine and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(
screen.getByText(/The username field must have at least 1 characters/i),
).toBeInTheDocument();
expect(
screen.getByText(/The password field must have at least 1 characters/i),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,76 @@
import vine from '@vinejs/vine';
import { Infer } from '@vinejs/vine/build/src/types';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = vine.compile(
vine.object({
username: vine.string().regex(/^\w+$/).minLength(3).maxLength(30),
password: vine
.string()
.regex(new RegExp('.*[A-Z].*'))
.regex(new RegExp('.*[a-z].*'))
.regex(new RegExp('.*\\d.*'))
.regex(new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'))
.minLength(8)
.confirmed({ confirmationField: 'repeatPassword' }),
repeatPassword: vine.string().sameAs('password'),
accessToken: vine.unionOfTypes([vine.string(), vine.number()]),
birthYear: vine.number().min(1900).max(2013),
email: vine.string().email().optional(),
tags: vine.array(vine.string()),
enabled: vine.boolean(),
like: vine.array(
vine.object({
id: vine.number(),
name: vine.string().fixedLength(4),
}),
),
dateStr: vine
.string()
.transform((value: string) => new Date(value).toISOString()),
}),
);
export const validData: Infer<typeof schema> = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: '2020-01-01T00:00:00.000Z',
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View File

@@ -0,0 +1,180 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`vineResolver > should return a single error from vineResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "Invalid value provided for accessToken field",
"ref": undefined,
"type": "unionOfTypes",
},
"birthYear": {
"message": "The birthYear field must be a number",
"ref": undefined,
"type": "number",
},
"dateStr": {
"message": "The dateStr field must be defined",
"ref": undefined,
"type": "required",
},
"email": {
"message": "The email field must be a valid email address",
"ref": {
"name": "email",
},
"type": "email",
},
"enabled": {
"message": "The enabled field must be defined",
"ref": undefined,
"type": "required",
},
"like": [
{
"id": {
"message": "The id field must be a number",
"ref": undefined,
"type": "number",
},
"name": {
"message": "The name field must be defined",
"ref": undefined,
"type": "required",
},
},
],
"password": {
"message": "The password field format is invalid",
"ref": {
"name": "password",
},
"type": "regex",
},
"repeatPassword": {
"message": "The repeatPassword field must be defined",
"ref": undefined,
"type": "required",
},
"tags": {
"message": "The tags field must be defined",
"ref": undefined,
"type": "required",
},
"username": {
"message": "The username field must be defined",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`vineResolver > should return all the errors from vineResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"accessToken": {
"message": "Invalid value provided for accessToken field",
"ref": undefined,
"type": "unionOfTypes",
"types": {
"unionOfTypes": "Invalid value provided for accessToken field",
},
},
"birthYear": {
"message": "The birthYear field must be a number",
"ref": undefined,
"type": "number",
"types": {
"number": "The birthYear field must be a number",
},
},
"dateStr": {
"message": "The dateStr field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The dateStr field must be defined",
},
},
"email": {
"message": "The email field must be a valid email address",
"ref": {
"name": "email",
},
"type": "email",
"types": {
"email": "The email field must be a valid email address",
},
},
"enabled": {
"message": "The enabled field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The enabled field must be defined",
},
},
"like": [
{
"id": {
"message": "The id field must be a number",
"ref": undefined,
"type": "number",
"types": {
"number": "The id field must be a number",
},
},
"name": {
"message": "The name field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The name field must be defined",
},
},
},
],
"password": {
"message": "The password field format is invalid",
"ref": {
"name": "password",
},
"type": "regex",
"types": {
"regex": "The password field format is invalid",
},
},
"repeatPassword": {
"message": "The repeatPassword field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The repeatPassword field must be defined",
},
},
"tags": {
"message": "The tags field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The tags field must be defined",
},
},
"username": {
"message": "The username field must be defined",
"ref": {
"name": "username",
},
"type": "required",
"types": {
"required": "The username field must be defined",
},
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,53 @@
import { vineResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('vineResolver', () => {
it('should return values from vineResolver when validation pass', async () => {
const schemaSpy = vi.spyOn(schema, 'validate');
const result = await vineResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from vineResolver when validation fails', async () => {
const result = await vineResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from vineResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await vineResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return values from vineResolver when validation pass & raw=true', async () => {
const schemaSpy = vi.spyOn(schema, 'validate');
const result = await vineResolver(schema, undefined, { raw: true })(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
});

2
node_modules/@hookform/resolvers/vine/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from './vine';
export * from './types';

13
node_modules/@hookform/resolvers/vine/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { VineValidator } from '@vinejs/vine';
import { ValidationOptions } from '@vinejs/vine/build/src/types';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T extends VineValidator<any, any>>(
schema: T,
schemaOptions?: ValidationOptions<any>,
resolverOptions?: { raw?: boolean },
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;

68
node_modules/@hookform/resolvers/vine/src/vine.ts generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { SimpleErrorReporter, errors } from '@vinejs/vine';
import { FieldError, FieldErrors, appendErrors } from 'react-hook-form';
import type { Resolver } from './types';
const parseErrorSchema = (
vineErrors: SimpleErrorReporter['errors'],
validateAllFieldCriteria: boolean,
) => {
const schemaErrors: Record<string, FieldError> = {};
for (; vineErrors.length; ) {
const error = vineErrors[0];
const path = error.field;
if (!(path in schemaErrors)) {
schemaErrors[path] = { message: error.message, type: error.rule };
}
if (validateAllFieldCriteria) {
const { types } = schemaErrors[path];
const messages = types && types[error.rule];
schemaErrors[path] = appendErrors(
path,
validateAllFieldCriteria,
schemaErrors,
error.rule,
messages ? [...(messages as string[]), error.message] : error.message,
) as FieldError;
}
vineErrors.shift();
}
return schemaErrors;
};
export const vineResolver: Resolver =
(schema, schemaOptions, resolverOptions = {}) =>
async (values, _, options) => {
try {
const data = await schema.validate(values, schemaOptions);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {} as FieldErrors,
values: resolverOptions.raw ? values : data,
};
} catch (error: any) {
if (error instanceof errors.E_VALIDATION_ERROR) {
return {
values: {},
errors: toNestErrors(
parseErrorSchema(
error.messages,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
throw error;
}
};