build revisions and layout updates for toast

This commit is contained in:
makearmy 2025-09-26 14:31:18 -04:00
parent b341a3675e
commit 39235193e6
1116 changed files with 130517 additions and 12 deletions

1
node_modules/@hookform/resolvers/zod/dist/index.d.ts generated vendored Normal file
View file

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

49
node_modules/@hookform/resolvers/zod/dist/zod.d.ts generated vendored Normal file
View file

@ -0,0 +1,49 @@
import { FieldValues, Resolver } from 'react-hook-form';
import * as z3 from 'zod/v3';
import * as z4 from 'zod/v4/core';
type RawResolverOptions = {
mode?: 'async' | 'sync';
raw: true;
};
type NonRawResolverOptions = {
mode?: 'async' | 'sync';
raw?: false;
};
interface Zod3Type<O = unknown, I = unknown> {
_output: O;
_input: I;
_def: {
typeName: string;
};
}
type IsUnresolved<T> = PropertyKey extends keyof T ? true : false;
type UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true ? Fallback : T;
type FallbackIssue = {
code: string;
message: string;
path: (string | number)[];
};
type Zod3ParseParams = UnresolvedFallback<z3.ParseParams, {
path?: (string | number)[];
errorMap?: (iss: FallbackIssue, ctx: {
defaultError: string;
data: any;
}) => {
message: string;
};
async?: boolean;
}>;
type Zod4ParseParams = UnresolvedFallback<z4.ParseContext<z4.$ZodIssue>, {
readonly error?: (iss: FallbackIssue) => null | undefined | string | {
message: string;
};
readonly reportInput?: boolean;
readonly jitless?: boolean;
}>;
export declare function zodResolver<Input extends FieldValues, Context, Output>(schema: Zod3Type<Output, Input>, schemaOptions?: Zod3ParseParams, resolverOptions?: NonRawResolverOptions): Resolver<Input, Context, Output>;
export declare function zodResolver<Input extends FieldValues, Context, Output>(schema: Zod3Type<Output, Input>, schemaOptions: Zod3ParseParams | undefined, resolverOptions: RawResolverOptions): Resolver<Input, Context, Input>;
export declare function zodResolver<Input extends FieldValues, Context, Output, T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>>(schema: T, schemaOptions?: Zod4ParseParams, // already partial
resolverOptions?: NonRawResolverOptions): Resolver<z4.input<T>, Context, z4.output<T>>;
export declare function zodResolver<Input extends FieldValues, Context, Output, T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>>(schema: z4.$ZodType<Output, Input>, schemaOptions: Zod4ParseParams | undefined, // already partial
resolverOptions: RawResolverOptions): Resolver<z4.input<T>, Context, z4.input<T>>;
export {};

2
node_modules/@hookform/resolvers/zod/dist/zod.js generated vendored Normal file
View file

@ -0,0 +1,2 @@
var r=require("@hookform/resolvers"),e=require("react-hook-form");function n(r){if(r&&r.__esModule)return r;var e=Object.create(null);return r&&Object.keys(r).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:function(){return r[n]}})}}),e.default=r,e}var o=/*#__PURE__*/n(require("zod/v4/core"));function t(r,e){try{var n=r()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function s(r,n){for(var o={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!o[a])if("unionErrors"in t){var u=t.unionErrors[0].errors[0];o[a]={message:u.message,type:u.code}}else o[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),n){var c=o[a].types,f=c&&c[t.code];o[a]=e.appendErrors(a,n,o,s,f?[].concat(f,t.message):t.message)}r.shift()}return o}function i(r,n){for(var o={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!o[a])if("invalid_union"===t.code&&t.errors.length>0){var u=t.errors[0][0];o[a]={message:u.message,type:u.code}}else o[a]={message:i,type:s};if("invalid_union"===t.code&&t.errors.forEach(function(e){return e.forEach(function(e){return r.push(e)})}),n){var c=o[a].types,f=c&&c[t.code];o[a]=e.appendErrors(a,n,o,s,f?[].concat(f,t.message):t.message)}r.shift()}return o}exports.zodResolver=function(e,n,a){if(void 0===a&&(a={}),function(r){return"_def"in r&&"object"==typeof r._def&&"typeName"in r._def}(e))return function(o,i,u){try{return Promise.resolve(t(function(){return Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](o,n)).then(function(e){return u.shouldUseNativeValidation&&r.validateFieldsNatively({},u),{errors:{},values:a.raw?Object.assign({},o):e}})},function(e){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(e))return{values:{},errors:r.toNestErrors(s(e.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw e}))}catch(r){return Promise.reject(r)}};if(function(r){return"_zod"in r&&"object"==typeof r._zod}(e))return function(s,u,c){try{return Promise.resolve(t(function(){return Promise.resolve(("sync"===a.mode?o.parse:o.parseAsync)(e,s,n)).then(function(e){return c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{errors:{},values:a.raw?Object.assign({},s):e}})},function(e){if(function(r){return r instanceof o.$ZodError}(e))return{values:{},errors:r.toNestErrors(i(e.issues,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw e}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")};
//# sourceMappingURL=zod.js.map

1
node_modules/@hookform/resolvers/zod/dist/zod.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2
node_modules/@hookform/resolvers/zod/dist/zod.mjs generated vendored Normal file
View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as o}from"react-hook-form";import*as n from"zod/v4/core";function t(r,e){try{var o=r()}catch(r){return e(r)}return o&&o.then?o.then(void 0,e):o}function s(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("unionErrors"in t){var u=t.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=o(a,e,n,s,f?[].concat(f,t.message):t.message)}r.shift()}return n}function i(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("invalid_union"===t.code&&t.errors.length>0){var u=t.errors[0][0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:s};if("invalid_union"===t.code&&t.errors.forEach(function(e){return e.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=o(a,e,n,s,f?[].concat(f,t.message):t.message)}r.shift()}return n}function a(o,a,u){if(void 0===u&&(u={}),function(r){return"_def"in r&&"object"==typeof r._def&&"typeName"in r._def}(o))return function(n,i,c){try{return Promise.resolve(t(function(){return Promise.resolve(o["sync"===u.mode?"parse":"parseAsync"](n,a)).then(function(e){return c.shouldUseNativeValidation&&r({},c),{errors:{},values:u.raw?Object.assign({},n):e}})},function(r){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(r))return{values:{},errors:e(s(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};if(function(r){return"_zod"in r&&"object"==typeof r._zod}(o))return function(s,c,f){try{return Promise.resolve(t(function(){return Promise.resolve(("sync"===u.mode?n.parse:n.parseAsync)(o,s,a)).then(function(e){return f.shouldUseNativeValidation&&r({},f),{errors:{},values:u.raw?Object.assign({},s):e}})},function(r){if(function(r){return r instanceof n.$ZodError}(r))return{values:{},errors:e(i(r.issues,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}export{a as zodResolver};
//# sourceMappingURL=zod.module.js.map

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as e,toNestErrors as r}from"@hookform/resolvers";import{appendErrors as o}from"react-hook-form";import*as s from"zod/v4/core";function t(e,r){const s={};for(;e.length;){const t=e[0],{code:n,message:a,path:i}=t,c=i.join(".");if(!s[c])if("unionErrors"in t){const e=t.unionErrors[0].errors[0];s[c]={message:e.message,type:e.code}}else s[c]={message:a,type:n};if("unionErrors"in t&&t.unionErrors.forEach(r=>r.errors.forEach(r=>e.push(r))),r){const e=s[c].types,a=e&&e[t.code];s[c]=o(c,r,s,n,a?[].concat(a,t.message):t.message)}e.shift()}return s}function n(e,r){const s={};for(;e.length;){const t=e[0],{code:n,message:a,path:i}=t,c=i.join(".");if(!s[c])if("invalid_union"===t.code&&t.errors.length>0){const e=t.errors[0][0];s[c]={message:e.message,type:e.code}}else s[c]={message:a,type:n};if("invalid_union"===t.code&&t.errors.forEach(r=>r.forEach(r=>e.push(r))),r){const e=s[c].types,a=e&&e[t.code];s[c]=o(c,r,s,n,a?[].concat(a,t.message):t.message)}e.shift()}return s}function a(o,a,i={}){if((e=>"_def"in e&&"object"==typeof e._def&&"typeName"in e._def)(o))return async(s,n,c)=>{try{const r=await o["sync"===i.mode?"parse":"parseAsync"](s,a);return c.shouldUseNativeValidation&&e({},c),{errors:{},values:i.raw?Object.assign({},s):r}}catch(e){if((e=>Array.isArray(null==e?void 0:e.issues))(e))return{values:{},errors:r(t(e.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw e}};if((e=>"_zod"in e&&"object"==typeof e._zod)(o))return async(t,c,d)=>{try{const r="sync"===i.mode?s.parse:s.parseAsync,n=await r(o,t,a);return d.shouldUseNativeValidation&&e({},d),{errors:{},values:i.raw?Object.assign({},t):n}}catch(e){if((e=>e instanceof s.$ZodError)(e))return{values:{},errors:r(n(e.issues,!d.shouldUseNativeValidation&&"all"===d.criteriaMode),d)};throw e}};throw new Error("Invalid input: not a Zod schema")}export{a as zodResolver};
//# sourceMappingURL=zod.modern.mjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import{appendErrors as o}from"react-hook-form";import*as n from"zod/v4/core";function t(r,e){try{var o=r()}catch(r){return e(r)}return o&&o.then?o.then(void 0,e):o}function s(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("unionErrors"in t){var u=t.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=o(a,e,n,s,f?[].concat(f,t.message):t.message)}r.shift()}return n}function i(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("invalid_union"===t.code&&t.errors.length>0){var u=t.errors[0][0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:s};if("invalid_union"===t.code&&t.errors.forEach(function(e){return e.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=o(a,e,n,s,f?[].concat(f,t.message):t.message)}r.shift()}return n}function a(o,a,u){if(void 0===u&&(u={}),function(r){return"_def"in r&&"object"==typeof r._def&&"typeName"in r._def}(o))return function(n,i,c){try{return Promise.resolve(t(function(){return Promise.resolve(o["sync"===u.mode?"parse":"parseAsync"](n,a)).then(function(e){return c.shouldUseNativeValidation&&r({},c),{errors:{},values:u.raw?Object.assign({},n):e}})},function(r){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(r))return{values:{},errors:e(s(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};if(function(r){return"_zod"in r&&"object"==typeof r._zod}(o))return function(s,c,f){try{return Promise.resolve(t(function(){return Promise.resolve(("sync"===u.mode?n.parse:n.parseAsync)(o,s,a)).then(function(e){return f.shouldUseNativeValidation&&r({},f),{errors:{},values:u.raw?Object.assign({},s):e}})},function(r){if(function(r){return r instanceof n.$ZodError}(r))return{values:{},errors:e(i(r.issues,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}export{a as zodResolver};
//# sourceMappingURL=zod.module.js.map

File diff suppressed because one or more lines are too long

2
node_modules/@hookform/resolvers/zod/dist/zod.umd.js generated vendored Normal file
View file

@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("react-hook-form"),require("zod/v4/core")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","react-hook-form","zod/v4/core"],r):r((e||self).hookformResolversZod={},e.hookformResolvers,e.ReactHookForm,e.z4)}(this,function(e,r,o,n){function t(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(r,o,n.get?n:{enumerable:!0,get:function(){return e[o]}})}}),r.default=e,r}var s=/*#__PURE__*/t(n);function i(e,r){try{var o=e()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}function a(e,r){for(var n={};e.length;){var t=e[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("unionErrors"in t){var u=t.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(r){return r.errors.forEach(function(r){return e.push(r)})}),r){var c=n[a].types,f=c&&c[t.code];n[a]=o.appendErrors(a,r,n,s,f?[].concat(f,t.message):t.message)}e.shift()}return n}function u(e,r){for(var n={};e.length;){var t=e[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("invalid_union"===t.code&&t.errors.length>0){var u=t.errors[0][0];n[a]={message:u.message,type:u.code}}else n[a]={message:i,type:s};if("invalid_union"===t.code&&t.errors.forEach(function(r){return r.forEach(function(r){return e.push(r)})}),r){var c=n[a].types,f=c&&c[t.code];n[a]=o.appendErrors(a,r,n,s,f?[].concat(f,t.message):t.message)}e.shift()}return n}e.zodResolver=function(e,o,n){if(void 0===n&&(n={}),function(e){return"_def"in e&&"object"==typeof e._def&&"typeName"in e._def}(e))return function(t,s,u){try{return Promise.resolve(i(function(){return Promise.resolve(e["sync"===n.mode?"parse":"parseAsync"](t,o)).then(function(e){return u.shouldUseNativeValidation&&r.validateFieldsNatively({},u),{errors:{},values:n.raw?Object.assign({},t):e}})},function(e){if(function(e){return Array.isArray(null==e?void 0:e.issues)}(e))return{values:{},errors:r.toNestErrors(a(e.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw e}))}catch(e){return Promise.reject(e)}};if(function(e){return"_zod"in e&&"object"==typeof e._zod}(e))return function(t,a,c){try{return Promise.resolve(i(function(){return Promise.resolve(("sync"===n.mode?s.parse:s.parseAsync)(e,t,o)).then(function(e){return c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{errors:{},values:n.raw?Object.assign({},t):e}})},function(e){if(function(e){return e instanceof s.$ZodError}(e))return{values:{},errors:r.toNestErrors(u(e.issues,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw e}))}catch(e){return Promise.reject(e)}};throw new Error("Invalid input: not a Zod schema")}});
//# sourceMappingURL=zod.umd.js.map

File diff suppressed because one or more lines are too long

18
node_modules/@hookform/resolvers/zod/package.json generated vendored Normal file
View file

@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/zod",
"amdName": "hookformResolversZod",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: zod",
"main": "dist/zod.js",
"module": "dist/zod.module.js",
"umd:main": "dist/zod.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",
"zod": "^3.25.0 || ^4.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 { z } from 'zod/v3';
import { zodResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = z.object({
username: z.string().nonempty({ message: USERNAME_REQUIRED_MESSAGE }),
password: z.string().nonempty({ message: PASSWORD_REQUIRED_MESSAGE }),
});
type FormData = z.infer<typeof schema>;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: zodResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Zod", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(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,48 @@
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 { z } from 'zod/v3';
import { zodResolver } from '..';
const schema = z.object({
username: z.string().nonempty({ message: 'username field is required' }),
password: z.string().nonempty({ message: 'password field is required' }),
});
function TestComponent({
onSubmit,
}: { onSubmit: (data: z.infer<typeof schema>) => void }) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(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 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();
});

View file

@ -0,0 +1,88 @@
import { Field, InternalFieldName } from 'react-hook-form';
import { z } from 'zod/v3';
export const schema = z
.object({
username: z.string().regex(/^\w+$/).min(3).max(30),
password: z
.string()
.regex(new RegExp('.*[A-Z].*'), 'One uppercase character')
.regex(new RegExp('.*[a-z].*'), 'One lowercase character')
.regex(new RegExp('.*\\d.*'), 'One number')
.regex(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8, 'Must be at least 8 characters in length'),
repeatPassword: z.string(),
accessToken: z.union([z.string(), z.number()]),
birthYear: z.number().min(1900).max(2013).optional(),
email: z.string().email().optional(),
tags: z.array(z.string()),
enabled: z.boolean(),
url: z.string().url('Custom error url').or(z.literal('')),
like: z
.array(
z.object({
id: z.number(),
name: z.string().length(4),
}),
)
.optional(),
dateStr: z
.string()
.transform((value) => new Date(value))
.refine((value) => !isNaN(value.getTime()), {
message: 'Invalid date',
}),
})
.refine((obj) => obj.password === obj.repeatPassword, {
message: 'Passwords do not match',
path: ['confirm'],
});
export const validData = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: '2020-01-01',
} satisfies z.input<typeof schema>;
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
} as unknown as z.input<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,112 @@
import { Field, InternalFieldName } from 'react-hook-form';
import { z } from 'zod/v4-mini';
export const schema = z
.object({
username: z
.string()
.check(z.regex(/^\w+$/), z.minLength(3), z.maxLength(30)),
password: z
.string()
.check(
z.regex(new RegExp('.*[A-Z].*'), 'One uppercase character'),
z.regex(new RegExp('.*[a-z].*'), 'One lowercase character'),
z.regex(new RegExp('.*\\d.*'), 'One number'),
z.regex(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
),
z.minLength(8, 'Must be at least 8 characters in length'),
),
repeatPassword: z.string(),
accessToken: z.union([z.string(), z.number()]),
birthYear: z.optional(z.number().check(z.minimum(1900), z.maximum(2013))),
email: z.optional(z.email()),
tags: z.array(z.string()),
enabled: z.boolean(),
url: z.union([z.url('Custom error url'), z.literal('')]),
like: z.optional(
z.array(
z.object({
id: z.number(),
name: z.string().check(z.length(4)),
}),
),
),
dateStr: z
.pipe(
z.string(),
z.transform((value) => new Date(value)),
)
.check(
z.refine((value) => !isNaN(value.getTime()), {
message: 'Invalid date',
}),
),
auth: z.discriminatedUnion('type', [
z.object({
type: z.literal('registered'),
passwordHash: z.string(),
}),
z.object({
type: z.literal('guest'),
}),
]),
})
.check(
z.refine((obj) => obj.password === obj.repeatPassword, {
message: 'Passwords do not match',
path: ['confirm'],
}),
);
export const validData = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: '2020-01-01',
auth: {
type: 'registered',
passwordHash: 'hash',
},
} satisfies z.input<typeof schema>;
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
auth: { type: 'invalid' },
} as unknown as z.input<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,89 @@
import { Field, InternalFieldName } from 'react-hook-form';
import { z } from 'zod/v4';
export const schema = z
.object({
username: z.string().regex(/^\w+$/).min(3).max(30),
password: z
.string()
.regex(new RegExp('.*[A-Z].*'), 'One uppercase character')
.regex(new RegExp('.*[a-z].*'), 'One lowercase character')
.regex(new RegExp('.*\\d.*'), 'One number')
.regex(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8, 'Must be at least 8 characters in length'),
repeatPassword: z.string(),
accessToken: z.union([z.string(), z.number()]),
birthYear: z.number().min(1900).max(2013).optional(),
email: z.string().email().optional(),
tags: z.array(z.string()),
enabled: z.boolean(),
url: z.string().url('Custom error url').or(z.literal('')),
like: z
.array(
z.object({
id: z.number(),
name: z.string().length(4),
}),
)
.optional(),
dateStr: z
.string()
.transform((value) => new Date(value))
.refine((value) => !isNaN(value.getTime()), {
message: 'Invalid date',
}),
})
.refine((obj) => obj.password === obj.repeatPassword, {
message: 'Passwords do not match',
path: ['confirm'],
});
export const validData = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: '2020-01-01',
} satisfies z.input<typeof schema>;
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
} as unknown as z.input<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,430 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`zodResolver > should return a single error from zodResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"birthYear": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
},
"dateStr": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"email": {
"message": "Invalid email",
"ref": {
"name": "email",
},
"type": "invalid_string",
},
"enabled": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"like": [
{
"id": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
},
"name": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "invalid_string",
},
"repeatPassword": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"tags": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"url": {
"message": "Custom error url",
"ref": undefined,
"type": "invalid_string",
},
"username": {
"message": "Required",
"ref": {
"name": "username",
},
"type": "invalid_type",
},
},
"values": {},
}
`;
exports[`zodResolver > should return a single error from zodResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"birthYear": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
},
"dateStr": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"email": {
"message": "Invalid email",
"ref": {
"name": "email",
},
"type": "invalid_string",
},
"enabled": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"like": [
{
"id": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
},
"name": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "invalid_string",
},
"repeatPassword": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"tags": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
},
"url": {
"message": "Custom error url",
"ref": undefined,
"type": "invalid_string",
},
"username": {
"message": "Required",
"ref": {
"name": "username",
},
"type": "invalid_type",
},
},
"values": {},
}
`;
exports[`zodResolver > should return all the errors from zodResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"accessToken": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": [
"Required",
"Required",
],
"invalid_union": "Invalid input",
},
},
"birthYear": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Expected number, received string",
},
},
"dateStr": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"email": {
"message": "Invalid email",
"ref": {
"name": "email",
},
"type": "invalid_string",
"types": {
"invalid_string": "Invalid email",
},
},
"enabled": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"like": [
{
"id": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Expected number, received string",
},
},
"name": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "invalid_string",
"types": {
"invalid_string": [
"One uppercase character",
"One lowercase character",
"One number",
],
"too_small": "Must be at least 8 characters in length",
},
},
"repeatPassword": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"tags": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"url": {
"message": "Custom error url",
"ref": undefined,
"type": "invalid_string",
"types": {
"invalid_string": "Custom error url",
},
},
"username": {
"message": "Required",
"ref": {
"name": "username",
},
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
},
"values": {},
}
`;
exports[`zodResolver > should return all the errors from zodResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"accessToken": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": [
"Required",
"Required",
],
"invalid_union": "Invalid input",
},
},
"birthYear": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Expected number, received string",
},
},
"dateStr": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"email": {
"message": "Invalid email",
"ref": {
"name": "email",
},
"type": "invalid_string",
"types": {
"invalid_string": "Invalid email",
},
},
"enabled": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"like": [
{
"id": {
"message": "Expected number, received string",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Expected number, received string",
},
},
"name": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
},
],
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "invalid_string",
"types": {
"invalid_string": [
"One uppercase character",
"One lowercase character",
"One number",
],
"too_small": "Must be at least 8 characters in length",
},
},
"repeatPassword": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"tags": {
"message": "Required",
"ref": undefined,
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
"url": {
"message": "Custom error url",
"ref": undefined,
"type": "invalid_string",
"types": {
"invalid_string": "Custom error url",
},
},
"username": {
"message": "Required",
"ref": {
"name": "username",
},
"type": "invalid_type",
"types": {
"invalid_type": "Required",
},
},
},
"values": {},
}
`;
exports[`zodResolver > should return parsed values from zodResolver with \`mode: sync\` when validation pass 1`] = `
{
"errors": {},
"values": {
"accessToken": "accessToken",
"birthYear": 2000,
"dateStr": 2020-01-01T00:00:00.000Z,
"email": "john@doe.com",
"enabled": true,
"like": [
{
"id": 1,
"name": "name",
},
],
"password": "Password123_",
"repeatPassword": "Password123_",
"tags": [
"tag1",
"tag2",
],
"url": "https://react-hook-form.com/",
"username": "Doe",
},
}
`;

View file

@ -0,0 +1,178 @@
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
import { z } from 'zod/v3';
import { zodResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data-v3';
const shouldUseNativeValidation = false;
describe('zodResolver', () => {
it('should return values from zodResolver when validation pass & raw=true', async () => {
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
const parseSpy = vi.spyOn(schema, 'parse');
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result.errors).toEqual({});
expect(result).toMatchSnapshot();
});
it('should return a single error from zodResolver when validation fails', async () => {
const result = await zodResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
const parseSpy = vi.spyOn(schema, 'parse');
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await zodResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await zodResolver(schema, undefined, { mode: 'sync' })(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should throw any error unrelated to Zod', async () => {
const schemaWithCustomError = schema.refine(() => {
throw Error('custom error');
});
const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
await expect(promise).rejects.toThrow('custom error');
});
it('should enforce parse params type signature', async () => {
const resolver = zodResolver(schema, {
async: true,
path: ['asdf', 1234],
errorMap(iss, ctx) {
iss.path;
iss.code;
iss.path;
ctx.data;
ctx.defaultError;
return { message: 'asdf' };
},
});
resolver;
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a zod schema', () => {
const resolver = zodResolver(z.object({ id: z.number() }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a zod schema using a transform', () => {
const resolver = zodResolver(
z.object({ id: z.number().transform((val) => String(val)) }),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();
});
it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
const schema = z.object({ id: z.number() }).transform(({ id }) => {
return { id: String(id) };
});
const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
schema,
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, any, { id: string }>
>();
});
it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
const schema = z.object({ id: z.number() });
const form = useForm({
resolver: zodResolver(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 Zod schema with a transform for the handleSubmit function in useForm', () => {
const schema = z.object({ id: z.number().transform((val) => String(val)) });
const form = useForm({
resolver: zodResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

View file

@ -0,0 +1,182 @@
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
import { z } from 'zod/v4-mini';
import { zodResolver } from '..';
import {
fields,
invalidData,
schema,
validData,
} from './__fixtures__/data-v4-mini';
const shouldUseNativeValidation = false;
describe('zodResolver', () => {
it('should return values from zodResolver when validation pass & raw=true', async () => {
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
result;
expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
expectTypeOf(result.values);
});
it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
const parseSpy = vi.spyOn(schema, 'parse');
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result.errors).toEqual({});
expect(result).toMatchSnapshot();
});
it('should return a single error from zodResolver when validation fails', async () => {
const result = await zodResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
const parseSpy = vi.spyOn(schema, 'parse');
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await zodResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await zodResolver(schema, undefined, { mode: 'sync' })(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should throw any error unrelated to Zod', async () => {
const schemaWithCustomError = schema.check(
z.refine(() => {
throw Error('custom error');
}),
);
const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
await expect(promise).rejects.toThrow('custom error');
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a zod schema', () => {
const resolver = zodResolver(z.object({ id: z.number() }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a zod schema using a transform', () => {
const resolver = zodResolver(
z.object({
id: z.pipe(
z.number(),
z.transform((val) => String(val)),
),
}),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();
});
it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
const schema = z.pipe(
z.object({ id: z.number() }),
z.transform(({ id }) => {
return { id: String(id) };
}),
);
const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
schema,
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, any, { id: string }>
>();
});
it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
const schema = z.object({ id: z.number() });
const form = useForm({
resolver: zodResolver(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 Zod schema with a transform for the handleSubmit function in useForm', () => {
const schema = z.object({
id: z.pipe(
z.number(),
z.transform((val) => String(val)),
),
});
const form = useForm({
resolver: zodResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

View file

@ -0,0 +1,176 @@
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { zodResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data-v4';
const shouldUseNativeValidation = false;
describe('zodResolver', () => {
it('should return values from zodResolver when validation pass & raw=true', async () => {
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
const parseSpy = vi.spyOn(schema, 'parse');
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result.errors).toEqual({});
expect(result).toMatchSnapshot();
});
it('should return a single error from zodResolver when validation fails', async () => {
const result = await zodResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
const parseSpy = vi.spyOn(schema, 'parse');
const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await zodResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await zodResolver(schema, undefined, { mode: 'sync' })(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should throw any error unrelated to Zod', async () => {
const schemaWithCustomError = schema.refine(() => {
throw Error('custom error');
});
const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
await expect(promise).rejects.toThrow('custom error');
});
it('should enforce parse params type signature', async () => {
const resolver = zodResolver(schema, {
jitless: true,
reportInput: true,
error(iss) {
iss.path;
iss.code;
iss.path;
return { message: 'asdf' };
},
});
resolver;
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a zod schema', () => {
const resolver = zodResolver(z.object({ id: z.number() }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a zod schema using a transform', () => {
const resolver = zodResolver(
z.object({ id: z.number().transform((val) => String(val)) }),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();
});
it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
const schema = z.object({ id: z.number() }).transform(({ id }) => {
return { id: String(id) };
});
const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
schema,
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, any, { id: string }>
>();
});
it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
const schema = z.object({ id: z.number() });
const form = useForm({
resolver: zodResolver(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 Zod schema with a transform for the handleSubmit function in useForm', () => {
const schema = z.object({ id: z.number().transform((val) => String(val)) });
const form = useForm({
resolver: zodResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

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

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

315
node_modules/@hookform/resolvers/zod/src/zod.ts generated vendored Normal file
View file

@ -0,0 +1,315 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import {
FieldError,
FieldErrors,
FieldValues,
Resolver,
ResolverError,
ResolverSuccess,
appendErrors,
} from 'react-hook-form';
import * as z3 from 'zod/v3';
import * as z4 from 'zod/v4/core';
const isZod3Error = (error: any): error is z3.ZodError => {
return Array.isArray(error?.issues);
};
const isZod3Schema = (schema: any): schema is z3.ZodSchema => {
return (
'_def' in schema &&
typeof schema._def === 'object' &&
'typeName' in schema._def
);
};
const isZod4Error = (error: any): error is z4.$ZodError => {
// instanceof is safe in Zod 4 (uses Symbol.hasInstance)
return error instanceof z4.$ZodError;
};
const isZod4Schema = (schema: any): schema is z4.$ZodType => {
return '_zod' in schema && typeof schema._zod === 'object';
};
function parseZod3Issues(
zodErrors: z3.ZodIssue[],
validateAllFieldCriteria: boolean,
) {
const errors: Record<string, FieldError> = {};
for (; zodErrors.length; ) {
const error = zodErrors[0];
const { code, message, path } = error;
const _path = path.join('.');
if (!errors[_path]) {
if ('unionErrors' in error) {
const unionError = error.unionErrors[0].errors[0];
errors[_path] = {
message: unionError.message,
type: unionError.code,
};
} else {
errors[_path] = { message, type: code };
}
}
if ('unionErrors' in error) {
error.unionErrors.forEach((unionError) =>
unionError.errors.forEach((e) => zodErrors.push(e)),
);
}
if (validateAllFieldCriteria) {
const types = errors[_path].types;
const messages = types && types[error.code];
errors[_path] = appendErrors(
_path,
validateAllFieldCriteria,
errors,
code,
messages
? ([] as string[]).concat(messages as string[], error.message)
: error.message,
) as FieldError;
}
zodErrors.shift();
}
return errors;
}
function parseZod4Issues(
zodErrors: z4.$ZodIssue[],
validateAllFieldCriteria: boolean,
) {
const errors: Record<string, FieldError> = {};
// const _zodErrors = zodErrors as z4.$ZodISsue; //
for (; zodErrors.length; ) {
const error = zodErrors[0];
const { code, message, path } = error;
const _path = path.join('.');
if (!errors[_path]) {
if (error.code === 'invalid_union' && error.errors.length > 0) {
const unionError = error.errors[0][0];
errors[_path] = {
message: unionError.message,
type: unionError.code,
};
} else {
errors[_path] = { message, type: code };
}
}
if (error.code === 'invalid_union') {
error.errors.forEach((unionError) =>
unionError.forEach((e) => zodErrors.push(e)),
);
}
if (validateAllFieldCriteria) {
const types = errors[_path].types;
const messages = types && types[error.code];
errors[_path] = appendErrors(
_path,
validateAllFieldCriteria,
errors,
code,
messages
? ([] as string[]).concat(messages as string[], error.message)
: error.message,
) as FieldError;
}
zodErrors.shift();
}
return errors;
}
type RawResolverOptions = {
mode?: 'async' | 'sync';
raw: true;
};
type NonRawResolverOptions = {
mode?: 'async' | 'sync';
raw?: false;
};
// minimal interfaces to avoid asssignability issues between versions
interface Zod3Type<O = unknown, I = unknown> {
_output: O;
_input: I;
_def: {
typeName: string;
};
}
// some type magic to make versions pre-3.25.0 still work
type IsUnresolved<T> = PropertyKey extends keyof T ? true : false;
type UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true
? Fallback
: T;
type FallbackIssue = {
code: string;
message: string;
path: (string | number)[];
};
type Zod3ParseParams = UnresolvedFallback<
z3.ParseParams,
// fallback if user is on <3.25.0
{
path?: (string | number)[];
errorMap?: (
iss: FallbackIssue,
ctx: {
defaultError: string;
data: any;
},
) => { message: string };
async?: boolean;
}
>;
type Zod4ParseParams = UnresolvedFallback<
z4.ParseContext<z4.$ZodIssue>,
// fallback if user is on <3.25.0
{
readonly error?: (
iss: FallbackIssue,
) => null | undefined | string | { message: string };
readonly reportInput?: boolean;
readonly jitless?: boolean;
}
>;
export function zodResolver<Input extends FieldValues, Context, Output>(
schema: Zod3Type<Output, Input>,
schemaOptions?: Zod3ParseParams,
resolverOptions?: NonRawResolverOptions,
): Resolver<Input, Context, Output>;
export function zodResolver<Input extends FieldValues, Context, Output>(
schema: Zod3Type<Output, Input>,
schemaOptions: Zod3ParseParams | undefined,
resolverOptions: RawResolverOptions,
): Resolver<Input, Context, Input>;
// the Zod 4 overloads need to be generic for complicated reasons
export function zodResolver<
Input extends FieldValues,
Context,
Output,
T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>,
>(
schema: T,
schemaOptions?: Zod4ParseParams, // already partial
resolverOptions?: NonRawResolverOptions,
): Resolver<z4.input<T>, Context, z4.output<T>>;
export function zodResolver<
Input extends FieldValues,
Context,
Output,
T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>,
>(
schema: z4.$ZodType<Output, Input>,
schemaOptions: Zod4ParseParams | undefined, // already partial
resolverOptions: RawResolverOptions,
): Resolver<z4.input<T>, Context, z4.input<T>>;
/**
* Creates a resolver function for react-hook-form that validates form data using a Zod schema
* @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data
* @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing
* @param {Object} [resolverOptions] - Optional resolver-specific configuration
* @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation
* @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data
* @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form
* @throws {Error} Throws if validation fails with a non-Zod error
* @example
* const schema = z3.object({
* name: z3.string().min(2),
* age: z3.number().min(18)
* });
*
* useForm({
* resolver: zodResolver(schema)
* });
*/
export function zodResolver<Input extends FieldValues, Context, Output>(
schema: object,
schemaOptions?: object,
resolverOptions: {
mode?: 'async' | 'sync';
raw?: boolean;
} = {},
): Resolver<Input, Context, Output | Input> {
if (isZod3Schema(schema)) {
return async (values: Input, _, options) => {
try {
const data = await schema[
resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'
](values, schemaOptions);
options.shouldUseNativeValidation &&
validateFieldsNatively({}, options);
return {
errors: {} as FieldErrors,
values: resolverOptions.raw ? Object.assign({}, values) : data,
} satisfies ResolverSuccess<Output | Input>;
} catch (error) {
if (isZod3Error(error)) {
return {
values: {},
errors: toNestErrors(
parseZod3Issues(
error.errors,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
} satisfies ResolverError<Input>;
}
throw error;
}
};
}
if (isZod4Schema(schema)) {
return async (values: Input, _, options) => {
try {
const parseFn =
resolverOptions.mode === 'sync' ? z4.parse : z4.parseAsync;
const data: any = await parseFn(schema, values, schemaOptions);
options.shouldUseNativeValidation &&
validateFieldsNatively({}, options);
return {
errors: {} as FieldErrors,
values: resolverOptions.raw ? Object.assign({}, values) : data,
} satisfies ResolverSuccess<Output | Input>;
} catch (error) {
if (isZod4Error(error)) {
return {
values: {},
errors: toNestErrors(
parseZod4Issues(
error.issues,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
} satisfies ResolverError<Input>;
}
throw error;
}
};
}
throw new Error('Invalid input: not a Zod schema');
}