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,3 @@
import * as Either from 'fp-ts/Either';
declare const arrayToPath: (paths: Either.Either<string, number>[]) => string;
export default arrayToPath;

View File

@@ -0,0 +1,4 @@
import { ValidationError } from 'io-ts';
import { ErrorObject } from './types';
declare const errorsToRecord: (validateAllFieldCriteria: boolean) => (validationErrors: ReadonlyArray<ValidationError>) => ErrorObject;
export default errorsToRecord;

View File

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

View File

@@ -0,0 +1,2 @@
import { Resolver } from './types';
export declare const ioTsResolver: Resolver;

2
node_modules/@hookform/resolvers/io-ts/dist/io-ts.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
var e=require("@hookform/resolvers"),n=require("fp-ts/Either"),t=require("fp-ts/function"),r=require("fp-ts/Option"),i=require("fp-ts/ReadonlyArray"),u=require("fp-ts/ReadonlyRecord"),o=require("fp-ts/Semigroup"),a=require("io-ts");function f(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}}),n.default=e,n}var c=/*#__PURE__*/f(n),p=/*#__PURE__*/f(r),s=/*#__PURE__*/f(i),l=/*#__PURE__*/f(u),d=/*#__PURE__*/f(o);function m(){return m=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)({}).hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},m.apply(null,arguments)}var y=function(e){return e.reduce(function(e,n,r){return t.pipe(n,c.fold(function(e){return(r>0?".":"")+e},function(e){return"["+e+"]"}),function(n){return""+e+n})},"")},v=["path"],g=[a.TaggedUnionType,a.UnionType,a.IntersectionType,a.ExactType,a.RefinementType],O=function(e){var n,r=t.pipe(n=e.context,s.filterMapWithIndex(function(e,t){var r=e-1,i=-1===r?void 0:n[r];return void 0===i||g.some(function(e){return i.type instanceof e})?p.none:p.some(t)}),s.map(function(e){return e.key}),s.map(function(e){return t.pipe(e,function(e){return parseInt(e,10)},c.fromPredicate(t.not(Number.isNaN),function(){return e}))}),s.toArray,y);return{message:t.pipe(e.message,c.fromNullable(e.context),c.mapLeft(t.flow(s.last,p.map(function(e){return"expected "+e.type.name+" but got "+JSON.stringify(e.actual)}),p.getOrElseW(function(){return t.absurd("Error context is missing name")}))),c.getOrElseW(t.identity)),type:t.pipe(e.context,s.last,p.map(function(e){return e.type.name}),p.getOrElse(function(){return"unknown"})),path:r}},b=function(e){return t.pipe(e,s.map(function(e){var n;return(n={})[e.path]={type:e.type,message:e.message},n}),function(e){return d.fold({concat:function(e,n){return Object.assign({},n,e)}})({},e)})},h={concat:function(e,n){var t;return m({},n,{types:m({},e.types,(t={},t[e.type]=e.message,t[n.type]=n.message,t))})}},x=function(e){return t.pipe(l.fromFoldableMap(h,s.Foldable)(e,function(e){return[e.path,e]}),l.map(function(e){return function(e,n){if(null==e)return{};var t={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(n.indexOf(r)>=0)continue;t[r]=e[r]}return t}(e,v)}))};exports.ioTsResolver=function(n){return function(r,i,u){return t.pipe(r,n.decode,c.mapLeft((o=!u.shouldUseNativeValidation&&"all"===u.criteriaMode,function(e){var n=o?x:b;return t.pipe(e,s.map(O),n)})),c.mapLeft(function(n){return e.toNestErrors(n,u)}),c.fold(function(e){return{values:{},errors:e}},function(n){return u.shouldUseNativeValidation&&e.validateFieldsNatively({},u),{values:n,errors:{}}}));var o}};
//# sourceMappingURL=io-ts.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
import{toNestErrors as n,validateFieldsNatively as t}from"@hookform/resolvers";import*as r from"fp-ts/Either";import{pipe as e,flow as o,absurd as u,identity as a,not as i}from"fp-ts/function";import*as f from"fp-ts/Option";import*as s from"fp-ts/ReadonlyArray";import*as c from"fp-ts/ReadonlyRecord";import*as p from"fp-ts/Semigroup";import{TaggedUnionType as m,UnionType as l,IntersectionType as d,ExactType as v,RefinementType as y}from"io-ts";function g(){return g=Object.assign?Object.assign.bind():function(n){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var e in r)({}).hasOwnProperty.call(r,e)&&(n[e]=r[e])}return n},g.apply(null,arguments)}var h=function(n){return n.reduce(function(n,t,o){return e(t,r.fold(function(n){return(o>0?".":"")+n},function(n){return"["+n+"]"}),function(t){return""+n+t})},"")},O=["path"],b=[m,l,d,v,y],x=function(n){var t,c=e(t=n.context,s.filterMapWithIndex(function(n,r){var e=n-1,o=-1===e?void 0:t[e];return void 0===o||b.some(function(n){return o.type instanceof n})?f.none:f.some(r)}),s.map(function(n){return n.key}),s.map(function(n){return e(n,function(n){return parseInt(n,10)},r.fromPredicate(i(Number.isNaN),function(){return n}))}),s.toArray,h);return{message:e(n.message,r.fromNullable(n.context),r.mapLeft(o(s.last,f.map(function(n){return"expected "+n.type.name+" but got "+JSON.stringify(n.actual)}),f.getOrElseW(function(){return u("Error context is missing name")}))),r.getOrElseW(a)),type:e(n.context,s.last,f.map(function(n){return n.type.name}),f.getOrElse(function(){return"unknown"})),path:c}},N=function(n){return e(n,s.map(function(n){var t;return(t={})[n.path]={type:n.type,message:n.message},t}),function(n){return p.fold({concat:function(n,t){return Object.assign({},t,n)}})({},n)})},E={concat:function(n,t){var r;return g({},t,{types:g({},n.types,(r={},r[n.type]=n.message,r[t.type]=t.message,r))})}},j=function(n){return e(c.fromFoldableMap(E,s.Foldable)(n,function(n){return[n.path,n]}),c.map(function(n){return function(n,t){if(null==n)return{};var r={};for(var e in n)if({}.hasOwnProperty.call(n,e)){if(t.indexOf(e)>=0)continue;r[e]=n[e]}return r}(n,O)}))},k=function(o){return function(u,a,i){return e(u,o.decode,r.mapLeft((f=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,function(n){var t=f?j:N;return e(n,s.map(x),t)})),r.mapLeft(function(t){return n(t,i)}),r.fold(function(n){return{values:{},errors:n}},function(n){return i.shouldUseNativeValidation&&t({},i),{values:n,errors:{}}}));var f}};export{k as ioTsResolver};
//# sourceMappingURL=io-ts.module.js.map

View File

@@ -0,0 +1,2 @@
import{toNestErrors as e,validateFieldsNatively as t}from"@hookform/resolvers";import*as r from"fp-ts/Either";import{pipe as o,flow as a,absurd as s,identity as n,not as p}from"fp-ts/function";import*as i from"fp-ts/Option";import*as m from"fp-ts/ReadonlyArray";import*as f from"fp-ts/ReadonlyRecord";import*as l from"fp-ts/Semigroup";import{TaggedUnionType as c,UnionType as u,IntersectionType as d,ExactType as y,RefinementType as g}from"io-ts";function v(){return v=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)({}).hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},v.apply(null,arguments)}const h=e=>e.reduce((e,t,a)=>o(t,r.fold(e=>`${a>0?".":""}${e}`,e=>`[${e}]`),t=>`${e}${t}`),""),O=["path"],b=[c,u,d,y,g],x=e=>{const t=o(f=e.context,m.filterMapWithIndex((e,t)=>{const r=e-1,o=-1===r?void 0:f[r];return void 0===o||b.some(e=>o.type instanceof e)?i.none:i.some(t)}),m.map(({key:e})=>e),m.map(e=>o(e,e=>parseInt(e,10),r.fromPredicate(p(Number.isNaN),()=>e))),m.toArray,h);var f;return{message:o(e.message,r.fromNullable(e.context),r.mapLeft(a(m.last,i.map(e=>`expected ${e.type.name} but got ${JSON.stringify(e.actual)}`),i.getOrElseW(()=>s("Error context is missing name")))),r.getOrElseW(n)),type:o(e.context,m.last,i.map(e=>e.type.name),i.getOrElse(()=>"unknown")),path:t}},N=e=>o(e,m.map(e=>({[e.path]:{type:e.type,message:e.message}})),e=>l.fold({concat:(e,t)=>Object.assign({},t,e)})({},e)),$={concat:(e,t)=>v({},t,{types:v({},e.types,{[e.type]:e.message,[t.type]:t.message})})},E=e=>o(f.fromFoldableMap($,m.Foldable)(e,e=>[e.path,e]),f.map(e=>function(e,t){if(null==e)return{};var r={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(t.indexOf(o)>=0)continue;r[o]=e[o]}return r}(e,O))),j=a=>(s,n,p)=>{return o(s,a.decode,r.mapLeft((i=!p.shouldUseNativeValidation&&"all"===p.criteriaMode,e=>{const t=i?E:N;return o(e,m.map(x),t)})),r.mapLeft(t=>e(t,p)),r.fold(e=>({values:{},errors:e}),e=>(p.shouldUseNativeValidation&&t({},p),{values:e,errors:{}})));var i};export{j as ioTsResolver};
//# sourceMappingURL=io-ts.modern.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
import{toNestErrors as n,validateFieldsNatively as t}from"@hookform/resolvers";import*as r from"fp-ts/Either";import{pipe as e,flow as o,absurd as u,identity as a,not as i}from"fp-ts/function";import*as f from"fp-ts/Option";import*as s from"fp-ts/ReadonlyArray";import*as c from"fp-ts/ReadonlyRecord";import*as p from"fp-ts/Semigroup";import{TaggedUnionType as m,UnionType as l,IntersectionType as d,ExactType as v,RefinementType as y}from"io-ts";function g(){return g=Object.assign?Object.assign.bind():function(n){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var e in r)({}).hasOwnProperty.call(r,e)&&(n[e]=r[e])}return n},g.apply(null,arguments)}var h=function(n){return n.reduce(function(n,t,o){return e(t,r.fold(function(n){return(o>0?".":"")+n},function(n){return"["+n+"]"}),function(t){return""+n+t})},"")},O=["path"],b=[m,l,d,v,y],x=function(n){var t,c=e(t=n.context,s.filterMapWithIndex(function(n,r){var e=n-1,o=-1===e?void 0:t[e];return void 0===o||b.some(function(n){return o.type instanceof n})?f.none:f.some(r)}),s.map(function(n){return n.key}),s.map(function(n){return e(n,function(n){return parseInt(n,10)},r.fromPredicate(i(Number.isNaN),function(){return n}))}),s.toArray,h);return{message:e(n.message,r.fromNullable(n.context),r.mapLeft(o(s.last,f.map(function(n){return"expected "+n.type.name+" but got "+JSON.stringify(n.actual)}),f.getOrElseW(function(){return u("Error context is missing name")}))),r.getOrElseW(a)),type:e(n.context,s.last,f.map(function(n){return n.type.name}),f.getOrElse(function(){return"unknown"})),path:c}},N=function(n){return e(n,s.map(function(n){var t;return(t={})[n.path]={type:n.type,message:n.message},t}),function(n){return p.fold({concat:function(n,t){return Object.assign({},t,n)}})({},n)})},E={concat:function(n,t){var r;return g({},t,{types:g({},n.types,(r={},r[n.type]=n.message,r[t.type]=t.message,r))})}},j=function(n){return e(c.fromFoldableMap(E,s.Foldable)(n,function(n){return[n.path,n]}),c.map(function(n){return function(n,t){if(null==n)return{};var r={};for(var e in n)if({}.hasOwnProperty.call(n,e)){if(t.indexOf(e)>=0)continue;r[e]=n[e]}return r}(n,O)}))},k=function(o){return function(u,a,i){return e(u,o.decode,r.mapLeft((f=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,function(n){var t=f?j:N;return e(n,s.map(x),t)})),r.mapLeft(function(t){return n(t,i)}),r.fold(function(n){return{values:{},errors:n}},function(n){return i.shouldUseNativeValidation&&t({},i),{values:n,errors:{}}}));var f}};export{k as ioTsResolver};
//# sourceMappingURL=io-ts.module.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("@hookform/resolvers"),require("fp-ts/Either"),require("fp-ts/function"),require("fp-ts/Option"),require("fp-ts/ReadonlyArray"),require("fp-ts/ReadonlyRecord"),require("fp-ts/Semigroup"),require("io-ts")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","fp-ts/Either","fp-ts/function","fp-ts/Option","fp-ts/ReadonlyArray","fp-ts/ReadonlyRecord","fp-ts/Semigroup","io-ts"],n):n((e||self).hookformResolversIoTs={},e.hookformResolvers,e.Either,e._function,e.Option,e.ReadonlyArray,e.ReadonlyRecord,e.Semigroup,e.ioTs)}(this,function(e,n,t,r,o,i,u,a,f){function s(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}}),n.default=e,n}var p=/*#__PURE__*/s(t),c=/*#__PURE__*/s(o),l=/*#__PURE__*/s(i),d=/*#__PURE__*/s(u),y=/*#__PURE__*/s(a);function m(){return m=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)({}).hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},m.apply(null,arguments)}var v=function(e){return e.reduce(function(e,n,t){return r.pipe(n,p.fold(function(e){return(t>0?".":"")+e},function(e){return"["+e+"]"}),function(n){return""+e+n})},"")},g=["path"],h=[f.TaggedUnionType,f.UnionType,f.IntersectionType,f.ExactType,f.RefinementType],b=function(e){var n,t=r.pipe(n=e.context,l.filterMapWithIndex(function(e,t){var r=e-1,o=-1===r?void 0:n[r];return void 0===o||h.some(function(e){return o.type instanceof e})?c.none:c.some(t)}),l.map(function(e){return e.key}),l.map(function(e){return r.pipe(e,function(e){return parseInt(e,10)},p.fromPredicate(r.not(Number.isNaN),function(){return e}))}),l.toArray,v);return{message:r.pipe(e.message,p.fromNullable(e.context),p.mapLeft(r.flow(l.last,c.map(function(e){return"expected "+e.type.name+" but got "+JSON.stringify(e.actual)}),c.getOrElseW(function(){return r.absurd("Error context is missing name")}))),p.getOrElseW(r.identity)),type:r.pipe(e.context,l.last,c.map(function(e){return e.type.name}),c.getOrElse(function(){return"unknown"})),path:t}},O=function(e){return r.pipe(e,l.map(function(e){var n;return(n={})[e.path]={type:e.type,message:e.message},n}),function(e){return y.fold({concat:function(e,n){return Object.assign({},n,e)}})({},e)})},R={concat:function(e,n){var t;return m({},n,{types:m({},e.types,(t={},t[e.type]=e.message,t[n.type]=n.message,t))})}},x=function(e){return r.pipe(d.fromFoldableMap(R,l.Foldable)(e,function(e){return[e.path,e]}),d.map(function(e){return function(e,n){if(null==e)return{};var t={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(n.indexOf(r)>=0)continue;t[r]=e[r]}return t}(e,g)}))};e.ioTsResolver=function(e){return function(t,o,i){return r.pipe(t,e.decode,p.mapLeft((u=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,function(e){var n=u?x:O;return r.pipe(e,l.map(b),n)})),p.mapLeft(function(e){return n.toNestErrors(e,i)}),p.fold(function(e){return{values:{},errors:e}},function(e){return i.shouldUseNativeValidation&&n.validateFieldsNatively({},i),{values:e,errors:{}}}));var u}}});
//# sourceMappingURL=io-ts.umd.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
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;
};

19
node_modules/@hookform/resolvers/io-ts/package.json generated vendored Normal file
View 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"
}
}

View 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('');
});

View 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();
});

View 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',
},
};

View 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": {},
}
`;

View 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);
});
});

View 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();
});
});

View 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;

View 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
node_modules/@hookform/resolvers/io-ts/src/index.ts generated vendored Normal file
View File

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

32
node_modules/@hookform/resolvers/io-ts/src/io-ts.ts generated vendored Normal file
View 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
node_modules/@hookform/resolvers/io-ts/src/types.ts generated vendored Normal file
View 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 };