added apps

This commit is contained in:
2025-04-10 20:11:36 +03:00
parent 3613f9030e
commit c3b7556e7e
346 changed files with 265054 additions and 159 deletions

17
node_modules/@hookform/resolvers/yup/package.json generated vendored Normal file
View File

@@ -0,0 +1,17 @@
{
"name": "@hookform/resolvers/yup",
"amdName": "hookformResolversYup",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: yup",
"main": "dist/yup.js",
"module": "dist/yup.module.js",
"umd:main": "dist/yup.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.55.0",
"@hookform/resolvers": "^2.0.0"
}
}

View File

@@ -0,0 +1,81 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { useForm } from 'react-hook-form';
import * as Yup from 'yup';
import { yupResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Yup.object({
username: Yup.string().required(USERNAME_REQUIRED_MESSAGE),
password: Yup.string().required(PASSWORD_REQUIRED_MESSAGE),
});
type FormData = Yup.InferType<typeof schema>;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: yupResolver(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 Yup", 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(USERNAME_REQUIRED_MESSAGE);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
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,52 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import * as Yup from 'yup';
import { yupResolver } from '..';
const schema = Yup.object({
username: Yup.string().required(),
password: Yup.string().required(),
});
type FormData = Yup.InferType<typeof schema>;
interface Props {
onSubmit: SubmitHandler<FormData>;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
resolver: yupResolver(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 Yup 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(/username is a required field/i)).toBeInTheDocument();
expect(screen.getByText(/password is a required field/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,80 @@
import { Field, InternalFieldName } from 'react-hook-form';
import * as yup from 'yup';
export const schema = yup.object({
username: yup.string().matches(/^\w+$/).min(3).max(30).required(),
password: yup
.string()
.matches(new RegExp('.*[A-Z].*'), 'One uppercase character')
.matches(new RegExp('.*[a-z].*'), 'One lowercase character')
.matches(new RegExp('.*\\d.*'), 'One number')
.matches(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8, 'Must be at least 8 characters in length')
.required('New Password is required'),
repeatPassword: yup.ref('password'),
accessToken: yup.string(),
birthYear: yup.number().min(1900).max(2013),
email: yup.string().email(),
tags: yup.array(yup.string()),
enabled: yup.boolean(),
like: yup.array().of(
yup.object({
id: yup.number().required(),
name: yup.string().length(4).required(),
}),
),
});
export const schemaWithWhen = yup.object({
name: yup.string().required(),
value: yup.string().when('name', ([name], schema) => {
return name === 'test' ? yup.number().required() : schema;
}),
});
export const validData = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
like: [
{
id: 1,
name: 'name',
},
],
} satisfies yup.InferType<typeof schema>;
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
// Must be set to "unknown", otherwise typescript knows that it is invalid
} as unknown as Required<yup.InferType<typeof schema>>;
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,244 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`yupResolver > should return a single error from yupResolver when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"birthYear"\`).",
"ref": undefined,
"type": "typeError",
},
"like": [
{
"id": {
"message": "like[0].id must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"z"\`).",
"ref": undefined,
"type": "typeError",
},
"name": {
"message": "like[0].name is a required field",
"ref": undefined,
"type": "optionality",
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "matches",
},
"username": {
"message": "username is a required field",
"ref": {
"name": "username",
},
"type": "optionality",
},
},
"values": {},
}
`;
exports[`yupResolver > should return a single error from yupResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"birthYear"\`).",
"ref": undefined,
"type": "typeError",
},
"like": [
{
"id": {
"message": "like[0].id must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"z"\`).",
"ref": undefined,
"type": "typeError",
},
"name": {
"message": "like[0].name is a required field",
"ref": undefined,
"type": "optionality",
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "matches",
},
"username": {
"message": "username is a required field",
"ref": {
"name": "username",
},
"type": "optionality",
},
},
"values": {},
}
`;
exports[`yupResolver > should return all the errors from yupResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"birthYear"\`).",
"ref": undefined,
"type": "typeError",
"types": {
"typeError": "birthYear must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"birthYear"\`).",
},
},
"like": [
{
"id": {
"message": "like[0].id must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"z"\`).",
"ref": undefined,
"type": "typeError",
"types": {
"typeError": "like[0].id must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"z"\`).",
},
},
"name": {
"message": "like[0].name is a required field",
"ref": undefined,
"type": "optionality",
"types": {
"optionality": "like[0].name is a required field",
},
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "matches",
"types": {
"matches": [
"One uppercase character",
"One lowercase character",
"One number",
],
"min": "Must be at least 8 characters in length",
},
},
"username": {
"message": "username is a required field",
"ref": {
"name": "username",
},
"type": "optionality",
"types": {
"optionality": "username is a required field",
},
},
},
"values": {},
}
`;
exports[`yupResolver > should return all the errors from yupResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"birthYear"\`).",
"ref": undefined,
"type": "typeError",
"types": {
"typeError": "birthYear must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"birthYear"\`).",
},
},
"like": [
{
"id": {
"message": "like[0].id must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"z"\`).",
"ref": undefined,
"type": "typeError",
"types": {
"typeError": "like[0].id must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`"z"\`).",
},
},
"name": {
"message": "like[0].name is a required field",
"ref": undefined,
"type": "optionality",
"types": {
"optionality": "like[0].name is a required field",
},
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "matches",
"types": {
"matches": [
"One uppercase character",
"One lowercase character",
"One number",
],
"min": "Must be at least 8 characters in length",
},
},
"username": {
"message": "username is a required field",
"ref": {
"name": "username",
},
"type": "optionality",
"types": {
"optionality": "username is a required field",
},
},
},
"values": {},
}
`;
exports[`yupResolver > should return an error from yupResolver when validation fails and pass down the yup context 1`] = `
{
"errors": {
"name": {
"message": "name must be at least 6 characters",
"ref": undefined,
"type": "min",
},
},
"values": {},
}
`;
exports[`yupResolver > should return correct error message with using yup.test 1`] = `
{
"errors": {
"": {
"message": "Email or name are required",
"ref": undefined,
"type": "name",
},
},
"values": {},
}
`;
exports[`yupResolver > should throw an error without inner property 1`] = `
{
"errors": {
"value": {
"message": "value must be a \`number\` type, but the final value was: \`NaN\` (cast from the value \`""\`).",
"ref": undefined,
"type": "typeError",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,285 @@
import { type Resolver, type SubmitHandler, useForm } from 'react-hook-form';
/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */
import * as yup from 'yup';
import { yupResolver } from '..';
import {
fields,
invalidData,
schema,
schemaWithWhen,
validData,
} from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('yupResolver', () => {
it('should return values from yupResolver when validation pass', async () => {
const schemaSpy = vi.spyOn(schema, 'validate');
const schemaSyncSpy = vi.spyOn(schema, 'validateSync');
const result = await yupResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(schemaSyncSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return values from yupResolver with `mode: sync` when validation pass', async () => {
const validateSyncSpy = vi.spyOn(schema, 'validateSync');
const validateSpy = vi.spyOn(schema, 'validate');
const result = await yupResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from yupResolver when validation fails', async () => {
const result = await yupResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return a single error from yupResolver with `mode: sync` when validation fails', async () => {
const validateSyncSpy = vi.spyOn(schema, 'validateSync');
const validateSpy = vi.spyOn(schema, 'validate');
const result = await yupResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});
it('should return all the errors from yupResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await yupResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from yupResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await yupResolver(schema, undefined, { mode: 'sync' })(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return an error from yupResolver when validation fails and pass down the yup context', async () => {
const data = { name: 'eric' };
const context = { min: true };
const schemaWithContext = yup.object({
name: yup
.string()
.required()
.when('$min', ([min], schema) => {
return min ? schema.min(6) : schema;
}),
});
const validateSpy = vi.spyOn(schemaWithContext, 'validate');
const result = await yupResolver(schemaWithContext)(data, context, {
fields,
shouldUseNativeValidation,
});
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).toHaveBeenCalledWith(
data,
expect.objectContaining({
abortEarly: false,
context,
}),
);
expect(result).toMatchSnapshot();
});
it('should return correct error message with using yup.test', async () => {
const result = await yupResolver(
yup
.object({
name: yup.string(),
email: yup.string(),
})
.test(
'name',
'Email or name are required',
(value) => !!(value && (value.name || value.email)),
),
)({ name: '', email: '' }, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it("should merge default yup resolver options with yup's options", async () => {
const validateSpy = vi.spyOn(schema, 'validate');
await yupResolver(schema, { stripUnknown: true })(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(validateSpy.mock.calls[0][1]).toEqual(
expect.objectContaining({ stripUnknown: true, abortEarly: false }),
);
});
it('should throw an error without inner property', async () => {
const result = await yupResolver(schemaWithWhen)(
{ name: 'test', value: '' },
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should throw any error unrelated to Yup', async () => {
const schemaWithCustomError = schema.transform(() => {
throw Error('custom error');
});
const promise = yupResolver(schemaWithCustomError)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
await expect(promise).rejects.toThrow('custom error');
});
it('should return values from yupResolver when validation pass & raw=true', async () => {
const schemaSpy = vi.spyOn(schema, 'validate');
const schemaSyncSpy = vi.spyOn(schema, 'validateSync');
const result = await yupResolver(schema, undefined, { raw: true })(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(schemaSyncSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
});
it('shoud validate a lazy schema with success', async () => {
const lazySchema = yup.lazy(() =>
yup.object().shape({ firstName: yup.string().optional() }),
);
const schemaSpy = vi.spyOn(lazySchema, 'validate');
const schemaSyncSpy = vi.spyOn(lazySchema, 'validateSync');
const result = await yupResolver(lazySchema, undefined)(
{ firstName: 'resolver' },
undefined,
{
fields: {
firstName: {
ref: { name: 'firstName' },
name: 'firstName',
},
},
shouldUseNativeValidation,
},
);
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(schemaSyncSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: { firstName: 'resolver' } });
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a yup schema', () => {
const resolver = yupResolver(yup.object({ id: yup.number().required() }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a yup schema using a transform', () => {
const resolver = yupResolver(
yup.object({
id: yup
.number()
.required()
.transform((val) => String(val)),
}),
);
// Because Yup is not able to infer the output type from the schema with a transform, the output type remains unchanged
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a yup schema for the handleSubmit function in useForm', () => {
const schema = yup.object({ id: yup.number().required() });
const form = useForm({
resolver: yupResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: number;
}>
>();
});
it('should correctly infer the output type from a yup schema with a transform for the handleSubmit function in useForm', () => {
const schema = yup.object({
id: yup
.number()
.required()
.transform((val) => String(val)),
});
const form = useForm({
resolver: yupResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
// Because Yup is not able to infer the output type from the schema with a transform, the output type remains unchanged
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: number;
}>
>();
});
});

1
node_modules/@hookform/resolvers/yup/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './yup';

135
node_modules/@hookform/resolvers/yup/src/yup.ts generated vendored Normal file
View File

@@ -0,0 +1,135 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import {
FieldError,
FieldValues,
Resolver,
appendErrors,
} from 'react-hook-form';
import * as Yup from 'yup';
/**
* Why `path!` ? because it could be `undefined` in some case
* https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
*/
function parseErrorSchema(
error: Yup.ValidationError,
validateAllFieldCriteria: boolean,
) {
return (error.inner || []).reduce<Record<string, FieldError>>(
(previous, error) => {
if (!previous[error.path!]) {
previous[error.path!] = { message: error.message, type: error.type! };
}
if (validateAllFieldCriteria) {
const types = previous[error.path!].types;
const messages = types && types[error.type!];
previous[error.path!] = appendErrors(
error.path!,
validateAllFieldCriteria,
previous,
error.type!,
messages
? ([] as string[]).concat(messages as string[], error.message)
: error.message,
) as FieldError;
}
return previous;
},
{},
);
}
export function yupResolver<Input extends FieldValues, Context, Output>(
schema:
| Yup.ObjectSchema<Input, any, Output, any>
| ReturnType<typeof Yup.lazy<Yup.ObjectSchema<Input, any, Output, any>>>,
schemaOptions?: Parameters<(typeof schema)['validate']>[1],
resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
},
): Resolver<Input, Context, Yup.InferType<typeof schema>>;
export function yupResolver<Input extends FieldValues, Context, Output>(
schema:
| Yup.ObjectSchema<Input, any, Output, any>
| ReturnType<typeof Yup.lazy<Yup.ObjectSchema<Input, any, Output, any>>>,
schemaOptions: Parameters<(typeof schema)['validate']>[1] | undefined,
resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
},
): Resolver<Input, Context, Input>;
/**
* Creates a resolver for react-hook-form using Yup schema validation
* @param {Yup.ObjectSchema<TFieldValues> | ReturnType<typeof Yup.lazy<Yup.ObjectSchema<TFieldValues>>>} schema - Yup validation schema
* @param {Parameters<(typeof schema)['validate']>[1]} schemaOptions - Options to pass to Yup's validate/validateSync
* @param {Object} resolverOptions - Additional resolver configuration
* @param {('async' | 'sync')} [resolverOptions.mode] - Validation mode
* @param {boolean} [resolverOptions.raw] - If true, returns raw values instead of validated results
* @returns {Resolver<Yup.InferType<typeof schema> | Input>} A resolver function compatible with react-hook-form
* @example
* const schema = Yup.object({
* name: Yup.string().required(),
* age: Yup.number().required(),
* });
*
* useForm({
* resolver: yupResolver(schema)
* });
*/
export function yupResolver<Input extends FieldValues, Context, Output>(
schema:
| Yup.ObjectSchema<Input, any, Output, any>
| ReturnType<typeof Yup.lazy<Yup.ObjectSchema<Input, any, Output, any>>>,
schemaOptions?: Parameters<(typeof schema)['validate']>[1],
resolverOptions: {
mode?: 'async' | 'sync';
raw?: boolean;
} = {},
): Resolver<Input, Context, Yup.InferType<typeof schema> | Input> {
return async (values: Input, context, options) => {
try {
if (schemaOptions?.context && process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.warn(
"You should not used the yup options context. Please, use the 'useForm' context object instead",
);
}
const result = await schema[
resolverOptions.mode === 'sync' ? 'validateSync' : 'validate'
](
values,
Object.assign({ abortEarly: false }, schemaOptions, { context }),
);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
values: resolverOptions.raw ? Object.assign({}, values) : result,
errors: {},
};
} catch (e: any) {
if (!e.inner) {
throw e;
}
return {
values: {},
errors: toNestErrors(
parseErrorSchema(
e,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
};
}