Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
name: CI

on:
push:
branches:
- main
- dev
pull_request:

jobs:
build_and_test:
runs-on: ubuntu-latest
name: Build and Test
steps:
- name: Checkout code
uses: actions/checkout@v5

- uses: pnpm/action-setup@v4
with:
version: 9

- name: Read .nvmrc
run: echo ::set-output name=NVMRC::$(cat .nvmrc)
id: nvm

- name: Set up Node.js environment
uses: actions/setup-node@v5
with:
node-version: '${{ steps.nvm.outputs.NVMRC }}'

- name: Install pnpm
run: npm install -g pnpm

- name: Install dependencies
run: pnpm install

- name: Run lint
run: pnpm lint

- name: Run tests with coverage
run: pnpm test:coverage
env:
FORCE_COLOR: true

- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}

- name: Build project
run: pnpm build

- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release

2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

.idea/

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
Expand Down
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
22.19.0
80 changes: 80 additions & 0 deletions .releaserc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
{
"branches": [{ "name": "main" }, { "name": "dev", "prerelease": true }],
"ci": true,
"plugins": [
[
"@semantic-release/commit-analyzer",
{
"releaseRules": [
{ "message": "*[release]*", "release": "patch" },
{ "breaking": true, "release": "major" },
{ "revert": true, "release": "patch" },
{ "type": "feat", "release": "minor" },
{ "type": "fix", "release": "patch" },
{ "type": "perf", "release": "patch" },
{ "emoji": ":racehorse:", "release": "patch" },
{ "emoji": ":bug:", "release": "patch" },
{ "emoji": ":penguin:", "release": "patch" },
{ "emoji": ":apple:", "release": "patch" },
{ "emoji": ":checkered_flag:", "release": "patch" },
{ "tag": "BUGFIX", "release": "patch" },
{ "tag": "FEATURE", "release": "minor" },
{ "tag": "SECURITY", "release": "patch" },
{ "tag": "Breaking", "release": "major" },
{ "tag": "Fix", "release": "patch" },
{ "tag": "Update", "release": "minor" },
{ "tag": "New", "release": "minor" },
{ "component": "perf", "release": "patch" },
{ "component": "deps", "release": "patch" },
{ "type": "FEAT", "release": "minor" },
{ "type": "FIX", "release": "patch" }
]
}
],
[
"@semantic-release/release-notes-generator",
{
"preset": "conventionalCommits",
"parserOpts": {
"noteKeywords": ["BREAKING CHANGE", "BREAKING CHANGES", "BREAKING"]
},
"presetConfig": {
"types": [
{
"type": "feat",
"section": "Features ✨"
},
{
"type": "fix",
"section": "Bug Fixes \uD83D\uDC1E"
},
{
"type": "chore",
"section": "Internal \uD83E\uDDF0",
"hidden": true
},
{
"type": "refactor",
"section": "Internal \uD83E\uDDF0",
"hidden": false
},
{
"type": "perf",
"section": "Internal \uD83E\uDDF0",
"hidden": false
}
]
}
}
],
"@semantic-release/npm",
"@semantic-release/github",
[
"@semantic-release/git",
{
"assets": ["CHANGELOG.md", "package.json"],
"message": "chore(📦): ${nextRelease.version}\n\n${nextRelease.notes}"
}
]
]
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Sophia <me@sophia-dev.io>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
182 changes: 182 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<h1 align="center">
<br />
💎
<br />
better-zod-errors
<sup>
<br />
<br />
</sup>
</h1>

<div align="center">
<a href="https://github.com/async3619/better-zod-errors/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/async3619/better-zod-errors?style=flat-square" alt="MIT License" />
</a>
<a href="https://codecov.io/gh/async3619/better-zod-errors">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/async3619/better-zod-errors?style=flat-square">
</a>
<a href="https://www.npmjs.com/package/better-zod-errors">
<img alt="npm" src="https://img.shields.io/npm/v/better-zod-errors?style=flat-square" />
</a>
<br />
<sup>formatted and more descriptive error messages for Zod validation</sup>
<br />
<br />
</div>

## Introduction

This library provides set of functions to format and enhance error messages generated by [Zod](https://zod.dev/) with code frames.

## Installation

```bash
$ npm install better-zod-errors
# or
$ yarn add better-zod-errors
# or
$ pnpm add better-zod-errors
```

## Usage

This library provides two main functions to format Zod errors with code frames:

### JSON Format

You can format JSON data validation errors using the `formatJsonError` function:

```typescript
import { z } from "zod";
import { formatJsonError } from "better-zod-errors";

const schema = z.object({
name: z.string().min(2, "Name must be at least 2 characters long"),
age: z.number().min(0, "Age must be a positive number"),
});

const payload = {
name: "A",
age: -5,
};

try {
schema.parse(payload);
} catch (e) {
if (e instanceof z.ZodError) {
for (const issue of e.issues) {
const formattedError = formatJsonError(issue, payload);
console.log(formattedError); // formatted error message with code frame
}
} else {
// handle other errors
}
}
```

### YAML Format

You can also format YAML data validation errors using the `formatYamlError` function:

```typescript
import { z } from "zod";
import { formatYamlError } from "better-zod-errors";

const schema = z.object({
name: z.string().min(2, "Name must be at least 2 characters long"),
age: z.number().min(0, "Age must be a positive number"),
address: z.object({
street: z.string(),
city: z.string(),
}),
});

const payload = {
name: "John",
age: -5,
address: {
street: "123 Main St",
city: 456, // Invalid type
},
};

try {
schema.parse(payload);
} catch (e) {
if (e instanceof z.ZodError) {
for (const issue of e.issues) {
const formattedError = formatYamlError(issue, payload);
console.log(formattedError); // formatted YAML error message with code frame
}
} else {
// handle other errors
}
}
```

## API

### `formatJsonError(issue: z.ZodIssue, data: any, [options: FormatJsonErrorOptions]): string`

Formats a single Zod issue into a more readable error message with a code frame.

#### `issue`

Type: `z.ZodIssue`

The Zod issue to format thrown during validation with `ZodError`.

#### `data`

Type: `any`

The original data that was validated. If the data was not matched with the original structure, it may throw an error.

#### `options`

Type: `FormatJsonErrorOptions` (optional)

##### `useColor`

Type: `boolean` (default: `true`)

Whether to use ANSI colors in the output. Set to `false` to disable colors.

##### `syntaxHighlighting`

Type: `boolean` (default: `true`)

Whether to use syntax highlighting in the code frame. Set to `false` to disable syntax highlighting.

### `formatYamlError(issue: z.ZodIssue, payload: any, [options: FormatYamlErrorOptions]): string`

Formats a single Zod issue into a more readable error message with a YAML code frame.

#### `issue`

Type: `z.ZodIssue`

The Zod issue to format thrown during validation with `ZodError`.

#### `payload`

Type: `number | bigint | boolean | string | object`

The original data that was validated in YAML format. The function will serialize this data to YAML and create a source map to locate error positions.

#### `options`

Type: `FormatYamlErrorOptions` (optional)

##### `useColor`

Type: `boolean` (default: `true`)

Whether to use ANSI colors in the output. Set to `false` to disable colors.

##### `syntaxHighlighting`

Type: `boolean` (default: `true`)

Whether to use syntax highlighting in the YAML code frame. Set to `false` to disable syntax highlighting.
3 changes: 2 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false
"ignoreUnknown": false,
"includes": ["**", "!dist/", "!node_modules/", "!coverage/"]
},
"formatter": {
"enabled": true,
Expand Down
13 changes: 13 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createDefaultPreset } from 'ts-jest'

const tsJestTransformCfg = createDefaultPreset().transform

const config: import('jest').Config = {
testEnvironment: 'node',
testMatch: ['**/*.spec.ts'],
transform: {
...tsJestTransformCfg,
},
}

export default config
Loading
Loading