@haddowg/json-api-codegen

中文文档
2.19.0发布于 2026/11/17MITTypeScriptES Module构建来源已验证近 30 天下载 8518

CLI that reads the json-api-symfony OpenAPI spec (+ JSON Schemas) and emits a typed client descriptor.

原始使用文档
文档目录9 节
  1. Install
  2. CLI
  3. Provenance stamp
  4. Drift check ( --check )
  5. Multiple servers
  6. What it generates
  7. Verb / relation collisions
  8. Programmatic API
  9. License

@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]
FlagRequiredDescription
--inputyesOpenAPI document source — an http(s) URL or a local file path (JSON or YAML).
--outputyesOutput file for the generated client (e.g. src/api/music.gen.ts).
--servernoServer name to target. Metadata-only — the served document is already per-server.
--schemasnoJSON Schema source (URL or path) for the validation seam. Omit to skip schema output.
--examplesnoAlso write the operations' worked examples to a sibling .examples.gen.ts module.
--checknoDrift 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 + bound createClient);
  • 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's atomic capability are baked in; you supply only ClientOptions).
  • Attributes / WriteAttributes — the per-type attribute maps (read vs create/update).
  • Per-type …Attributes / …CreateAttributes / …UpdateAttributes interfaces, 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 typed meta, 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

版本与发布记录

@haddowg/json-api-codegen 共发布 49 个版本,首次发布于 2026/07/13;过去 12 个月发布了 49 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.19.0latest2026/11/17今天
2.18.12026/11/17今天
2.18.02026/11/16今天
2.17.02026/11/133 天前
2.16.12026/11/133 天前
2.16.02026/11/133 天前

关于 @haddowg/json-api-codegen 的常见问题

@haddowg/json-api-codegen 是什么?

CLI that reads the json-api-symfony OpenAPI spec (+ JSON Schemas) and emits a typed client descriptor.

如何安装 @haddowg/json-api-codegen?

在项目目录运行 npm install @haddowg/json-api-codegen,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 japi、json-api-codegen,可以用 npx japi 直接运行。

@haddowg/json-api-codegen 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@haddowg/json-api-codegen 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@haddowg/json-api-codegen 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@haddowg/json-api-codegen 可以商用吗?

@haddowg/json-api-codegen 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@haddowg/json-api-codegen 的下载量有多少?

根据 npm 官方下载统计,@haddowg/json-api-codegen 在 2026/10/17 – 2026/11/15 这 30 天内被下载 8,518 次,日均约 284 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@haddowg/json-api-codegen 还在维护吗?

最新版本 2.19.0 发布于 2026/11/17(今天);至今共发布 49 个版本,其中过去 12 个月发布了 49 个;首次发布于 2026/07/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。