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

View File

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

View File

@@ -0,0 +1,88 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { Schema } from 'effect';
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmptyString({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});
interface FormData {
username: string;
password: string;
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: effectTsResolver(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 effect-ts", 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,85 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { Schema } from 'effect';
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmptyString({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});
type FormData = Schema.Schema.Type<typeof schema>;
function TestComponent({
onSubmit,
}: {
onSubmit: (data: FormData) => void;
}) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: effectTsResolver(schema),
});
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 Zod 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 field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
export function TestComponentManualType({
onSubmit,
}: {
onSubmit: (data: FormData) => void;
}) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<Schema.Schema.Type<typeof schema>, undefined, FormData>({
resolver: effectTsResolver(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>
);
}

View File

@@ -0,0 +1,124 @@
import { Schema } from 'effect';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => 'A username is required' }),
),
password: Schema.String.pipe(
Schema.pattern(new RegExp('.*[A-Z].*'), {
message: () => 'At least 1 uppercase letter.',
}),
Schema.pattern(new RegExp('.*[a-z].*'), {
message: () => 'At least 1 lowercase letter.',
}),
Schema.pattern(new RegExp('.*\\d.*'), {
message: () => 'At least 1 number.',
}),
Schema.pattern(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
{
message: () => 'At least 1 special character.',
},
),
Schema.minLength(8, { message: () => 'Must be at least 8 characters.' }),
),
accessToken: Schema.Union(Schema.String, Schema.Number),
birthYear: Schema.Number.pipe(
Schema.greaterThan(1900, {
message: () => 'Must be greater than the year 1900',
}),
Schema.filter((value) => value < new Date().getFullYear(), {
message: () => 'Must be before the current year.',
}),
),
email: Schema.String.pipe(
Schema.pattern(
new RegExp(
/^(?!\.)(?!.*\.\.)([A-Z0-9_+-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i,
),
{
message: () => 'A valid email address is required.',
},
),
),
tags: Schema.Array(
Schema.Struct({
name: Schema.String,
}),
),
luckyNumbers: Schema.Array(Schema.Number),
enabled: Schema.Boolean,
animal: Schema.Union(Schema.String, Schema.Literal('bird', 'snake')),
vehicles: Schema.Array(
Schema.Union(
Schema.Struct({
type: Schema.Literal('car'),
brand: Schema.String,
horsepower: Schema.Number,
}),
Schema.Struct({
type: Schema.Literal('bike'),
speed: Schema.Number,
}),
),
),
});
export const validData: Schema.Schema.Type<typeof schema> = {
accessToken: 'abcd1234',
animal: 'dog',
birthYear: 2000,
email: 'johnDoe@here.there',
enabled: true,
luckyNumbers: [1, 2, 3, 4, 5],
password: 'Super#Secret123',
tags: [{ name: 'move' }, { name: 'over' }, { name: 'zod' }, { name: ';)' }],
username: 'johnDoe',
vehicles: [
{ type: 'bike', speed: 5 },
{ type: 'car', brand: 'BMW', horsepower: 150 },
],
};
export const invalidData = {
username: 'test',
password: 'Password123',
repeatPassword: 'Password123',
birthYear: 2000,
accessToken: '1015d809-e99d-41ec-b161-981a3c243df8',
email: 'john@doe.com',
tags: [{ name: 'test' }],
enabled: true,
animal: ['dog'],
luckyNumbers: [1, 2, '3'],
like: [
{
id: '1',
name: 'name',
},
],
vehicles: [
{ type: 'car', brand: 'BMW', horsepower: 150 },
{ type: 'car', brand: 'Mercedes' },
],
} as any as Schema.Schema.Type<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,74 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`effectTsResolver > should return a single error from effectTsResolver when validation fails 1`] = `
{
"errors": {
"animal": {
"message": "Expected string, actual ["dog"]",
"ref": undefined,
"type": "Type",
},
"luckyNumbers": [
,
,
{
"message": "Expected number, actual "3"",
"ref": undefined,
"type": "Type",
},
],
"password": {
"message": "At least 1 special character.",
"ref": {
"name": "password",
},
"type": "Refinement",
},
"vehicles": [
,
{
"horsepower": {
"message": "is missing",
"ref": undefined,
"type": "Missing",
},
},
],
},
"values": {},
}
`;
exports[`effectTsResolver > should return all the errors from effectTsResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"phoneNumber": {
"message": "Please enter a valid phone number in international format.",
"ref": {
"name": "phoneNumber",
},
"type": "Refinement",
"types": {
"Refinement": "Please enter a valid phone number in international format.",
"Type": "Expected undefined, actual "123"",
},
},
},
"values": {},
}
`;
exports[`effectTsResolver > should return the first error from effectTsResolver when validation fails with \`validateAllFieldCriteria\` set to firstError 1`] = `
{
"errors": {
"phoneNumber": {
"message": "Please enter a valid phone number in international format.",
"ref": {
"name": "phoneNumber",
},
"type": "Refinement",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,146 @@
import { Schema } from 'effect';
import { Resolver, useForm } from 'react-hook-form';
import { SubmitHandler } from 'react-hook-form';
import { effectTsResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('effectTsResolver', () => {
it('should return values from effectTsResolver when validation pass', async () => {
const result = await effectTsResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from effectTsResolver when validation fails', async () => {
const result = await effectTsResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return the first error from effectTsResolver when validation fails with `validateAllFieldCriteria` set to firstError', async () => {
const SignupSchema = Schema.Struct({
phoneNumber: Schema.optional(
Schema.String.pipe(
Schema.pattern(/^\+\d{7,15}$/, {
message: () =>
'Please enter a valid phone number in international format.',
}),
),
),
});
const result = await effectTsResolver(SignupSchema)(
{ phoneNumber: '123' },
undefined,
{
fields: {
phoneNumber: {
ref: { name: 'phoneNumber' },
name: 'phoneNumber',
},
},
criteriaMode: 'firstError',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return all the errors from effectTsResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const SignupSchema = Schema.Struct({
phoneNumber: Schema.optional(
Schema.String.pipe(
Schema.pattern(/^\+\d{7,15}$/, {
message: () =>
'Please enter a valid phone number in international format.',
}),
),
),
});
const result = await effectTsResolver(SignupSchema)(
{ phoneNumber: '123' },
undefined,
{
fields: {
phoneNumber: {
ref: { name: 'phoneNumber' },
name: 'phoneNumber',
},
},
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a effectTs schema', () => {
const resolver = effectTsResolver(Schema.Struct({ id: Schema.Number }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<Readonly<{ id: number }>, unknown, Readonly<{ id: number }>>
>();
});
it('should correctly infer the output type from a effectTs schema using a transform', () => {
const resolver = effectTsResolver(
Schema.Struct({
id: Schema.transform(Schema.Number, Schema.String, {
decode: (val) => String(val),
encode: (val) => Number(val),
}),
}),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<Readonly<{ id: number }>, unknown, Readonly<{ id: string }>>
>();
});
it('should correctly infer the output type from a effectTs schema for the handleSubmit function in useForm', () => {
const schema = Schema.Struct({ id: Schema.Number });
const form = useForm({
resolver: effectTsResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit)
.parameter(0)
.toEqualTypeOf<SubmitHandler<Readonly<{ id: number }>>>();
});
it('should correctly infer the output type from a effectTs schema with a transform for the handleSubmit function in useForm', () => {
const schema = Schema.Struct({
id: Schema.transform(Schema.Number, Schema.String, {
decode: (val) => String(val),
encode: (val) => Number(val),
}),
});
const form = useForm({
resolver: effectTsResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit)
.parameter(0)
.toEqualTypeOf<SubmitHandler<Readonly<{ id: string }>>>();
});
});

View File

@@ -0,0 +1,105 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { Effect, Schema } from 'effect';
import { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';
import { ParseOptions } from 'effect/SchemaAST';
import {
type FieldError,
FieldValues,
Resolver,
appendErrors,
} from 'react-hook-form';
export function effectTsResolver<Input extends FieldValues, Context, Output>(
schema: Schema.Schema<Output, Input>,
schemaOptions?: ParseOptions,
resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
},
): Resolver<Input, Context, Output>;
export function effectTsResolver<Input extends FieldValues, Context, Output>(
schema: Schema.Schema<Output, Input>,
schemaOptions: ParseOptions | undefined,
resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
},
): Resolver<Input, Context, Input>;
/**
* Creates a resolver for react-hook-form using Effect.ts schema validation
* @param {Schema.Schema<TFieldValues, I>} schema - The Effect.ts schema to validate against
* @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options
* @returns {Resolver<Schema.Schema.Type<typeof schema>>} A resolver function compatible with react-hook-form
* @example
* const schema = Schema.Struct({
* name: Schema.String,
* age: Schema.Number
* });
*
* useForm({
* resolver: effectTsResolver(schema)
* });
*/
export function effectTsResolver<Input extends FieldValues, Context, Output>(
schema: Schema.Schema<Output, Input>,
schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },
): Resolver<Input, Context, Output | Input> {
return (values, _, options) => {
return decodeUnknown(
schema,
schemaOptions,
)(values).pipe(
Effect.catchAll((parseIssue) =>
Effect.flip(ArrayFormatter.formatIssue(parseIssue)),
),
Effect.mapError((issues) => {
const validateAllFieldCriteria =
!options.shouldUseNativeValidation && options.criteriaMode === 'all';
const errors = issues.reduce(
(acc, error) => {
const key = error.path.join('.');
if (!acc[key]) {
acc[key] = { message: error.message, type: error._tag };
}
if (validateAllFieldCriteria) {
const types = acc[key].types;
const messages = types && types[String(error._tag)];
acc[key] = appendErrors(
key,
validateAllFieldCriteria,
acc,
error._tag,
messages
? ([] as string[]).concat(messages as string[], error.message)
: error.message,
) as FieldError;
}
return acc;
},
{} as Record<string, FieldError>,
);
return toNestErrors(errors, options);
}),
Effect.tap(() =>
Effect.sync(
() =>
options.shouldUseNativeValidation &&
validateFieldsNatively({}, options),
),
),
Effect.match({
onFailure: (errors) => ({ errors, values: {} }),
onSuccess: (result) => ({ errors: {}, values: result }),
}),
Effect.runPromise,
);
};
}

View File

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