{"name":"zod-validation-error","version":"3.4.0","description":"Wrap zod validation errors in user-friendly readable messages","keywords":["zod","error","validation"],"license":"MIT","repository":{"type":"git","url":"git://github.com/causaly/zod-validation-error.git"},"author":{"name":"Dimitrios C. Michalakos","email":"dimitris@jmike.gr","url":"https://github.com/jmike"},"contributors":[{"name":"Thanos Karagiannis","email":"hey@maestros.io","url":"https://github.com/thanoskrg"},{"name":"Nikos Kalogridis","url":"https://github.com/nikoskalogridis"}],"main":"./dist/index.js","module":"./dist/index.mjs","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","require":"./dist/index.js","import":"./dist/index.mjs"}},"publishConfig":{"access":"public"},"sideEffects":false,"engines":{"node":">=18.0.0"},"scripts":{"typecheck":"tsc --noEmit","build":"tsup --config ./tsup.config.ts","lint":"eslint lib --ext .ts","format":"prettier --config ./.prettierrc --ignore-path .gitignore -w .","test":"jest","coverage":"jest --coverage","changeset":"changeset","prerelease":"npm run build && npm run test","release":"changeset publish","prepare":"husky install"},"lint-staged":{"*.{js,jsx,ts,tsx}":["eslint --fix","prettier --config ./.prettierrc --write"]},"devDependencies":{"@changesets/changelog-github":"^0.5.0","@changesets/cli":"^2.27.7","@commitlint/cli":"^18.0.0","@commitlint/config-conventional":"^18.0.0","@types/jest":"^29.2.4","@types/node":"^20.5.0","@typescript-eslint/eslint-plugin":"^6.4.1","@typescript-eslint/parser":"^6.4.1","concurrently":"^8.2.0","eslint":"^8.4.1","eslint-config-prettier":"^9.0.0","eslint-plugin-import":"^2.29.1","eslint-plugin-prettier":"^4.2.1","husky":"^8.0.3","jest":"^29.3.1","lint-staged":"^15.0.1","prettier":"^2.8.8","rimraf":"^5.0.1","ts-jest":"^29.0.3","tsup":"^8.0.2","typescript":"^5.1.6","zod":"^3.20.0"},"peerDependencies":{"zod":"^3.18.0"},"_id":"zod-validation-error@3.4.0","gitHead":"a332c003216f82daf7eccc70b471e07377467eaf","bugs":{"url":"https://github.com/causaly/zod-validation-error/issues"},"homepage":"https://github.com/causaly/zod-validation-error#readme","_nodeVersion":"20.17.0","_npmVersion":"10.8.2","dist":{"integrity":"sha512-ZOPR9SVY6Pb2qqO5XHt+MkkTRxGXb4EVtnjc9JpXUOtUB1T9Ru7mZOT361AN3MsetVe7R0a1KZshJDZdgp9miQ==","shasum":"3a8a1f55c65579822d7faa190b51336c61bee2a6","tarball":"http://registry-npm.ywwl.com/zod-validation-error/download/zod-validation-error-3.4.0.tgz","fileCount":9,"unpackedSize":73670,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICgxYxPexYUM9dUab6q2SgYcbuTsHTUS2N3m1D6OEcamAiEA4eNNzd0RwWvYPbJvhuLHuO4xr5pzuewk/n2SoOiyk68="}],"size":13986,"noattachment":false,"key":"/zod-validation-error/-/zod-validation-error-3.4.0.tgz"},"_npmUser":{"name":"jmike","email":"dimitris@jmike.gr"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zod-validation-error_3.4.0_1726469045417_0.39345610085901717"},"_hasShrinkwrap":false,"readme":"# zod-validation-error\n\nWrap zod validation errors in user-friendly readable messages.\n\n[![Build Status](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml/badge.svg)](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/zod-validation-error.svg?color=0c0)](https://www.npmjs.com/package/zod-validation-error)\n\n#### Features\n\n- User-friendly readable messages, configurable via options;\n- Maintain original issues under `error.details`;\n- Extensive tests.\n\n## Installation\n\n```bash\nnpm install zod-validation-error\n```\n\n#### Requirements\n\n- Node.js v.18+\n- TypeScript v.4.5+\n\n## Quick start\n\n```typescript\nimport { z as zod } from 'zod';\nimport { fromError } from 'zod-validation-error';\n\n// create zod schema\nconst zodSchema = zod.object({\n  id: zod.number().int().positive(),\n  email: zod.string().email(),\n});\n\n// parse some invalid value\ntry {\n  zodSchema.parse({\n    id: 1,\n    email: 'foobar', // note: invalid email\n  });\n} catch (err) {\n  const validationError = fromError(err);\n  // the error is now readable by the user\n  // you may print it to console\n  console.log(validationError.toString());\n  // or return it as an actual error\n  return validationError;\n}\n```\n\n## Motivation\n\nZod errors are difficult to consume for the end-user. This library wraps Zod validation errors in user-friendly readable messages that can be exposed to the outer world, while maintaining the original errors in an array for _dev_ use.\n\n### Example\n\n#### Input (from Zod)\n\n```json\n[\n  {\n    \"code\": \"too_small\",\n    \"inclusive\": false,\n    \"message\": \"Number must be greater than 0\",\n    \"minimum\": 0,\n    \"path\": [\"id\"],\n    \"type\": \"number\"\n  },\n  {\n    \"code\": \"invalid_string\",\n    \"message\": \"Invalid email\",\n    \"path\": [\"email\"],\n    \"validation\": \"email\"\n  }\n]\n```\n\n#### Output\n\n```\nValidation error: Number must be greater than 0 at \"id\"; Invalid email at \"email\"\n```\n\n## API\n\n- [ValidationError(message[, options])](#validationerror)\n- [createMessageBuilder(props)](#createMessageBuilder)\n- [errorMap](#errormap)\n- [isValidationError(error)](#isvalidationerror)\n- [isValidationErrorLike(error)](#isvalidationerrorlike)\n- [isZodErrorLike(error)](#iszoderrorlike)\n- [fromError(error[, options])](#fromerror)\n- [fromZodIssue(zodIssue[, options])](#fromzodissue)\n- [fromZodError(zodError[, options])](#fromzoderror)\n- [toValidationError([options]) => (error) => ValidationError](#tovalidationerror)\n\n### ValidationError\n\nMain `ValidationError` class, extending native JavaScript `Error`.\n\n#### Arguments\n\n- `message` - _string_; error message (required)\n- `options` - _ErrorOptions_; error options as per [JavaScript definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#options) (optional)\n  - `options.cause` - _any_; can be used to hold the original zod error (optional)\n\n#### Example 1: construct new ValidationError with `message`\n\n```typescript\nconst { ValidationError } = require('zod-validation-error');\n\nconst error = new ValidationError('foobar');\nconsole.log(error instanceof Error); // prints true\n```\n\n#### Example 2: construct new ValidationError with `message` and `options.cause`\n\n```typescript\nimport { z as zod } from 'zod';\nconst { ValidationError } = require('zod-validation-error');\n\nconst error = new ValidationError('foobar', {\n  cause: new zod.ZodError([\n    {\n      code: 'invalid_string',\n      message: 'Invalid email',\n      path: ['email'],\n      validation: 'email',\n    },\n  ]),\n});\n\nconsole.log(error.details); // prints issues from zod error\n```\n\n### createMessageBuilder\n\nCreates zod-validation-error's default `MessageBuilder`, which is used to produce user-friendly error messages.\n\nMeant to be passed as an option to [fromError](#fromerror), [fromZodIssue](#fromzodissue), [fromZodError](#fromzoderror) or [toValidationError](#tovalidationerror).\n\nYou may read more on the concept of the `MessageBuilder` further [below](#MessageBuilder).\n\n#### Arguments\n\n- `props` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\n#### Example\n\n```typescript\nimport { createMessageBuilder } from 'zod-validation-error';\n\nconst messageBuilder = createMessageBuilder({\n  includePath: false,\n  maxIssuesInMessage: 3\n});\n```\n\n### errorMap\n\nA custom error map to use with zod's `setErrorMap` method and get user-friendly messages automatically.\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod';\nimport { errorMap } from 'zod-validation-error';\n\nzod.setErrorMap(errorMap);\n```\n\n### isValidationError\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on `instanceof` comparison.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod';\nimport { ValidationError, isValidationError } from 'zod-validation-error';\n\nconst err = new ValidationError('foobar');\nisValidationError(err); // returns true\n\nconst invalidErr = new Error('foobar');\nisValidationError(err); // returns false\n```\n\n### isValidationErrorLike\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.\n\n_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod-validation-error` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.\n\ntl;dr if you are uncertain then it is preferable to use `isValidationErrorLike` instead of `isValidationError`.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { ValidationError, isValidationErrorLike } from 'zod-validation-error';\n\nconst err = new ValidationError('foobar');\nisValidationErrorLike(err); // returns true\n\nconst invalidErr = new Error('foobar');\nisValidationErrorLike(err); // returns false\n```\n\n### isZodErrorLike\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.\n\n_Why do we need heuristics since we can use a simple `instanceof` comparison?_ Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older `zod` version internally. In such case, the `instanceof` comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod';\nimport { ValidationError, isZodErrorLike } from 'zod-validation-error';\n\nconst zodValidationErr = new ValidationError('foobar');\nisZodErrorLike(zodValidationErr); // returns false\n\nconst genericErr = new Error('foobar');\nisZodErrorLike(genericErr); // returns false\n\nconst zodErr = new zod.ZodError([\n  {\n    code: zod.ZodIssueCode.custom,\n    path: [],\n    message: 'foobar',\n    fatal: true,\n  },\n]);\nisZodErrorLike(zodErr); // returns true\n```\n\n### fromError\n\nConverts an error to `ValidationError`.\n\n_What is the difference between `fromError` and `fromZodError`?_ The `fromError` function is a less strict version of `fromZodError`. It can accept an unknown error and attempt to convert it to a `ValidationError`.\n\n#### Arguments\n\n- `error` - _unknown_; an error (required)\n- `options` - _Object_; formatting options (optional)\n  - `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).\n\n#### Notes\n\nAlternatively, you may pass the following `options` instead of a `messageBuilder`.\n\n- `options` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\nThey will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.\n\n### fromZodIssue\n\nConverts a single zod issue to `ValidationError`.\n\n#### Arguments\n\n- `zodIssue` - _zod.ZodIssue_; a ZodIssue instance (required)\n- `options` - _Object_; formatting options (optional)\n  - `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).\n\n#### Notes\n\nAlternatively, you may pass the following `options` instead of a `messageBuilder`.\n\n- `options` - _Object_; formatting options (optional)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\nThey will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.\n\n### fromZodError\n\nConverts zod error to `ValidationError`.\n\n_Why is the difference between `ZodError` and `ZodIssue`?_ A `ZodError` is a collection of 1 or more `ZodIssue` instances. It's what you get when you call `zodSchema.parse()`.\n\n#### Arguments\n\n- `zodError` - _zod.ZodError_; a ZodError instance (required)\n- `options` - _Object_; formatting options (optional)\n  - `messageBuilder` - _MessageBuilder_; a function that accepts an array of `zod.ZodIssue` objects and returns a user-friendly error message in the form of a `string` (optional).\n\n#### Notes\n\nAlternatively, you may pass the following `options` instead of a `messageBuilder`.\n\n- `options` - _Object_; formatting options (optional)\nuser-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\nThey will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.\n\n### toValidationError\n\nA curried version of `fromZodError` meant to be used for FP (Functional Programming). Note it first takes the options object if needed and returns a function that converts the `zodError` to a `ValidationError` object\n\n```js\ntoValidationError(options) => (zodError) => ValidationError\n```\n\n#### Example using fp-ts\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod';\nimport { toValidationError, ValidationError } from 'zod-validation-error';\n\n// create zod schema\nconst zodSchema = zod\n  .object({\n    id: zod.number().int().positive(),\n    email: zod.string().email(),\n  })\n  .brand<'User'>();\n\nexport type User = zod.infer<typeof zodSchema>;\n\nexport function parse(\n  value: zod.input<typeof zodSchema>\n): Either.Either<ValidationError, User> {\n  return Either.tryCatch(() => schema.parse(value), toValidationError());\n}\n```\n\n## MessageBuilder\n\n`zod-validation-error` can be configured with a custom `MessageBuilder` function in order to produce case-specific error messages.\n\n#### Example\n\nFor instance, one may want to print `invalid_string` errors to the console in red color.\n\n```typescript\nimport { z as zod } from 'zod';\nimport { type MessageBuilder, fromError } from 'zod-validation-error';\nimport chalk from 'chalk';\n\n// create custom MessageBuilder\nconst myMessageBuilder: MessageBuilder = (issues) => {\n  return issues\n    // format error message\n    .map((issue) => {\n      if (issue.code === zod.ZodIssueCode.invalid_string) {\n        return chalk.red(issue.message);\n      }\n\n      return issue.message;\n    })\n    // join as string with new-line character\n    .join('\\n');\n}\n\n// create zod schema\nconst zodSchema = zod.object({\n  id: zod.number().int().positive(),\n  email: zod.string().email(),\n});\n\n// parse some invalid value\ntry {\n  zodSchema.parse({\n    id: 1,\n    email: 'foobar', // note: invalid email value\n  });\n} catch (err) {\n  const validationError = fromError(err, {\n    messageBuilder: myMessageBuilder\n  });\n  // the error is now displayed with red letters\n  console.log(validationError.toString());\n}\n\n```\n\n## FAQ\n\n### How to distinguish between errors\n\nUse the `isValidationErrorLike` type guard.\n\n#### Example\n\nScenario: Distinguish between `ValidationError` VS generic `Error` in order to respond with 400 VS 500 HTTP status code respectively.\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod';\nimport { isValidationErrorLike } from 'zod-validation-error';\n\ntry {\n  func(); // throws Error - or - ValidationError\n} catch (err) {\n  if (isValidationErrorLike(err)) {\n    return 400; // Bad Data (this is a client error)\n  }\n\n  return 500; // Server Error\n}\n```\n\n### How to use `ValidationError` outside `zod`\n\nIt's possible to implement custom validation logic outside `zod` and throw a `ValidationError`.\n\n#### Example 1: passing custom message\n\n```typescript\nimport { ValidationError } from 'zod-validation-error';\nimport { Buffer } from 'node:buffer';\n\nfunction parseBuffer(buf: unknown): Buffer {\n  if (!Buffer.isBuffer(buf)) {\n    throw new ValidationError('Invalid argument; expected buffer');\n  }\n\n  return buf;\n}\n```\n\n#### Example 2: passing custom message and original error as cause\n\n```typescript\nimport { ValidationError } from 'zod-validation-error';\n\ntry {\n  // do something that throws an error\n} catch (err) {\n  throw new ValidationError('Something went deeply wrong', { cause: err });\n}\n```\n\n### How to use `ValidationError` with custom \"error map\"\n\nZod supports customizing error messages by providing a custom \"error map\". You may combine this with `zod-validation-error` to produce user-friendly messages.\n\n#### Example 1: produce user-friendly error messages using the `errorMap` property\n\nIf all you need is to produce user-friendly error messages you may use the `errorMap` property.\n\n```typescript\nimport { z as zod } from 'zod';\nimport { errorMap } from 'zod-validation-error';\n\nzod.setErrorMap(errorMap);\n```\n\n#### Example 2: extra customization using `fromZodIssue`\n\nIf you need to customize some error code, you may use the `fromZodIssue` function.\n\n```typescript\nimport { z as zod } from 'zod';\nimport { fromZodIssue } from 'zod-validation-error';\n\nconst customErrorMap: zod.ZodErrorMap = (issue, ctx) => {\n  switch (issue.code) {\n    case ZodIssueCode.invalid_type: {\n      return {\n        message:\n          'Custom error message of your preference for invalid_type errors',\n      };\n    }\n    default: {\n      const validationError = fromZodIssue({\n        ...issue,\n        // fallback to the default error message\n        // when issue does not have a message\n        message: issue.message ?? ctx.defaultError,\n      });\n\n      return {\n        message: validationError.message,\n      };\n    }\n  }\n};\n\nzod.setErrorMap(customErrorMap);\n```\n\n### How to use `zod-validation-error` with `react-hook-form`?\n\n```typescript\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { errorMap } from 'zod-validation-error';\n\nuseForm({\n  resolver: zodResolver(schema, { errorMap }),\n});\n```\n\n### Does `zod-validation-error` support CommonJS\n\nYes, `zod-validation-error` supports CommonJS out-of-the-box. All you need to do is import it using `require`.\n\n#### Example\n\n```typescript\nconst { ValidationError } = require('zod-validation-error');\n```\n\n## Contribute\n\nSource code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.\n\n#### We are hiring\n\nCausaly is building the world's largest biomedical knowledge platform, using technologies such as TypeScript, React and Node.js. Find out more about our openings at https://apply.workable.com/causaly/.\n\n## License\n\nMIT\n","publish_time":1726469045552,"maintainers":[{"name":"nikoskalogridis","email":"nikos.kalogridis@gmail.com"},{"name":"dnlytras","email":"dnlytras@gmail.com"},{"name":"jmike","email":"dimitris@jmike.gr"},{"name":"thanoskrg","email":"hey@maestros.io"}],"_cnpm_publish_time":1726469045552,"dist-tags":{"beta":"4.0.0-beta.2","latest":"5.0.0"}}