contributing-to-z-schema

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Contributing to z-schema

为z-schema做贡献

z-schema is a JSON Schema validator (draft-04 through draft-2020-12) written in TypeScript. This skill covers the development workflow, codebase navigation, and common contribution tasks.
z-schema是一款用TypeScript编写的JSON Schema验证器(支持draft-04到draft-2020-12版本)。本指南涵盖开发工作流、代码库导航和常见贡献任务。

Repository setup

仓库设置

bash
git clone --recursive https://github.com/zaggino/z-schema.git
cd z-schema
npm install
If already cloned without
--recursive
(needed for the
json-schema-spec/
submodule):
bash
git submodule update --init --recursive
bash
git clone --recursive https://github.com/zaggino/z-schema.git
cd z-schema
npm install
如果克隆时未添加
--recursive
参数(拉取
json-schema-spec/
子模块需要该参数),请执行以下命令:
bash
git submodule update --init --recursive

Quality checks

质量检查

Run all checks before pushing:
bash
npm run lint:check      # ESLint
npm run format:check    # Prettier
npm run build           # TypeScript + Rollup
npm run build:tests     # Type-check tests
npm test                # Vitest (node + browser)
Pre-commit hooks auto-run lint + format on staged files. Pre-push hooks run build + type-check.
推送代码前请运行所有检查:
bash
npm run lint:check      # ESLint
npm run format:check    # Prettier
npm run build           # TypeScript + Rollup
npm run build:tests     # 测试用例类型检查
npm test                # Vitest (node + browser)
预提交钩子会自动对暂存文件执行lint和格式检查。预推送钩子会执行构建和类型检查。

Codebase map

代码库结构

src/
  index.ts              → Public API (all exports)
  z-schema.ts           → Factory + ZSchema/ZSchemaSafe/ZSchemaAsync/ZSchemaAsyncSafe
  z-schema-base.ts      → Core validation orchestration
  schema-compiler.ts    → $ref resolution, id collection, schema compilation
  schema-validator.ts   → Schema-level validation against meta-schemas
  json-validation.ts    → Instance validation (type, constraints, combiners)
  schema-cache.ts       → Schema caching by URI/id
  errors.ts             → Error codes (Errors object) + ValidateError class
  format-validators.ts  → Built-in + custom format validators
  report.ts             → Error accumulation (Report, SchemaErrorDetail)
  json-schema.ts        → Common JSON Schema definitions + helpers
  json-schema-versions.ts → Draft-specific type unions + version mappings
  z-schema-options.ts   → Options interface + defaults + normalizeOptions
  z-schema-reader.ts    → Schema reader type
  z-schema-versions.ts  → Registers bundled meta-schemas into cache
  utils/                → Pure utilities (array, clone, json, uri, etc.)
  schemas/              → Bundled meta-schemas (generated at build time)
src/
  index.ts              → 公共API(所有导出内容)
  z-schema.ts           → 工厂函数 + ZSchema/ZSchemaSafe/ZSchemaAsync/ZSchemaAsyncSafe类
  z-schema-base.ts      → 核心验证编排逻辑
  schema-compiler.ts    → $ref解析、id收集、Schema编译
  schema-validator.ts   → 基于元Schema的Schema层级验证
  json-validation.ts    → 实例验证(类型、约束、组合器)
  schema-cache.ts       → 按URI/id缓存Schema
  errors.ts             → 错误码(Errors对象) + ValidateError类
  format-validators.ts  → 内置 + 自定义格式验证器
  report.ts             → 错误归集(Report, SchemaErrorDetail)
  json-schema.ts        → 通用JSON Schema定义 + 工具函数
  json-schema-versions.ts → 版本专属类型联合 + 版本映射
  z-schema-options.ts   → 配置项接口 + 默认值 + normalizeOptions方法
  z-schema-reader.ts    → Schema读取器类型
  z-schema-versions.ts  → 将打包的元Schema注册到缓存中
  utils/                → 纯工具函数(数组、克隆、json、uri等)
  schemas/              → 打包的元Schema(构建时生成)

Validation pipeline

验证流水线

  1. Schema compilation (
    schema-compiler.ts
    ): resolves
    $ref
    , collects
    id
    /
    $id
    , registers in cache
  2. Schema validation (
    schema-validator.ts
    ): validates schema against its meta-schema
  3. JSON validation (
    json-validation.ts
    ): validates data against compiled schema — type checks, constraints, combiners (
    allOf
    /
    anyOf
    /
    oneOf
    /
    not
    ),
    unevaluated*
    tracking, format checks
  4. Report (
    report.ts
    ): errors accumulate in a
    Report
    , then convert to
    ValidateError
  1. Schema编译
    schema-compiler.ts
    ):解析
    $ref
    、收集
    id
    /
    $id
    、注册到缓存
  2. Schema验证
    schema-validator.ts
    ):基于对应元Schema验证Schema本身合法性
  3. JSON验证
    json-validation.ts
    ):基于编译后的Schema验证数据 — 类型检查、约束校验、组合器(
    allOf
    /
    anyOf
    /
    oneOf
    /
    not
    )逻辑、
    unevaluated*
    追踪、格式校验
  4. 报告生成
    report.ts
    ):错误归集到
    Report
    对象,之后转换为
    ValidateError

Common tasks

常见任务

Adding a new error code

新增错误码

  1. Add the error to the
    Errors
    object in
    src/errors.ts
    :
    typescript
    MY_NEW_ERROR: 'Description with {0} placeholder',
  2. Use
    report.addError('MY_NEW_ERROR', [param])
    in the validation logic.
  3. Write tests verifying the error code is produced.
  1. src/errors.ts
    Errors
    对象中添加新错误:
    typescript
    MY_NEW_ERROR: 'Description with {0} placeholder',
  2. 在验证逻辑中使用
    report.addError('MY_NEW_ERROR', [param])
    抛出该错误。
  3. 编写测试用例验证错误码可以正常触发。

Adding a new format validator

新增格式验证器

  1. Write the validator function in
    src/format-validators.ts
    :
    typescript
    const myFormatValidator: FormatValidatorFn = (input: unknown) => {
      if (typeof input !== 'string') return true;
      return /^pattern$/.test(input);
    };
  2. Register it in the
    inbuiltValidators
    record:
    typescript
    const inbuiltValidators = {
      // ...existing
      'my-format': myFormatValidator,
    };
  3. Add tests in
    test/spec/format-validators.spec.ts
    .
  1. src/format-validators.ts
    中编写验证函数:
    typescript
    const myFormatValidator: FormatValidatorFn = (input: unknown) => {
      if (typeof input !== 'string') return true;
      return /^pattern$/.test(input);
    };
  2. inbuiltValidators
    对象中注册该验证器:
    typescript
    const inbuiltValidators = {
      // ...现有验证器
      'my-format': myFormatValidator,
    };
  3. test/spec/format-validators.spec.ts
    中添加测试用例。

Adding a new option

新增配置项

  1. Add the option to
    ZSchemaOptions
    in
    src/z-schema-options.ts
    .
  2. Add a default value in
    defaultOptions
    .
  3. If the option is part of
    strictMode
    , add it to the
    strictMode
    block in
    normalizeOptions
    .
  4. Document it in
    docs/options.md
    .
  5. Write tests.
  1. src/z-schema-options.ts
    ZSchemaOptions
    接口中添加新配置项。
  2. defaultOptions
    中添加默认值。
  3. 如果该配置项属于
    strictMode
    的一部分,在
    normalizeOptions
    strictMode
    代码块中添加对应逻辑。
  4. docs/options.md
    中添加配置项说明。
  5. 编写测试用例。

Implementing a new JSON Schema keyword

实现新的JSON Schema关键字

  1. Add validation logic in
    src/json-validation.ts
    (for data validation) or
    src/schema-validator.ts
    (for schema-level validation).
  2. Guard with a draft version check if the keyword is draft-specific.
  3. Remove relevant entries from
    excludedFiles
    /
    excludedTests
    in
    test/spec/json-schema-test-suite.common.ts
    .
  4. Run the JSON Schema Test Suite to confirm compliance:
    bash
    npx vitest run --silent=false --project node -t "draft2020-12/newKeyword"
  5. Export any new types through
    src/index.ts
    .
  1. src/json-validation.ts
    (数据验证逻辑)或
    src/schema-validator.ts
    (Schema层级验证逻辑)中添加验证逻辑。
  2. 如果关键字是特定draft版本专属,添加版本检查逻辑。
  3. test/spec/json-schema-test-suite.common.ts
    excludedFiles
    /
    excludedTests
    中移除相关条目。
  4. 运行JSON Schema测试套件验证合规性:
    bash
    npx vitest run --silent=false --project node -t "draft2020-12/newKeyword"
  5. 通过
    src/index.ts
    导出所有新增类型。

Modifying existing behavior

修改现有行为

  1. Find the relevant module using the codebase map above.
  2. Make changes following code conventions (see below).
  3. Run the full test suite — regressions often appear in other drafts.
  1. 参考上方的代码库结构找到对应模块。
  2. 遵循代码规范进行修改(见下文)。
  3. 运行完整测试套件 — 经常会在其他版本的draft中出现回归问题。

Test framework

测试框架

  • Vitest with
    globals: true
    .
  • Two projects: node and browser (Playwright: Chromium, Firefox, WebKit).
  • Tests live in
    test/spec/
    .
  • 采用Vitest,开启
    globals: true
    配置
  • 包含两个测试项目:nodebrowser(Playwright驱动:Chromium、Firefox、WebKit)
  • 测试用例存放于
    test/spec/
    目录

File naming

文件命名规则

SuffixRuns in
*.spec.ts
Both node and browser
*.node-spec.ts
Node only
*.browser-spec.ts
Browser only
后缀运行环境
*.spec.ts
Node和浏览器环境都运行
*.node-spec.ts
仅Node环境运行
*.browser-spec.ts
仅浏览器环境运行

Running tests

运行测试

bash
npm test                                                        # all
npm run test:node                                               # node only
npx vitest run --silent=false --project node -t "draft4/type"   # single test
npm run test:coverage                                           # coverage
bash
npm test                                                        # 运行所有测试
npm run test:node                                               # 仅运行Node端测试
npx vitest run --silent=false --project node -t "draft4/type"   # 运行单个测试用例
npm run test:coverage                                           # 生成测试覆盖率报告

Test pattern

测试写法示例

typescript
import { ZSchema } from '../../src/z-schema.ts';

describe('Feature Name', () => {
  it('should accept valid data', () => {
    const validator = ZSchema.create();
    expect(validator.validate('hello', { type: 'string' })).toBe(true);
  });

  it('should reject invalid data', () => {
    const validator = ZSchema.create();
    const { valid, err } = validator.validateSafe(42, { type: 'string' });
    expect(valid).toBe(false);
    expect(err?.details?.[0]?.code).toBe('INVALID_TYPE');
  });
});
typescript
import { ZSchema } from '../../src/z-schema.ts';

describe('Feature Name', () => {
  it('should accept valid data', () => {
    const validator = ZSchema.create();
    expect(validator.validate('hello', { type: 'string' })).toBe(true);
  });

  it('should reject invalid data', () => {
    const validator = ZSchema.create();
    const { valid, err } = validator.validateSafe(42, { type: 'string' });
    expect(valid).toBe(false);
    expect(err?.details?.[0]?.code).toBe('INVALID_TYPE');
  });
});

JSON Schema Test Suite

JSON Schema测试套件

Official test cases loaded via
test/spec/json-schema-test-suite.common.ts
. To enable tests for a newly implemented feature, remove entries from
excludedFiles
/
excludedTests
and confirm they pass.
官方测试用例通过
test/spec/json-schema-test-suite.common.ts
加载。如果要为新实现的功能启用测试,请从
excludedFiles
/
excludedTests
中移除对应条目并确认测试通过。

Code conventions

代码约定

  • TypeScript
    strict: true
    , ESM with
    .js
    import extensions in
    src/
  • .ts
    import extensions in
    test/
    (via
    allowImportingTsExtensions
    )
  • import type
    for type-only imports (enforced by ESLint)
  • Import order: type-only → side-effect → node builtins → packages → relative
  • Prettier: 120 char width, single quotes, trailing commas (es5), semicolons
  • Classes/types:
    PascalCase
    — functions/variables:
    camelCase
    — errors:
    UPPER_SNAKE_CASE
  • All public API exported through
    src/index.ts
  • Internal types stay unexported
  • Schemas in
    src/schemas/
    are generated by
    scripts/copy-schemas.mts
    — do not edit manually
  • json-schema-spec/
    is a git submodule — do not commit changes to it
  • TypeScript开启
    strict: true
    src/
    目录下ESM导入使用
    .js
    扩展名
  • test/
    目录下导入使用
    .ts
    扩展名(通过
    allowImportingTsExtensions
    配置支持)
  • 类型导入使用
    import type
    (由ESLint强制校验)
  • 导入顺序:类型导入 → 副作用导入 → Node内置模块 → 第三方依赖 → 相对路径导入
  • Prettier配置:120字符宽度、单引号、尾逗号(es5规则)、分号
  • 类/类型命名:
    PascalCase
    — 函数/变量命名:
    camelCase
    — 错误码命名:
    UPPER_SNAKE_CASE
  • 所有公共API通过
    src/index.ts
    导出
  • 内部类型不对外导出
  • src/schemas/
    下的Schema由
    scripts/copy-schemas.mts
    生成 — 请勿手动编辑
  • json-schema-spec/
    是git子模块 — 请勿提交对它的修改

PR checklist

PR检查清单

- [ ] Branch from `main`
- [ ] Changes follow code conventions
- [ ] npm run lint:check passes
- [ ] npm run format:check passes
- [ ] npm run build passes
- [ ] npm run build:tests passes
- [ ] npm test passes (node + browser)
- [ ] New public types/values exported through src/index.ts
- [ ] New features have tests
- [ ] docs/ updated if public API changed
- [ ] JSON Schema Test Suite entries un-excluded if applicable
- [ ] 从`main`分支创建开发分支
- [ ] 修改符合代码规范
- [ ] npm run lint:check 检查通过
- [ ] npm run format:check 检查通过
- [ ] npm run build 构建通过
- [ ] npm run build:tests 测试类型检查通过
- [ ] npm test 全部测试通过(Node + 浏览器端)
- [ ] 新增的公共类型/变量已通过src/index.ts导出
- [ ] 新功能已添加测试用例
- [ ] 若修改了公共API,已更新docs/目录下的文档
- [ ] 若适用,已取消对应JSON Schema测试套件条目的排除配置

Reference files

参考文件

  • references/architecture-details.md — Full module dependency diagram, factory pattern, build outputs, and internal types
  • references/architecture-details.md — 完整模块依赖图、工厂模式、构建输出和内部类型说明