@hookform/resolvers 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +17 -16
  2. package/ajv/package.json +1 -1
  3. package/arktype/package.json +1 -1
  4. package/computed-types/package.json +1 -1
  5. package/effect-ts/package.json +1 -1
  6. package/fluentvalidation-ts/package.json +1 -1
  7. package/io-ts/package.json +1 -1
  8. package/joi/package.json +1 -1
  9. package/nope/package.json +1 -1
  10. package/package.json +3 -3
  11. package/standard-schema/package.json +1 -1
  12. package/standard-schema/src/__tests__/__fixtures__/data.ts +1 -1
  13. package/standard-schema/src/__tests__/standard-schema.ts +1 -1
  14. package/superstruct/package.json +1 -1
  15. package/typanion/package.json +1 -1
  16. package/typebox/package.json +1 -1
  17. package/typebox/src/__tests__/typebox.ts +2 -2
  18. package/typeschema/dist/typeschema.d.ts +1 -1
  19. package/typeschema/dist/typeschema.js.map +1 -1
  20. package/typeschema/dist/typeschema.modern.mjs.map +1 -1
  21. package/typeschema/dist/typeschema.module.js.map +1 -1
  22. package/typeschema/dist/typeschema.umd.js.map +1 -1
  23. package/typeschema/package.json +1 -1
  24. package/typeschema/src/__tests__/Form-native-validation.tsx +1 -1
  25. package/typeschema/src/__tests__/Form.tsx +1 -1
  26. package/typeschema/src/__tests__/__fixtures__/data.ts +1 -1
  27. package/typeschema/src/__tests__/typeschema.ts +1 -1
  28. package/typeschema/src/typeschema.ts +1 -1
  29. package/valibot/package.json +1 -1
  30. package/vest/package.json +1 -1
  31. package/vine/package.json +1 -1
  32. package/yup/package.json +1 -1
  33. package/zod/dist/zod.d.ts +46 -7
  34. package/zod/dist/zod.js +1 -1
  35. package/zod/dist/zod.js.map +1 -1
  36. package/zod/dist/zod.mjs +1 -1
  37. package/zod/dist/zod.modern.mjs +1 -1
  38. package/zod/dist/zod.modern.mjs.map +1 -1
  39. package/zod/dist/zod.module.js +1 -1
  40. package/zod/dist/zod.module.js.map +1 -1
  41. package/zod/dist/zod.umd.js +1 -1
  42. package/zod/dist/zod.umd.js.map +1 -1
  43. package/zod/package.json +1 -1
  44. package/zod/src/__tests__/Form-native-validation.tsx +1 -1
  45. package/zod/src/__tests__/Form.tsx +1 -1
  46. package/zod/src/__tests__/__fixtures__/{data.ts → data-v3.ts} +1 -1
  47. package/zod/src/__tests__/__fixtures__/data-v4-mini.ts +98 -0
  48. package/zod/src/__tests__/__fixtures__/data-v4.ts +89 -0
  49. package/zod/src/__tests__/zod-v3.ts +178 -0
  50. package/zod/src/__tests__/zod-v4-mini.ts +182 -0
  51. package/zod/src/__tests__/{zod.ts → zod-v4.ts} +17 -2
  52. package/zod/src/zod.ts +227 -53
@@ -1 +1 @@
1
- {"version":3,"file":"zod.umd.js","sources":["../src/zod.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\nimport { ZodError, z } from 'zod';\n\nconst isZodError = (error: any): error is ZodError =>\n Array.isArray(error?.errors);\n\nfunction parseErrorSchema(\n zodErrors: z.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n const unionError = error.unionErrors[0].errors[0];\n\n errors[_path] = {\n message: unionError.message,\n type: unionError.code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: z.ZodSchema<Output, any, Input>,\n schemaOptions?: Partial<z.ParseParams>,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver<Input, Context, Output>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: z.ZodSchema<Output, any, Input>,\n schemaOptions: Partial<z.ParseParams> | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver<Input, Context, Input>;\n\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z.object({\n * name: z.string().min(2),\n * age: z.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: z.ZodSchema<Output, any, Input>,\n schemaOptions?: Partial<z.ParseParams>,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZodError(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n}\n"],"names":["parseErrorSchema","zodErrors","validateAllFieldCriteria","errors","length","error","code","message","_path","path","join","unionError","unionErrors","type","forEach","e","push","types","messages","appendErrors","concat","shift","schema","schemaOptions","resolverOptions","values","_","options","Promise","resolve","mode","then","data","shouldUseNativeValidation","validateFieldsNatively","raw","Object","assign","_catch","Array","isArray","isZodError","toNestErrors","criteriaMode","reject"],"mappings":"wXAeA,SAASA,EACPC,EACAC,GAGA,IADA,IAAMC,EAAqC,CAAE,EACtCF,EAAUG,QAAU,CACzB,IAAMC,EAAQJ,EAAU,GAChBK,EAAwBD,EAAxBC,KAAMC,EAAkBF,EAAlBE,QACRC,EAD0BH,EAATI,KACJC,KAAK,KAExB,IAAKP,EAAOK,GACV,GAAI,gBAAiBH,EAAO,CAC1B,IAAMM,EAAaN,EAAMO,YAAY,GAAGT,OAAO,GAE/CA,EAAOK,GAAS,CACdD,QAASI,EAAWJ,QACpBM,KAAMF,EAAWL,KAErB,MACEH,EAAOK,GAAS,CAAED,QAAAA,EAASM,KAAMP,GAUrC,GANI,gBAAiBD,GACnBA,EAAMO,YAAYE,QAAQ,SAACH,GACzB,OAAAA,EAAWR,OAAOW,QAAQ,SAACC,GAAC,OAAKd,EAAUe,KAAKD,EAAE,EAAC,GAInDb,EAA0B,CAC5B,IAAMe,EAAQd,EAAOK,GAAOS,MACtBC,EAAWD,GAASA,EAAMZ,EAAMC,MAEtCH,EAAOK,GAASW,EAAYA,aAC1BX,EACAN,EACAC,EACAG,EACAY,EACK,GAAgBE,OAAOF,EAAsBb,EAAME,SACpDF,EAAME,QAEd,CAEAN,EAAUoB,OACZ,CAEA,OAAOlB,CACT,eAuCM,SACJmB,EACAC,EACAC,GAKA,YALAA,IAAAA,IAAAA,EAGI,CAAE,GAEQC,SAAAA,EAAeC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCACrCD,QAAAC,QACiBP,EACQ,SAAzBE,EAAgBM,KAAkB,QAAU,cAC5CL,EAAQF,IAAcQ,KAFlBC,SAAAA,GAMN,OAFAL,EAAQM,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIP,GAEzD,CACLxB,OAAQ,CAAA,EACRsB,OAAQD,EAAgBW,IAAMC,OAAOC,OAAO,CAAE,EAAEZ,GAAUO,EAChB,4DAXLM,CAAA,EAYhCjC,SAAAA,GACP,GA/Ga,SAACA,GAClB,OAAAkC,MAAMC,QAAa,MAALnC,OAAK,EAALA,EAAOF,OAAO,CA8GpBsC,CAAWpC,GACb,MAAO,CACLoB,OAAQ,CAAA,EACRtB,OAAQuC,EAAYA,aAClB1C,EACEK,EAAMF,QACLwB,EAAQM,2BACkB,QAAzBN,EAAQgB,cAEZhB,IAKN,MAAMtB,CACR,GACF,CAAC,MAAAU,GAAAa,OAAAA,QAAAgB,OAAA7B,EACH,CAAA,CAAA"}
1
+ {"version":3,"file":"zod.umd.js","sources":["../../node_modules/zod/dist/esm/v4/core/core.js","../../node_modules/zod/dist/esm/v4/core/util.js","../../node_modules/zod/dist/esm/v4/core/errors.js","../../node_modules/zod/dist/esm/v4/core/parse.js","../src/zod.ts"],"sourcesContent":["export /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n var _a;\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod ?? {},\n enumerable: false,\n });\n (_a = inst._zod).traits ?? (_a.traits = new Set());\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n for (const k in _.prototype) {\n if (!(k in inst))\n Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });\n }\n inst._zod.constr = _;\n inst._zod.def = def;\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error();\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport function defineLazy(object, key, getter) {\n const set = false;\n Object.defineProperty(object, key, {\n get() {\n if (!set) {\n const value = getter();\n object[key] = value;\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(data) {\n return (typeof data === \"object\" &&\n data !== null &&\n (Object.getPrototypeOf(data) === Object.prototype || Object.getPrototypeOf(data) === null));\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const newShape = {};\n const currDef = schema._zod.def; //.shape;\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // pick key\n newShape[key] = currDef.shape[key];\n }\n return clone(schema, {\n ...schema._zod.def,\n shape: newShape,\n checks: [],\n });\n}\nexport function omit(schema, mask) {\n const newShape = { ...schema._zod.def.shape };\n const currDef = schema._zod.def; //.shape;\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n return clone(schema, {\n ...schema._zod.def,\n shape: newShape,\n checks: [],\n });\n}\nexport function extend(schema, shape) {\n const def = {\n ...schema._zod.def,\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: [], // delete existing checks\n };\n return clone(schema, def);\n}\nexport function merge(a, b) {\n return clone(a, {\n ...a._zod.def,\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n catchall: b._zod.def.catchall,\n checks: [], // delete existing checks\n });\n}\nexport function partial(Class, schema, mask) {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n return clone(schema, {\n ...schema._zod.def,\n shape,\n checks: [],\n });\n}\nexport function required(Class, schema, mask) {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n return clone(schema, {\n ...schema._zod.def,\n shape,\n // optional: [],\n checks: [],\n });\n}\nexport function aborted(x, startIndex = 0) {\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i].continue !== true)\n return true;\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n Object.defineProperty(inst, \"message\", {\n get() {\n return JSON.stringify(def, util.jsonStringifyReplacer, 2);\n },\n enumerable: true,\n // configurable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(path) {\n const segs = [];\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n Error.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n Error.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n","import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n ResolverError,\n ResolverSuccess,\n appendErrors,\n} from 'react-hook-form';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4/core';\n\nconst isZod3Error = (error: any): error is z3.ZodError => {\n return Array.isArray(error?.issues);\n};\nconst isZod3Schema = (schema: any): schema is z3.ZodSchema => {\n return (\n '_def' in schema &&\n typeof schema._def === 'object' &&\n 'typeName' in schema._def\n );\n};\nconst isZod4Error = (error: any): error is z4.$ZodError => {\n // instanceof is safe in Zod 4 (uses Symbol.hasInstance)\n return error instanceof z4.$ZodError;\n};\nconst isZod4Schema = (schema: any): schema is z4.$ZodType => {\n return '_zod' in schema && typeof schema._zod === 'object';\n};\n\nfunction parseZod3Issues(\n zodErrors: z3.ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if ('unionErrors' in error) {\n const unionError = error.unionErrors[0].errors[0];\n\n errors[_path] = {\n message: unionError.message,\n type: unionError.code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if ('unionErrors' in error) {\n error.unionErrors.forEach((unionError) =>\n unionError.errors.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\nfunction parseZod4Issues(\n zodErrors: z4.$ZodIssue[],\n validateAllFieldCriteria: boolean,\n) {\n const errors: Record<string, FieldError> = {};\n // const _zodErrors = zodErrors as z4.$ZodISsue; //\n for (; zodErrors.length; ) {\n const error = zodErrors[0];\n const { code, message, path } = error;\n const _path = path.join('.');\n\n if (!errors[_path]) {\n if (error.code === 'invalid_union') {\n const unionError = error.errors[0][0];\n\n errors[_path] = {\n message: unionError.message,\n type: unionError.code,\n };\n } else {\n errors[_path] = { message, type: code };\n }\n }\n\n if (error.code === 'invalid_union') {\n error.errors.forEach((unionError) =>\n unionError.forEach((e) => zodErrors.push(e)),\n );\n }\n\n if (validateAllFieldCriteria) {\n const types = errors[_path].types;\n const messages = types && types[error.code];\n\n errors[_path] = appendErrors(\n _path,\n validateAllFieldCriteria,\n errors,\n code,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n zodErrors.shift();\n }\n\n return errors;\n}\n\ntype RawResolverOptions = {\n mode?: 'async' | 'sync';\n raw: true;\n};\ntype NonRawResolverOptions = {\n mode?: 'async' | 'sync';\n raw?: false;\n};\n\n// minimal interfaces to avoid asssignability issues between versions\ninterface Zod3Type<O = unknown, I = unknown> {\n _output: O;\n _input: I;\n _def: {\n typeName: string;\n };\n}\n\n// some type magic to make versions pre-3.25.0 still work\ntype IsUnresolved<T> = PropertyKey extends keyof T ? true : false;\ntype UnresolvedFallback<T, Fallback> = IsUnresolved<typeof z3> extends true\n ? Fallback\n : T;\ntype FallbackIssue = {\n code: string;\n message: string;\n path: (string | number)[];\n};\ntype Zod3ParseParams = UnresolvedFallback<\n z3.ParseParams,\n // fallback if user is on <3.25.0\n {\n path?: (string | number)[];\n errorMap?: (\n iss: FallbackIssue,\n ctx: {\n defaultError: string;\n data: any;\n },\n ) => { message: string };\n async?: boolean;\n }\n>;\ntype Zod4ParseParams = UnresolvedFallback<\n z4.ParseContext<z4.$ZodIssue>,\n // fallback if user is on <3.25.0\n {\n readonly error?: (\n iss: FallbackIssue,\n ) => null | undefined | string | { message: string };\n readonly reportInput?: boolean;\n readonly jitless?: boolean;\n }\n>;\n\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions?: Zod3ParseParams,\n resolverOptions?: NonRawResolverOptions,\n): Resolver<Input, Context, Output>;\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: Zod3Type<Output, Input>,\n schemaOptions: Zod3ParseParams | undefined,\n resolverOptions: RawResolverOptions,\n): Resolver<Input, Context, Input>;\n// the Zod 4 overloads need to be generic for complicated reasons\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>,\n>(\n schema: T,\n schemaOptions?: Zod4ParseParams, // already partial\n resolverOptions?: NonRawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.output<T>>;\nexport function zodResolver<\n Input extends FieldValues,\n Context,\n Output,\n T extends z4.$ZodType<Output, Input> = z4.$ZodType<Output, Input>,\n>(\n schema: z4.$ZodType<Output, Input>,\n schemaOptions: Zod4ParseParams | undefined, // already partial\n resolverOptions: RawResolverOptions,\n): Resolver<z4.input<T>, Context, z4.input<T>>;\n/**\n * Creates a resolver function for react-hook-form that validates form data using a Zod schema\n * @param {z3.ZodSchema<Input>} schema - The Zod schema used to validate the form data\n * @param {Partial<z3.ParseParams>} [schemaOptions] - Optional configuration options for Zod parsing\n * @param {Object} [resolverOptions] - Optional resolver-specific configuration\n * @param {('async'|'sync')} [resolverOptions.mode='async'] - Validation mode. Use 'sync' for synchronous validation\n * @param {boolean} [resolverOptions.raw=false] - If true, returns the raw form values instead of the parsed data\n * @returns {Resolver<z3.output<typeof schema>>} A resolver function compatible with react-hook-form\n * @throws {Error} Throws if validation fails with a non-Zod error\n * @example\n * const schema = z3.object({\n * name: z3.string().min(2),\n * age: z3.number().min(18)\n * });\n *\n * useForm({\n * resolver: zodResolver(schema)\n * });\n */\nexport function zodResolver<Input extends FieldValues, Context, Output>(\n schema: object,\n schemaOptions?: object,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw?: boolean;\n } = {},\n): Resolver<Input, Context, Output | Input> {\n if (isZod3Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const data = await schema[\n resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'\n ](values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod3Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod3Issues(\n error.errors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n if (isZod4Schema(schema)) {\n return async (values: Input, _, options) => {\n try {\n const parseFn =\n resolverOptions.mode === 'sync' ? z4.parse : z4.parseAsync;\n const data: any = await parseFn(schema, values, schemaOptions);\n\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n } satisfies ResolverSuccess<Output | Input>;\n } catch (error) {\n if (isZod4Error(error)) {\n return {\n values: {},\n errors: toNestErrors(\n parseZod4Issues(\n error.issues,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n } satisfies ResolverError<Input>;\n }\n\n throw error;\n }\n };\n }\n\n throw new Error('Invalid input: not a Zod schema');\n}\n"],"names":["$constructor","name","initializer","params","init","inst","def","_a","Object","defineProperty","value","_zod","enumerable","traits","Set","add","k","_","prototype","bind","constr","Parent","Definition","this","deferred","fn","Symbol","hasInstance","has","$ZodAsyncError","Error","constructor","super","globalConfig","config","newConfig","assign","jsonStringifyReplacer","toString","unwrapMessage","message","finalizeIssue","iss","ctx","full","path","error","customError","localeError","continue","reportInput","input","get","JSON","stringify","util.jsonStringifyReplacer","$ZodError","$ZodRealError","parse","_Err","schema","_ctx","_params","async","result","run","issues","Promise","core.$ZodAsyncError","length","e","Err","map","util.finalizeIssue","core.config","captureStackTrace","callee","_parse","errors.$ZodRealError","parseAsync","_parseAsync","parseZod3Issues","zodErrors","validateAllFieldCriteria","errors","code","_path","join","unionError","unionErrors","type","forEach","push","types","messages","appendErrors","concat","shift","parseZod4Issues","schemaOptions","resolverOptions","_def","isZod3Schema","values","options","resolve","_catch","mode","then","data","shouldUseNativeValidation","validateFieldsNatively","raw","Array","isArray","isZod3Error","toNestErrors","criteriaMode","reject","isZod4Schema","z4","isZod4Error"],"mappings":"wXAAgC,SAASA,EAAaC,EAAMC,EAAaC,GACrE,SAASC,EAAKC,EAAMC,GAChB,IAAIC,EACJC,OAAOC,eAAeJ,EAAM,OAAQ,CAChCK,MAAOL,EAAKM,MAAQ,CAAE,EACtBC,YAAY,KAEfL,EAAKF,EAAKM,MAAME,SAAWN,EAAGM,OAAS,IAAIC,KAC5CT,EAAKM,KAAKE,OAAOE,IAAId,GACrBC,EAAYG,EAAMC,GAElB,IAAK,MAAMU,KAAKC,EAAEC,UACRF,KAAKX,GACPG,OAAOC,eAAeJ,EAAMW,EAAG,CAAEN,MAAOO,EAAEC,UAAUF,GAAGG,KAAKd,KAEpEA,EAAKM,KAAKS,OAASH,EACnBZ,EAAKM,KAAKL,IAAMA,CACnB,CAED,MAAMe,EAASlB,GAAQkB,QAAUb,OACjC,MAAMc,UAAmBD,GAGzB,SAASJ,EAAEX,GACP,IAAIC,EACJ,MAAMF,EAAOF,GAAQkB,OAAS,IAAIC,EAAeC,KACjDnB,EAAKC,EAAMC,IACVC,EAAKF,EAAKM,MAAMa,WAAajB,EAAGiB,SAAW,IAC5C,IAAK,MAAMC,KAAMpB,EAAKM,KAAKa,SACvBC,IAEJ,OAAOpB,CACV,CAUD,OApBAG,OAAOC,eAAea,EAAY,OAAQ,CAAEZ,MAAOT,IAWnDO,OAAOC,eAAeQ,EAAG,OAAQ,CAAEP,MAAON,IAC1CI,OAAOC,eAAeQ,EAAGS,OAAOC,YAAa,CACzCjB,MAAQL,MACAF,GAAQkB,QAAUhB,aAA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,OAHAL,EAAQM,2BACNC,EAAsBA,uBAAC,CAAE,EAAEP,GAEtB,CACLpB,OAAQ,CAAA,EACRmB,OAAQH,EAAgBY,IAAMxG,OAAO4B,OAAO,CAAE,EAAEmE,GAAUM,EAChB,EAC9C,EAAS/D,SAAAA,GACP,GA/QY,SAACA,GAEnB,OAAOA,aAAiB0E,CAC1B,CA4QYC,CAAY3E,GACd,MAAO,CACLyD,OAAQ,CAAE,EACVnB,OAAQgC,EAAYA,aAClBlB,EACEpD,EAAMoB,QACLsC,EAAQM,2BACkB,QAAzBN,EAAQa,cAEZb,IAKN,MAAM1D,CACR,GACF,CAAC,MAAAwB,GAAAH,OAAAA,QAAAmD,OAAAhD,EACH,CAAA,EAEA,MAAM,IAAIxC,MAAM,kCAClB"}
package/zod/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "types": "dist/index.d.ts",
12
12
  "license": "MIT",
13
13
  "peerDependencies": {
14
- "react-hook-form": "7.55.0",
14
+ "react-hook-form": "^7.55.0",
15
15
  "@hookform/resolvers": "^2.0.0"
16
16
  }
17
17
  }
@@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react';
2
2
  import user from '@testing-library/user-event';
3
3
  import React from 'react';
4
4
  import { useForm } from 'react-hook-form';
5
- import { z } from 'zod';
5
+ import { z } from 'zod/v3';
6
6
  import { zodResolver } from '..';
7
7
 
8
8
  const USERNAME_REQUIRED_MESSAGE = 'username field is required';
@@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react';
2
2
  import user from '@testing-library/user-event';
3
3
  import React from 'react';
4
4
  import { useForm } from 'react-hook-form';
5
- import { z } from 'zod';
5
+ import { z } from 'zod/v3';
6
6
  import { zodResolver } from '..';
7
7
 
8
8
  const schema = z.object({
@@ -1,5 +1,5 @@
1
1
  import { Field, InternalFieldName } from 'react-hook-form';
2
- import { z } from 'zod';
2
+ import { z } from 'zod/v3';
3
3
 
4
4
  export const schema = z
5
5
  .object({
@@ -0,0 +1,98 @@
1
+ import { Field, InternalFieldName } from 'react-hook-form';
2
+ import { z } from 'zod/v4-mini';
3
+
4
+ export const schema = z
5
+ .object({
6
+ username: z
7
+ .string()
8
+ .check(z.regex(/^\w+$/), z.minLength(3), z.maxLength(30)),
9
+ password: z
10
+ .string()
11
+ .check(
12
+ z.regex(new RegExp('.*[A-Z].*'), 'One uppercase character'),
13
+ z.regex(new RegExp('.*[a-z].*'), 'One lowercase character'),
14
+ z.regex(new RegExp('.*\\d.*'), 'One number'),
15
+ z.regex(
16
+ new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
17
+ 'One special character',
18
+ ),
19
+ z.minLength(8, 'Must be at least 8 characters in length'),
20
+ ),
21
+ repeatPassword: z.string(),
22
+ accessToken: z.union([z.string(), z.number()]),
23
+ birthYear: z.optional(z.number().check(z.minimum(1900), z.maximum(2013))),
24
+ email: z.optional(z.email()),
25
+ tags: z.array(z.string()),
26
+ enabled: z.boolean(),
27
+ url: z.union([z.url('Custom error url'), z.literal('')]),
28
+ like: z.optional(
29
+ z.array(
30
+ z.object({
31
+ id: z.number(),
32
+ name: z.string().check(z.length(4)),
33
+ }),
34
+ ),
35
+ ),
36
+ dateStr: z
37
+ .pipe(
38
+ z.string(),
39
+ z.transform((value) => new Date(value)),
40
+ )
41
+ .check(
42
+ z.refine((value) => !isNaN(value.getTime()), {
43
+ message: 'Invalid date',
44
+ }),
45
+ ),
46
+ })
47
+ .check(
48
+ z.refine((obj) => obj.password === obj.repeatPassword, {
49
+ message: 'Passwords do not match',
50
+ path: ['confirm'],
51
+ }),
52
+ );
53
+
54
+ export const validData = {
55
+ username: 'Doe',
56
+ password: 'Password123_',
57
+ repeatPassword: 'Password123_',
58
+ birthYear: 2000,
59
+ email: 'john@doe.com',
60
+ tags: ['tag1', 'tag2'],
61
+ enabled: true,
62
+ accessToken: 'accessToken',
63
+ url: 'https://react-hook-form.com/',
64
+ like: [
65
+ {
66
+ id: 1,
67
+ name: 'name',
68
+ },
69
+ ],
70
+ dateStr: '2020-01-01',
71
+ } satisfies z.input<typeof schema>;
72
+
73
+ export const invalidData = {
74
+ password: '___',
75
+ email: '',
76
+ birthYear: 'birthYear',
77
+ like: [{ id: 'z' }],
78
+ url: 'abc',
79
+ } as unknown as z.input<typeof schema>;
80
+
81
+ export const fields: Record<InternalFieldName, Field['_f']> = {
82
+ username: {
83
+ ref: { name: 'username' },
84
+ name: 'username',
85
+ },
86
+ password: {
87
+ ref: { name: 'password' },
88
+ name: 'password',
89
+ },
90
+ email: {
91
+ ref: { name: 'email' },
92
+ name: 'email',
93
+ },
94
+ birthday: {
95
+ ref: { name: 'birthday' },
96
+ name: 'birthday',
97
+ },
98
+ };
@@ -0,0 +1,89 @@
1
+ import { Field, InternalFieldName } from 'react-hook-form';
2
+ import { z } from 'zod/v4';
3
+
4
+ export const schema = z
5
+ .object({
6
+ username: z.string().regex(/^\w+$/).min(3).max(30),
7
+ password: z
8
+ .string()
9
+ .regex(new RegExp('.*[A-Z].*'), 'One uppercase character')
10
+ .regex(new RegExp('.*[a-z].*'), 'One lowercase character')
11
+ .regex(new RegExp('.*\\d.*'), 'One number')
12
+ .regex(
13
+ new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
14
+ 'One special character',
15
+ )
16
+ .min(8, 'Must be at least 8 characters in length'),
17
+ repeatPassword: z.string(),
18
+ accessToken: z.union([z.string(), z.number()]),
19
+ birthYear: z.number().min(1900).max(2013).optional(),
20
+ email: z.string().email().optional(),
21
+ tags: z.array(z.string()),
22
+
23
+ enabled: z.boolean(),
24
+ url: z.string().url('Custom error url').or(z.literal('')),
25
+ like: z
26
+ .array(
27
+ z.object({
28
+ id: z.number(),
29
+ name: z.string().length(4),
30
+ }),
31
+ )
32
+ .optional(),
33
+ dateStr: z
34
+ .string()
35
+ .transform((value) => new Date(value))
36
+ .refine((value) => !isNaN(value.getTime()), {
37
+ message: 'Invalid date',
38
+ }),
39
+ })
40
+ .refine((obj) => obj.password === obj.repeatPassword, {
41
+ message: 'Passwords do not match',
42
+ path: ['confirm'],
43
+ });
44
+
45
+ export const validData = {
46
+ username: 'Doe',
47
+ password: 'Password123_',
48
+ repeatPassword: 'Password123_',
49
+ birthYear: 2000,
50
+ email: 'john@doe.com',
51
+ tags: ['tag1', 'tag2'],
52
+ enabled: true,
53
+ accessToken: 'accessToken',
54
+ url: 'https://react-hook-form.com/',
55
+ like: [
56
+ {
57
+ id: 1,
58
+ name: 'name',
59
+ },
60
+ ],
61
+ dateStr: '2020-01-01',
62
+ } satisfies z.input<typeof schema>;
63
+
64
+ export const invalidData = {
65
+ password: '___',
66
+ email: '',
67
+ birthYear: 'birthYear',
68
+ like: [{ id: 'z' }],
69
+ url: 'abc',
70
+ } as unknown as z.input<typeof schema>;
71
+
72
+ export const fields: Record<InternalFieldName, Field['_f']> = {
73
+ username: {
74
+ ref: { name: 'username' },
75
+ name: 'username',
76
+ },
77
+ password: {
78
+ ref: { name: 'password' },
79
+ name: 'password',
80
+ },
81
+ email: {
82
+ ref: { name: 'email' },
83
+ name: 'email',
84
+ },
85
+ birthday: {
86
+ ref: { name: 'birthday' },
87
+ name: 'birthday',
88
+ },
89
+ };
@@ -0,0 +1,178 @@
1
+ import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
2
+ import { z } from 'zod/v3';
3
+ import { zodResolver } from '..';
4
+ import { fields, invalidData, schema, validData } from './__fixtures__/data-v3';
5
+
6
+ const shouldUseNativeValidation = false;
7
+
8
+ describe('zodResolver', () => {
9
+ it('should return values from zodResolver when validation pass & raw=true', async () => {
10
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
11
+
12
+ const result = await zodResolver(schema, undefined, {
13
+ raw: true,
14
+ })(validData, undefined, {
15
+ fields,
16
+ shouldUseNativeValidation,
17
+ });
18
+
19
+ expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
20
+ expect(result).toEqual({ errors: {}, values: validData });
21
+ });
22
+
23
+ it('should return parsed values from zodResolver with `mode: sync` when validation pass', async () => {
24
+ const parseSpy = vi.spyOn(schema, 'parse');
25
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
26
+
27
+ const result = await zodResolver(schema, undefined, {
28
+ mode: 'sync',
29
+ })(validData, undefined, { fields, shouldUseNativeValidation });
30
+
31
+ expect(parseSpy).toHaveBeenCalledTimes(1);
32
+ expect(parseAsyncSpy).not.toHaveBeenCalled();
33
+ expect(result.errors).toEqual({});
34
+ expect(result).toMatchSnapshot();
35
+ });
36
+
37
+ it('should return a single error from zodResolver when validation fails', async () => {
38
+ const result = await zodResolver(schema)(invalidData, undefined, {
39
+ fields,
40
+ shouldUseNativeValidation,
41
+ });
42
+
43
+ expect(result).toMatchSnapshot();
44
+ });
45
+
46
+ it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
47
+ const parseSpy = vi.spyOn(schema, 'parse');
48
+ const parseAsyncSpy = vi.spyOn(schema, 'parseAsync');
49
+
50
+ const result = await zodResolver(schema, undefined, {
51
+ mode: 'sync',
52
+ })(invalidData, undefined, { fields, shouldUseNativeValidation });
53
+
54
+ expect(parseSpy).toHaveBeenCalledTimes(1);
55
+ expect(parseAsyncSpy).not.toHaveBeenCalled();
56
+ expect(result).toMatchSnapshot();
57
+ });
58
+
59
+ it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
60
+ const result = await zodResolver(schema)(invalidData, undefined, {
61
+ fields,
62
+ criteriaMode: 'all',
63
+ shouldUseNativeValidation,
64
+ });
65
+
66
+ expect(result).toMatchSnapshot();
67
+ });
68
+
69
+ it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
70
+ const result = await zodResolver(schema, undefined, { mode: 'sync' })(
71
+ invalidData,
72
+ undefined,
73
+ {
74
+ fields,
75
+ criteriaMode: 'all',
76
+ shouldUseNativeValidation,
77
+ },
78
+ );
79
+
80
+ expect(result).toMatchSnapshot();
81
+ });
82
+
83
+ it('should throw any error unrelated to Zod', async () => {
84
+ const schemaWithCustomError = schema.refine(() => {
85
+ throw Error('custom error');
86
+ });
87
+ const promise = zodResolver(schemaWithCustomError)(validData, undefined, {
88
+ fields,
89
+ shouldUseNativeValidation,
90
+ });
91
+
92
+ await expect(promise).rejects.toThrow('custom error');
93
+ });
94
+
95
+ it('should enforce parse params type signature', async () => {
96
+ const resolver = zodResolver(schema, {
97
+ async: true,
98
+ path: ['asdf', 1234],
99
+ errorMap(iss, ctx) {
100
+ iss.path;
101
+ iss.code;
102
+ iss.path;
103
+ ctx.data;
104
+ ctx.defaultError;
105
+ return { message: 'asdf' };
106
+ },
107
+ });
108
+
109
+ resolver;
110
+ });
111
+
112
+ /**
113
+ * Type inference tests
114
+ */
115
+ it('should correctly infer the output type from a zod schema', () => {
116
+ const resolver = zodResolver(z.object({ id: z.number() }));
117
+
118
+ expectTypeOf(resolver).toEqualTypeOf<
119
+ Resolver<{ id: number }, unknown, { id: number }>
120
+ >();
121
+ });
122
+
123
+ it('should correctly infer the output type from a zod schema using a transform', () => {
124
+ const resolver = zodResolver(
125
+ z.object({ id: z.number().transform((val) => String(val)) }),
126
+ );
127
+
128
+ expectTypeOf(resolver).toEqualTypeOf<
129
+ Resolver<{ id: number }, unknown, { id: string }>
130
+ >();
131
+ });
132
+
133
+ it('should correctly infer the output type from a zod schema when a different input type is specified', () => {
134
+ const schema = z.object({ id: z.number() }).transform(({ id }) => {
135
+ return { id: String(id) };
136
+ });
137
+
138
+ const resolver = zodResolver<{ id: number }, any, z.output<typeof schema>>(
139
+ schema,
140
+ );
141
+
142
+ expectTypeOf(resolver).toEqualTypeOf<
143
+ Resolver<{ id: number }, any, { id: string }>
144
+ >();
145
+ });
146
+
147
+ it('should correctly infer the output type from a Zod schema for the handleSubmit function in useForm', () => {
148
+ const schema = z.object({ id: z.number() });
149
+
150
+ const form = useForm({
151
+ resolver: zodResolver(schema),
152
+ });
153
+
154
+ expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
155
+
156
+ expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
157
+ SubmitHandler<{
158
+ id: number;
159
+ }>
160
+ >();
161
+ });
162
+
163
+ it('should correctly infer the output type from a Zod schema with a transform for the handleSubmit function in useForm', () => {
164
+ const schema = z.object({ id: z.number().transform((val) => String(val)) });
165
+
166
+ const form = useForm({
167
+ resolver: zodResolver(schema),
168
+ });
169
+
170
+ expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
171
+
172
+ expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
173
+ SubmitHandler<{
174
+ id: string;
175
+ }>
176
+ >();
177
+ });
178
+ });