Save current BZZZ config-ui state before CHORUS branding update
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
19
install/config-ui/node_modules/@hookform/resolvers/io-ts/package.json
generated
vendored
Normal file
19
install/config-ui/node_modules/@hookform/resolvers/io-ts/package.json
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@hookform/resolvers/io-ts",
|
||||
"amdName": "hookformResolversIoTs",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: io-ts",
|
||||
"main": "dist/io-ts.js",
|
||||
"module": "dist/io-ts.module.js",
|
||||
"umd:main": "dist/io-ts.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": "^7.0.0",
|
||||
"@hookform/resolvers": "^2.0.0",
|
||||
"io-ts": "^2.0.0",
|
||||
"fp-ts": "^2.7.0"
|
||||
}
|
||||
}
|
||||
85
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
85
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ioTsResolver } from '..';
|
||||
|
||||
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
|
||||
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
|
||||
|
||||
const schema = t.type({
|
||||
username: tt.withMessage(tt.NonEmptyString, () => USERNAME_REQUIRED_MESSAGE),
|
||||
password: tt.withMessage(tt.NonEmptyString, () => 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: ioTsResolver(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 io-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('');
|
||||
});
|
||||
63
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx
generated
vendored
Normal file
63
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ioTsResolver } from '..';
|
||||
|
||||
const schema = t.type({
|
||||
username: tt.withMessage(
|
||||
tt.NonEmptyString,
|
||||
() => 'username is a required field',
|
||||
),
|
||||
password: tt.withMessage(
|
||||
tt.NonEmptyString,
|
||||
() => 'password is a required field',
|
||||
),
|
||||
});
|
||||
|
||||
interface FormData {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const {
|
||||
register,
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
} = useForm<FormData>({
|
||||
resolver: ioTsResolver(schema),
|
||||
criteriaMode: 'all',
|
||||
});
|
||||
|
||||
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 io-ts 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();
|
||||
});
|
||||
129
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
129
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
@@ -0,0 +1,129 @@
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
export const schema = t.intersection([
|
||||
t.type({
|
||||
username: tt.NonEmptyString,
|
||||
password: tt.NonEmptyString,
|
||||
accessToken: tt.UUID,
|
||||
birthYear: t.number,
|
||||
email: t.string,
|
||||
tags: t.array(
|
||||
t.type({
|
||||
name: t.string,
|
||||
}),
|
||||
),
|
||||
luckyNumbers: t.array(t.number),
|
||||
enabled: t.boolean,
|
||||
animal: t.union([
|
||||
t.string,
|
||||
t.number,
|
||||
t.literal('bird'),
|
||||
t.literal('snake'),
|
||||
]),
|
||||
vehicles: t.array(
|
||||
t.union([
|
||||
t.type({
|
||||
type: t.literal('car'),
|
||||
brand: t.string,
|
||||
horsepower: t.number,
|
||||
}),
|
||||
t.type({
|
||||
type: t.literal('bike'),
|
||||
speed: t.number,
|
||||
}),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
t.partial({
|
||||
like: t.array(
|
||||
t.type({
|
||||
id: tt.withMessage(
|
||||
t.number,
|
||||
(i) => `this id is very important but you passed: ${typeof i}(${i})`,
|
||||
),
|
||||
name: t.string,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
interface Data {
|
||||
username: string;
|
||||
password: string;
|
||||
accessToken: string;
|
||||
birthYear?: number;
|
||||
luckyNumbers: number[];
|
||||
email?: string;
|
||||
animal: string | number;
|
||||
tags: { name: string }[];
|
||||
enabled: boolean;
|
||||
like: { id: number; name: string }[];
|
||||
vehicles: Array<
|
||||
| { type: 'car'; brand: string; horsepower: number }
|
||||
| { type: 'bike'; speed: number }
|
||||
>;
|
||||
}
|
||||
|
||||
export const validData: Data = {
|
||||
username: 'Doe',
|
||||
password: 'Password123',
|
||||
accessToken: 'c2883927-5178-4ad1-bbee-07ba33a5de19',
|
||||
birthYear: 2000,
|
||||
email: 'john@doe.com',
|
||||
tags: [{ name: 'test' }],
|
||||
enabled: true,
|
||||
luckyNumbers: [17, 5],
|
||||
animal: 'cat',
|
||||
like: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
vehicles: [{ 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' },
|
||||
],
|
||||
};
|
||||
|
||||
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',
|
||||
},
|
||||
};
|
||||
89
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap
generated
vendored
Normal file
89
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap
generated
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`ioTsResolver > should return a single error from ioTsResolver when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"animal": {
|
||||
"message": "expected string but got ["dog"]",
|
||||
"ref": undefined,
|
||||
"type": "string",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "this id is very important but you passed: string(1)",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
"luckyNumbers": [
|
||||
,
|
||||
,
|
||||
{
|
||||
"message": "expected number but got "3"",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
],
|
||||
"vehicles": [
|
||||
,
|
||||
{
|
||||
"horsepower": {
|
||||
"message": "expected number but got undefined",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ioTsResolver > should return all the errors from ioTsResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"animal": {
|
||||
"message": "expected "snake" but got ["dog"]",
|
||||
"ref": undefined,
|
||||
"type": ""snake"",
|
||||
"types": {
|
||||
""bird"": "expected "bird" but got ["dog"]",
|
||||
""snake"": "expected "snake" but got ["dog"]",
|
||||
"number": "expected number but got ["dog"]",
|
||||
"string": "expected string but got ["dog"]",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "this id is very important but you passed: string(1)",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
"luckyNumbers": [
|
||||
,
|
||||
,
|
||||
{
|
||||
"message": "expected number but got "3"",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
],
|
||||
"vehicles": [
|
||||
,
|
||||
{
|
||||
"horsepower": {
|
||||
"message": "expected number but got undefined",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
57
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts
generated
vendored
Normal file
57
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
import { isLeft } from 'fp-ts/Either';
|
||||
import * as t from 'io-ts';
|
||||
import errorsToRecord from '../errorsToRecord';
|
||||
|
||||
const assertLeft = <T>(result: t.Validation<T>) => {
|
||||
expect(isLeft(result)).toBe(true);
|
||||
if (!isLeft(result)) {
|
||||
throw new Error(
|
||||
'panic! error is not of the "left" type, should be unreachable',
|
||||
);
|
||||
}
|
||||
return result.left;
|
||||
};
|
||||
|
||||
const FIRST_NAME_FIELD_PATH = 'firstName' as const;
|
||||
const FIRST_NAME_ERROR_SHAPE = {
|
||||
message: 'expected string but got undefined',
|
||||
type: 'string',
|
||||
};
|
||||
describe('errorsToRecord', () => {
|
||||
it('should return a correct error for an exact intersection type error object', () => {
|
||||
// a recommended pattern from https://github.com/gcanti/io-ts/blob/master/index.md#mixing-required-and-optional-props
|
||||
const schema = t.exact(
|
||||
t.intersection([
|
||||
t.type({
|
||||
[FIRST_NAME_FIELD_PATH]: t.string,
|
||||
}),
|
||||
t.partial({
|
||||
lastName: t.string,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const error = assertLeft(schema.decode({}));
|
||||
const record = errorsToRecord(false)(error);
|
||||
expect(record[FIRST_NAME_FIELD_PATH]).toMatchObject(FIRST_NAME_ERROR_SHAPE);
|
||||
});
|
||||
it('should return a correct error for a branded intersection', () => {
|
||||
interface Brand {
|
||||
readonly Brand: unique symbol;
|
||||
}
|
||||
const schema = t.brand(
|
||||
t.intersection([
|
||||
t.type({
|
||||
[FIRST_NAME_FIELD_PATH]: t.string,
|
||||
}),
|
||||
t.type({
|
||||
lastName: t.string,
|
||||
}),
|
||||
]),
|
||||
(_x): _x is t.Branded<typeof _x, Brand> => true,
|
||||
'Brand',
|
||||
);
|
||||
const error = assertLeft(schema.decode({}));
|
||||
const record = errorsToRecord(false)(error);
|
||||
expect(record[FIRST_NAME_FIELD_PATH]).toMatchObject(FIRST_NAME_ERROR_SHAPE);
|
||||
});
|
||||
});
|
||||
37
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts
generated
vendored
Normal file
37
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { ioTsResolver } from '..';
|
||||
import { fields, invalidData, schema, validData } from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('ioTsResolver', () => {
|
||||
it('should return values from ioTsResolver when validation pass', async () => {
|
||||
const validateSpy = vi.spyOn(schema, 'decode');
|
||||
|
||||
const result = ioTsResolver(schema)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(validateSpy).toHaveBeenCalled();
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
});
|
||||
|
||||
it('should return a single error from ioTsResolver when validation fails', () => {
|
||||
const result = ioTsResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from ioTsResolver when validation fails with `validateAllFieldCriteria` set to true', () => {
|
||||
const result = ioTsResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
18
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts
generated
vendored
Normal file
18
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as Either from 'fp-ts/Either';
|
||||
import { pipe } from 'fp-ts/function';
|
||||
|
||||
const arrayToPath = (paths: Either.Either<string, number>[]): string =>
|
||||
paths.reduce(
|
||||
(previous, path, index) =>
|
||||
pipe(
|
||||
path,
|
||||
Either.fold(
|
||||
(key) => `${index > 0 ? '.' : ''}${key}`,
|
||||
(key) => `[${key}]`,
|
||||
),
|
||||
(path) => `${previous}${path}`,
|
||||
),
|
||||
'',
|
||||
);
|
||||
|
||||
export default arrayToPath;
|
||||
141
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts
generated
vendored
Normal file
141
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts
generated
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
import * as Either from 'fp-ts/Either';
|
||||
import * as Option from 'fp-ts/Option';
|
||||
import * as ReadonlyArray from 'fp-ts/ReadonlyArray';
|
||||
import * as ReadonlyRecord from 'fp-ts/ReadonlyRecord';
|
||||
import * as SemiGroup from 'fp-ts/Semigroup';
|
||||
import { absurd, flow, identity, not, pipe } from 'fp-ts/function';
|
||||
import * as t from 'io-ts';
|
||||
import {
|
||||
ExactType,
|
||||
IntersectionType,
|
||||
RefinementType,
|
||||
TaggedUnionType,
|
||||
UnionType,
|
||||
ValidationError,
|
||||
} from 'io-ts';
|
||||
import arrayToPath from './arrayToPath';
|
||||
import { ErrorObject, FieldErrorWithPath } from './types';
|
||||
|
||||
const INSTANCE_TYPES_TO_FILTER = [
|
||||
TaggedUnionType,
|
||||
UnionType,
|
||||
IntersectionType,
|
||||
ExactType,
|
||||
RefinementType,
|
||||
];
|
||||
const formatErrorPath = (context: t.Context): string =>
|
||||
pipe(
|
||||
context,
|
||||
ReadonlyArray.filterMapWithIndex((index, contextEntry) => {
|
||||
const previousIndex = index - 1;
|
||||
const previousContextEntry =
|
||||
previousIndex === -1 ? undefined : context[previousIndex];
|
||||
const shouldBeFiltered =
|
||||
previousContextEntry === undefined ||
|
||||
INSTANCE_TYPES_TO_FILTER.some(
|
||||
(type) => previousContextEntry.type instanceof type,
|
||||
);
|
||||
|
||||
return shouldBeFiltered ? Option.none : Option.some(contextEntry);
|
||||
}),
|
||||
ReadonlyArray.map(({ key }) => key),
|
||||
ReadonlyArray.map((key) =>
|
||||
pipe(
|
||||
key,
|
||||
(k) => parseInt(k, 10),
|
||||
Either.fromPredicate(not<number>(Number.isNaN), () => key),
|
||||
),
|
||||
),
|
||||
ReadonlyArray.toArray,
|
||||
arrayToPath,
|
||||
);
|
||||
|
||||
const formatError = (e: t.ValidationError): FieldErrorWithPath => {
|
||||
const path = formatErrorPath(e.context);
|
||||
|
||||
const message = pipe(
|
||||
e.message,
|
||||
Either.fromNullable(e.context),
|
||||
Either.mapLeft(
|
||||
flow(
|
||||
ReadonlyArray.last,
|
||||
Option.map(
|
||||
(contextEntry) =>
|
||||
`expected ${contextEntry.type.name} but got ${JSON.stringify(
|
||||
contextEntry.actual,
|
||||
)}`,
|
||||
),
|
||||
Option.getOrElseW(() =>
|
||||
absurd<string>('Error context is missing name' as never),
|
||||
),
|
||||
),
|
||||
),
|
||||
Either.getOrElseW(identity),
|
||||
);
|
||||
|
||||
const type = pipe(
|
||||
e.context,
|
||||
ReadonlyArray.last,
|
||||
Option.map((contextEntry) => contextEntry.type.name),
|
||||
Option.getOrElse(() => 'unknown'),
|
||||
);
|
||||
|
||||
return { message, type, path };
|
||||
};
|
||||
|
||||
// this is almost the same function like Semigroup.getObjectSemigroup but reversed
|
||||
// in order to get the first error
|
||||
const getObjectSemigroup = <
|
||||
A extends Record<string, unknown> = never,
|
||||
>(): SemiGroup.Semigroup<A> => ({
|
||||
concat: (first, second) => Object.assign({}, second, first),
|
||||
});
|
||||
|
||||
const concatToSingleError = (
|
||||
errors: ReadonlyArray<FieldErrorWithPath>,
|
||||
): ErrorObject =>
|
||||
pipe(
|
||||
errors,
|
||||
ReadonlyArray.map((error) => ({
|
||||
[error.path]: {
|
||||
type: error.type,
|
||||
message: error.message,
|
||||
},
|
||||
})),
|
||||
(errors) => SemiGroup.fold(getObjectSemigroup<ErrorObject>())({}, errors),
|
||||
);
|
||||
|
||||
const appendSeveralErrors: SemiGroup.Semigroup<FieldErrorWithPath> = {
|
||||
concat: (a, b) => ({
|
||||
...b,
|
||||
types: { ...a.types, [a.type]: a.message, [b.type]: b.message },
|
||||
}),
|
||||
};
|
||||
|
||||
const concatToMultipleErrors = (
|
||||
errors: ReadonlyArray<FieldErrorWithPath>,
|
||||
): ErrorObject =>
|
||||
pipe(
|
||||
ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)(
|
||||
errors,
|
||||
(error) => [error.path, error],
|
||||
),
|
||||
ReadonlyRecord.map((errorWithPath) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { path, ...error } = errorWithPath;
|
||||
|
||||
return error;
|
||||
}),
|
||||
);
|
||||
|
||||
const errorsToRecord =
|
||||
(validateAllFieldCriteria: boolean) =>
|
||||
(validationErrors: ReadonlyArray<ValidationError>): ErrorObject => {
|
||||
const concat = validateAllFieldCriteria
|
||||
? concatToMultipleErrors
|
||||
: concatToSingleError;
|
||||
|
||||
return pipe(validationErrors, ReadonlyArray.map(formatError), concat);
|
||||
};
|
||||
|
||||
export default errorsToRecord;
|
||||
2
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/index.ts
generated
vendored
Normal file
2
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/index.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './io-ts';
|
||||
export * from './types';
|
||||
32
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/io-ts.ts
generated
vendored
Normal file
32
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/io-ts.ts
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import * as Either from 'fp-ts/Either';
|
||||
import { pipe } from 'fp-ts/function';
|
||||
import errorsToRecord from './errorsToRecord';
|
||||
import { Resolver } from './types';
|
||||
|
||||
export const ioTsResolver: Resolver = (codec) => (values, _context, options) =>
|
||||
pipe(
|
||||
values,
|
||||
codec.decode,
|
||||
Either.mapLeft(
|
||||
errorsToRecord(
|
||||
!options.shouldUseNativeValidation && options.criteriaMode === 'all',
|
||||
),
|
||||
),
|
||||
Either.mapLeft((errors) => toNestErrors(errors, options)),
|
||||
Either.fold(
|
||||
(errors) => ({
|
||||
values: {},
|
||||
errors,
|
||||
}),
|
||||
(values) => {
|
||||
options.shouldUseNativeValidation &&
|
||||
validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
values,
|
||||
errors: {},
|
||||
} as any;
|
||||
},
|
||||
),
|
||||
);
|
||||
18
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/types.ts
generated
vendored
Normal file
18
install/config-ui/node_modules/@hookform/resolvers/io-ts/src/types.ts
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as t from 'io-ts';
|
||||
import {
|
||||
FieldError,
|
||||
FieldValues,
|
||||
ResolverOptions,
|
||||
ResolverResult,
|
||||
} from 'react-hook-form';
|
||||
|
||||
export type Resolver = <T, TFieldValues extends FieldValues, TContext>(
|
||||
codec: t.Decoder<FieldValues, T>,
|
||||
) => (
|
||||
values: TFieldValues,
|
||||
_context: TContext | undefined,
|
||||
options: ResolverOptions<TFieldValues>,
|
||||
) => ResolverResult<TFieldValues>;
|
||||
|
||||
export type ErrorObject = Record<string, FieldError>;
|
||||
export type FieldErrorWithPath = FieldError & { path: string };
|
||||
Reference in New Issue
Block a user