chatgpt-api/packages/json-schema
Travis Fischer bc2c1e34fd chore: release v8.4.2 2025-07-03 06:20:43 -05:00
..
src 😱 2025-06-05 18:52:11 +07:00
test fix: improve json-schema test robustness 2025-06-24 23:00:49 -05:00
license feat: more refactoring work 2025-06-28 23:39:23 -05:00
package.json chore: release v8.4.2 2025-07-03 06:20:43 -05:00
readme.md fix: make readme images fully qualified urls so npm readmes don't 404 on them 2025-06-30 12:59:49 -05:00
tsconfig.json feat: refactor hono middleware to separate package; lots of work on gateway 2025-06-04 22:54:28 +07:00

readme.md

Agentic

Build Status NPM Prettier Code Formatting

[!NOTE] This package is a fork of @cfworker/json-schema which adds support for ajv-style type coercion. Coercion is disabled by default, but can be enabled with a boolean flag.

@agentic/json-schema

A JSON schema validator that will run on Cloudflare workers. Supports drafts 4, 7, 2019-09, and 2020-12.

This library is validated against the json-schema-test-suite, a series of approximately 4,500 assertions maintained along with the json-schema specification. A small set of test cases are intentionally not supported due to performance constraints or lack of feature use. These list of unsupported features are maintained in test/unsupported.ts. While this library is not the fastest due to lack of code generation, it's consistently among the most spec compliant.

Background

Why another JSON schema validator?

Cloudflare workers do not have APIs required by Ajv schema compilation (eval or new Function(code)). If possible use Ajv in a build step to precompile your schema. Otherwise this library could work for you.

Basic usage

import { Validator } from '@cfworker/json-schema'

const validator = new Validator({ type: 'number' })

const result = validator.validate(7)

Specify meta schema draft

const validator = new Validator({ type: 'number' }, '4') // draft-4

Add schemas

const validator = new Validator({
  $id: 'https://foo.bar/baz',
  $ref: '/beep'
})

validator.addSchema({ $id: 'https://foo.bar/beep', type: 'boolean' })

Include all errors

By default the validator stops processing after the first error. Set the shortCircuit parameter to false to emit all errors.

const shortCircuit = false;

const draft = '2019-09';

const schema = {
  type: 'object',
  required: ['name', 'email', 'number', 'bool'],
  properties: {
    name: { type: 'string' },
    email: { type: 'string', format: 'email' },
    number: { type: 'number' },
    bool: { type: 'boolean' }
  }
};

const validator = new Validator(schema, draft, shortCircuit);

const result = validator.validate({
  name: 'hello',
  email: 5, // invalid type
  number: 'Hello' // invalid type
  bool: 'false' // invalid type
});