@haddowg/json-api-codegen
Part of the jsonapi.rest suite — a complete, spec-compliant JSON:API 1.1 stack: a framework-agnostic PHP core, a Symfony bundle, a Laravel package, and this typed TypeScript client, bound together by one conformance-tested OpenAPI 3.1 contract. Full documentation: haddowg.github.io/json-api-ts.
The CLI (and programmatic API) that reads the
haddowg/json-api-symfony OpenAPI 3.1 document and
emits a typed client: a runtime descriptor, per-type attribute interfaces, and a descriptor-bound
createClient. Optionally reads the bundle's JSON Schemas to emit a per-type schema map for the
client's opt-in validation seam.
The OpenAPI document is fully self-describing for the runtime's needs — type identity
(properties.type.const), relationship cardinality and related types, the allowed ?include
paths (a bounded, pre-expanded enum per endpoint), the create client-id policy, and paginator
kinds. The codegen only reads the spec; all real work is generic runtime machinery in
@haddowg/json-api-client.
Install
A dev-only dependency — the generated output has no runtime tie back to the codegen (it imports
@haddowg/json-api-client).
pnpm add -D @haddowg/json-api-codegen
Two bin names are installed: json-api-codegen and the short alias japi.
The codegen reads documents of generator contracts 24 to 40 (info.x-generator.contract). A newer
document still generates, with a warning that the client may miss what the server added, and an
older one is refused: it describes its error codes in a form this codegen no longer reads.
Anything the server marks deprecated gets @deprecated TSDoc, so editors strike it through.
CLI
json-api-codegen --input <url|file> --output <file> [--server <name>] [--schemas <url|file>] [--examples] [--check]
| Flag | Required | Description |
|---|---|---|
--input | yes | OpenAPI document source — an http(s) URL or a local file path (JSON or YAML). |
--output | yes | Output file for the generated client (e.g. src/api/music.gen.ts). |
--server | no | Server name to target. Metadata-only — the served document is already per-server. |
--schemas | no | JSON Schema source (URL or path) for the validation seam. Omit to skip schema output. |
--examples | no | Also write the operations' worked examples to a sibling .examples.gen.ts module. |
--check | no | Drift gate — regenerate in memory and exit non-zero if the committed output differs. |
Example — generate against a served API, with the validation schemas:
json-api-codegen \
--input https://music.example/docs.json \
--output src/api/music.gen.ts \
--schemas https://music.example/schemas.json
This writes:
src/api/music.gen.ts— the typed client (descriptor + types + boundcreateClient);src/api/music.schemas.gen.ts— the per-type JSON Schema map (only with--schemas).src/api/music.examples.gen.ts— each operation's worked examples (only with--examples, and only when the document declares some).
The schema artifact path is derived from --output: a .gen.ts suffix becomes .schemas.gen.ts,
a plain .ts becomes .schemas.ts.
Commit the generated files. Like
openapi-typescript/graphql-codegen, the output is one small, reviewable, diffable, versioned module in your repo — not a published package. Regenerate when the API changes.
Provenance stamp
Every generated artifact carries a provenance record in its header — the source spec identifier
(<info.title> <info.version>), the first declared server URL, and a stable 16-hex content hash of
the source document (the schema artifact carries a Schema hash of the schema bundle). It is
timestamp-free and deterministic: regenerating from the same spec yields byte-identical output.
The hash tells a reviewer which spec a committed client was generated from, and lets the drift gate
below compare regenerated output byte-for-byte.
/**
* AUTO-GENERATED by @haddowg/json-api-codegen — do not edit by hand.
* Regenerate from the source OpenAPI document instead.
*
* Source spec: Music Catalog API 1.0.0
* Server: https://music.example
* Spec hash: 40e273dff0411f68
*/
Drift check (--check)
--check regenerates in memory and compares against the committed --output (and its schema
sibling when --schemas is set) without writing anything. It prints a per-artifact ok/DRIFT
line and exits non-zero if any committed file is missing or out of date. Wire it into CI — pinning
the spec to a committed fixture — so a stale generated client fails the build:
json-api-codegen \
--input spec/music-catalog.openapi.json \
--output src/api/music.gen.ts \
--schemas spec/music-catalog.schemas.json \
--check
Multiple servers
The bundle serves one OpenAPI document per server (e.g. default and admin differ in their
type set and path prefix). Generate one client per server by pointing --input at each server's
document — one typed client per server.
What it generates
The output module exports:
resourceMap— the runtime descriptor (as const); what the query package's normalization needs.ResourceMap—typeof resourceMap.createClient(options)— the descriptor-bound factory (the descriptor and the server'satomiccapability are baked in; you supply onlyClientOptions).Attributes/WriteAttributes— the per-type attribute maps (read vs create/update).- Per-type
…Attributes/…CreateAttributes/…UpdateAttributesinterfaces, enum types (e.g.AlbumStatus), named shapes (e.g.Reviewer), and action input/output types. Links— the typed declared links of each type that declares any.ErrorCodes/ErrorCode/ErrorCodeByStatus/ErrorCodeByOperation/ErrorMetaByCode/hasErrorCode/findError— the server's documented error codes, the codes only some operations raise, each code's typedmeta, and a guard and finder bound to them.pageLimits/relatedPageLimits— the page defaults and page-size caps of each collection and each related collection.pageKinds/relatedPageKinds— the pagination strategies each collection and related collection offers, the server's default first.
With --schemas, the sibling module exports schemas — the per-type JSON Schema 2020-12 map.
import { createClient, type ResourceMap, resourceMap } from './api/music.gen'
import { schemas } from './api/music.schemas.gen'
const client = createClient({ baseUrl: 'https://music.example' })
Verb / relation collisions
If a type has a relation named like a reserved verb on the resource handle (get, update,
delete, rel, actions, …), the codegen emits a build-time warning and that relation routes
through .rel('name') in the fluent client; the common case stays clean.
Programmatic API
The same generation, callable from a script (japi.config.ts, a build step, etc.):
import { generate, type CodegenConfig } from '@haddowg/json-api-codegen'
const config: CodegenConfig = {
input: 'https://music.example/docs.json',
output: 'src/api/music.gen.ts',
schemas: 'https://music.example/schemas.json', // optional
server: 'default', // optional, metadata-only
}
await generate(config) // writes the output file(s); returns the client source string
The drift gate is also programmatic — check(config) regenerates in memory and returns
{ ok, artifacts } (per-artifact { path, upToDate }) without writing:
import { check } from '@haddowg/json-api-codegen'
const result = await check({ ...config, check: true })
if (!result.ok) process.exit(1)
Lower-level building blocks are also exported for advanced use: readDocument / readSchemas,
buildDescriptor, buildExamples, emit, emitSchemas, emitExamples, readErrorCatalogue,
emitErrorCodes, checkContract, detectVerbCollisions, schemasOutputPath,
examplesOutputPath, and the provenance helpers deriveProvenance / provenanceLines /
hashJson. generateFiles(config) generates like generate and returns the paths it wrote.
License
MIT