npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

json-schema-contract-compiler

v0.1.0

Published

JSON Schema contract compiler - generates TypeScript types and validators

Downloads

6

Readme

json-schema-contract-compiler

A JSON Schema contract compiler that generates TypeScript types and validators at build time.

Why?

Traditional schema validation libraries interpret schemas at runtime. This compiler takes a different approach: compile once, import types, call a function.

| Approach | Bundle Size | Runtime Cost | Type Safety | |----------|-------------|--------------|-------------| | Runtime (Zod, Ajv) | Library + schema | Parse + validate | Inferred | | Compile-time | Generated code only | Validate only | Generated |

The result is near-zero runtime overhead, fast TypeScript builds, and small bundles.

Installation

npm install json-schema-contract-compiler

Quick Start

1. Create a JSON Schema

// schemas/user.json
{
  "$id": "User",
  "type": "object",
  "properties": {
    "id": { "type": "string" },
    "email": { "type": "string", "format": "email" },
    "age": { "type": "integer", "minimum": 0 }
  },
  "required": ["id", "email"]
}

2. Compile

npx jsc compile -o ./generated ./schemas/user.json

3. Use the Generated Code

import type { User } from './generated/user';
import { isUser, parseUser } from './generated/user.js';

// Type guard (returns boolean)
if (isUser(data)) {
  console.log(data.email); // TypeScript knows this is valid
}

// Parser (throws on invalid input)
try {
  const user = parseUser(data);
  console.log(user.email);
} catch (err) {
  console.error(err.path, err.message);
}

CLI Reference

jsc compile [options] <files...>

Options:
  -o, --out-dir <dir>    Output directory (required)
  -e, --emit <what>      What to emit: types, validators, all (default: all)
  -m, --module <format>  Module format: esm, cjs (default: esm)
  -s, --strict           Error on unsupported keywords
  -v, --verbose          Verbose output
  -w, --watch            Watch mode

Examples

# Compile all schemas in a directory
jsc compile -o ./generated ./schemas/*.json

# Generate only TypeScript types
jsc compile -o ./types --emit types ./schemas/user.json

# Generate CommonJS modules
jsc compile -o ./dist -m cjs ./schemas/*.json

# Watch mode for development
jsc compile -o ./generated -w ./schemas/*.json

Generated Output

For each schema file, the compiler generates:

| File | Contents | |------|----------| | <name>.d.ts | TypeScript type definitions | | <name>.js | isX() type guards + parseX() parsers |

Type Guards (isX)

Fast boolean checks that return true if valid, false otherwise.

function isUser(value: unknown): value is User

Parsers (parseX)

Validators that return the typed value or throw ValidationError.

function parseUser(value: unknown): User

The ValidationError includes structured information:

{
  message: "/email: Invalid email format",
  path: "/email",
  expected: "email",
  received: "not-an-email"
}

Supported JSON Schema Features

Types

  • string, number, integer, boolean, null, object, array
  • Type unions: { "type": ["string", "null"] }

String Constraints

  • minLength, maxLength
  • pattern (regex)
  • format: email, uuid, date-time, date, time, uri, hostname, ipv4, ipv6

Number Constraints

  • minimum, maximum
  • exclusiveMinimum, exclusiveMaximum
  • multipleOf

Object Constraints

  • properties, required
  • additionalProperties (boolean or schema)

Array Constraints

  • items (single schema for all items)
  • prefixItems (tuple validation)
  • minItems, maxItems

Composition

  • oneOf (discriminated unions supported via x-discriminator)
  • enum, const

References

  • $ref (local references only: #/$defs/Name)
  • $defs / definitions

Extensions

x-brand

Create branded/opaque types:

{
  "type": "string",
  "x-brand": "UserId"
}

Generates: string & { readonly __brand: "UserId" }

x-discriminator

Optimize union validation with a discriminator property:

{
  "oneOf": [
    { "properties": { "type": { "const": "dog" }, "bark": { "type": "boolean" } } },
    { "properties": { "type": { "const": "cat" }, "meow": { "type": "boolean" } } }
  ],
  "x-discriminator": "type"
}

x-coerce

Enable type coercion in parsers:

{
  "type": "number",
  "x-coerce": true
}

With coercion, parseX("42") returns 42 instead of throwing.

x-doc

Add JSDoc comments to generated types:

{
  "type": "string",
  "x-doc": "The user's unique identifier"
}

Runtime Library

The package exports a minimal runtime library for advanced use cases:

import {
  ValidationError,
  registerRefinement,
  refine,
  isEmail,
  isUUID,
  // ... other format validators
} from 'json-schema-contract-compiler';

Custom Refinements

Register custom validation logic:

import { registerRefinement } from 'json-schema-contract-compiler';

registerRefinement('positiveNumber', (value) => {
  return typeof value === 'number' && value > 0;
});

Then use in your schema:

{
  "type": "number",
  "x-refinement": "positiveNumber"
}

Comparison with Alternatives

| Feature | json-schema-contract-compiler | Zod | Ajv | |---------|-----------------|-----|-----| | Runtime overhead | Minimal | Medium | Low | | Bundle size impact | ~0 (generated) | ~12KB | ~30KB | | TypeScript types | Generated | Inferred | Separate | | Schema format | JSON Schema | Custom DSL | JSON Schema | | Build step required | Yes | No | No |

License

MIT