Skip to content
@pyreon/lathe
tools · api clients

121 lines of OpenAPI in. 1,133 lines of typed client you never write.

Lathe turns your OpenAPI spec into validated schemas, typed endpoints and query hooks for Pyreon, plus mocks, fake-data factories, docs and MCP tools. It fails CI when the committed client is stale, names every hook a breaking spec change touches, and can emit native modules that it compiles for iOS and Android before telling you they work.

bun add -D @pyreon/lathe
Documentation
reads
OpenAPI 3.0, 3.1, Swagger 2.0Swagger 2.0 is up-converted; split specs are bundled from their $refs.
plugins
10, from types to MCP toolsPick any; Lathe adds what they import and says what came along.
migrates from
orval, hey-api, kubb, openapi-typescriptlathe init reads the old config as text and lists what it could not map.
native
iOS and Android, experimentalThe multiplatform target compiles its own output and reports reach per operation.
lathe generate turns one OpenAPI spec into 29 typed files Terminal output of a real lathe generate run on the Bookshelf API (4 models, 4 operations, multiplatform target): it writes schemas, a typed client, query hooks, mocks, native screens and docs, 29 of 29 files, and reports 4 of 4 operations reaching native with the Swift and Kotlin builds compiled. bookshelf · lathe generate $ lathe generate lathe generate · 1 project ✓ Bookshelf 1.2.0 · openapi.yaml · 4 models · 4 operations files 29 of 29 files written + new src/gen/schemas/Book.ts + new src/gen/client.ts + new src/gen/queries/books.ts + new src/gen/mocks.ts + new src/gen/books.native.tsx + new src/gen/docs/books.md ⋯ 23 more native reach 4 of 4 operations ✓ lowers books.native.tsx swift compiled ✓ lowers books.native.tsx kotlin compiled real output · every operation reaches iOS and Android, createBook (POST) included
  • 1,133 lines of generated TypeScript from the 121-line Bookshelf spec (4 models, 4 operations): schemas, client, hooks, keys, mocks, factories, Atlas scenarios and native modules.examples/lathe-bookshelf: wc -l openapi.yaml = 121; cat src/gen/*.ts src/gen/*/*.ts src/gen/*.tsx | wc -l = 1,133
  • 0 of 29 files rewritten when lathe check runs on an unchanged spec. Output is deterministic, so a stale client is a diff, and a diff is exit 1.lathe check in a copy of examples/lathe-bookshelf, 2026-11-11: "0 of 29 file(s) written (everything already current)", exit 0
  • 6 functions and hooks named by lathe diff when one enum value left the spec, with --fail-on-breaking turning it into exit 1.lathe diff HEAD:examples/lathe-bookshelf/openapi.yaml <edited copy> --format github --fail-on-breaking, 2026-11-11

synthetic · author-run · M3 Max · record of 2026-11-05

Every result, including where we lose →
why teams pick it

Your API client, generated and kept honest.

  1. One spec, the whole surface

    Schemas, a typed client, useQuery and useMutation hooks with their query keys, deterministic mocks, createBook(overrides?) factories, Atlas scenarios, Markdown docs and MCP tool definitions. Fixtures live in ./gen/dev, which ./gen/index.ts never imports, so they cannot reach a page bundle.

  2. API changes show up in the PR

    lathe diff main:openapi.yaml openapi.yaml --format github puts breaking changes first, each naming the generated code it affects: "affects createBook, useCreateBook (books); getBook, useGetBook (books); listBooks, useListBooks (books)".

  3. Responses are checked, not trusted

    Every response is validated against the generated schema by default (responseValidation: 'strict'), so a backend that drifts fails at the boundary instead of three components later. 'warn' and 'off' exist when you need them.

  4. Switch without a rewrite weekend

    lathe init reads your orval, hey-api or kubb config, or the openapi-typescript script in package.json, maps it, and lists what it could not map with what to do instead. It never runs your old config and never writes into the old generator's output.

the difference

The client you hand-write today, and the one line that replaces it.

React + TanStack Query, by hand

A type copied from the docs, a key to keep in sync, a body nobody checks.

// api/books.ts: written by hand, kept in sync by hope
import { useQuery } from '@tanstack/react-query'

export type Book = {
  id: string
  title: string
  status: 'available' | 'borrowed' | 'lost'
}

export function useBook(bookId: string) {
  return useQuery({
    queryKey: ['books', bookId], // match it in every invalidateQueries
    queryFn: async (): Promise<Book> => {
      const res = await fetch(`https://bookshelf.example/v1/books/${bookId}`)
      if (!res.ok) throw new Error(`GET /books/${bookId}: ${res.status}`)
      return res.json() // a promise, not a check
    },
  })
}

// BookPage.tsx
export function BookPage({ id }: { id: string }) {
  const book = useBook(id)
  return <h1>{book.data?.title}</h1>
}
Pyreon + Lathe

URL, method, key and schema come from the spec. The response is validated.

// $ lathe generate   (writes ./src/gen from openapi.yaml)
import { useGetBook } from './gen'

export function BookPage(props: { id: string }) {
  const book = useGetBook(() => ({ params: { bookId: props.id } }))
  return <h1>{book.data()?.title}</h1>
}
real output

Delete one enum value from the spec. Here is what CI sees.

The repo's examples/lathe-bookshelf, with lost removed from Book.status and the client not regenerated. Every line below is what the command printed.

$ lathe check

real output

$ lathe check
lathe check · 1 project

  ✗ Bookshelf  1.2.0 · openapi.yaml · 4 models · 4 operations · multiplatform · stale
    plugins        schemas, client, queries, mocks, faker, atlas, docs (+components, required by
                   them)
    files          4 of 29 files differ from the spec
      ~ stale  src/gen/schemas/Book.ts
      ~ stale  src/gen/faker.ts
      ~ stale  src/gen/docs/models.md
      ~ stale  src/gen/api-surface.json
    contract       1 breaking · 0 additive
      ~ breaking  field-type-changed  Book.status  enum("available"|"borrowed"|"lost") →
        enum("available"|"borrowed")
    native reach   4 of 4 operations
    native verify  4 of 4 files lower
      ✓ lowers    authors.native.tsx    swift   compiled
          PyreonQuery< PyreonZodSchema_ PyreonSchemaError
      ✓ lowers    authors.native.tsx    kotlin  compiled
          PyreonQuery< PyreonZodSchema_ PyreonSchemaError
      ✓ lowers    books.native.tsx      swift   compiled
          PyreonQuery< PyreonMutation< PyreonHttpRequest( PyreonZodSchema_ PyreonSchemaError
      ✓ lowers    books.native.tsx      kotlin  compiled
          PyreonQuery< PyreonMutation< PyreonHttpRequest( PyreonZodSchema_ PyreonSchemaError
      ✓ compiled  all modules together  swift
      ✓ compiled  all modules together  kotlin

  fix: run lathe generate and commit the result

✗ 1 project stale · 1 breaking change · 87 ms
$ echo $?
1
coming from

Coming from orval, openapi-typescript + openapi-fetch or hey-api?

Same hooks, read as signals. No .data.data.

orval
// orval 8 (react-query client, default fetch httpClient) — generated into ./api
import { useCreateBook, useGetBook, useListBooks } from './api/books'

export function Books({ bookId }: { bookId: string }) {
  const books = useListBooks()
  const book = useGetBook(bookId)
  const create = useCreateBook()
  return (
    <section>
      <h2>{book.data?.data.title}</h2>
      <ul>
        {books.data?.data.map((b) => <li key={b.id}>{b.title}</li>)}
      </ul>
      <button onClick={() => create.mutate({ data: { title: 'Dune' } })}>Add</button>
    </section>
  )
}
Pyreon

Hook arguments are an accessor, so a new bookId refetches. Mutation bodies say their encoding: json, form, multipart or body. lathe init maps client: 'react-query' to plugins: queries, mock: true to mocks, faker, and lists override.mutator for you to move into configureApi({ use }).

import { For } from '@pyreon/core'
import { useCreateBook, useGetBook, useListBooks } from './gen'

export function Books(props: { bookId: string }) {
  const books = useListBooks()
  const book = useGetBook(() => ({ params: { bookId: props.bookId } }))
  const create = useCreateBook()
  return (
    <section>
      <h2>{book.data()?.title}</h2>
      <ul>
        <For each={() => books.data() ?? []} by={(b) => b.id}>
          {(b) => <li>{b.title}</li>}
        </For>
      </ul>
      <button onClick={() => create.mutate({ json: { title: 'Dune' } })}>Add</button>
    </section>
  )
}

Call the operation by name, not by path string.

openapi-typescript + openapi-fetch
// openapi-typescript + openapi-fetch
import createClient from 'openapi-fetch'
import type { paths } from './api/v1'

const client = createClient<paths>({ baseUrl: 'https://bookshelf.example/v1' })

const { data, error } = await client.GET('/books/{bookId}', {
  params: { path: { bookId: '1' } },
})
if (error) throw error
console.log(data.title) // typed, but nothing checked the body
Pyreon

Path parameters are params, query parameters query, the body json. There is no { data, error } pair: the call resolves to the validated body and rejects on a non-2xx status with the status and parsed body. lathe init finds the openapi-typescript spec -o file script and reads the paths from it.

import { configureApi, getBook } from './gen'

configureApi({ baseUrl: 'https://bookshelf.example/v1' })

// Resolves to a validated Book; a non-2xx status rejects.
const book = await getBook({ params: { bookId: '1' } })
console.log(book.title)

A generated hook instead of an options factory to spread.

hey-api
// @hey-api/openapi-ts with the @tanstack/react-query plugin
import { useMutation, useQuery } from '@tanstack/react-query'
import { createBookMutation, getBookOptions } from './client/@tanstack/react-query.gen'

export function BookView({ bookId }: { bookId: string }) {
  const book = useQuery(getBookOptions({ path: { bookId } }))
  const create = useMutation(createBookMutation())
  return (
    <>
      <h1>{book.data?.title}</h1>
      <button onClick={() => create.mutate({ body: { title: 'Dune' } })}>Add</button>
    </>
  )
}
Pyreon

@hey-api/sdk maps to plugins: client, @tanstack/react-query to queries, zod to validator: 'zod'. A mutation already invalidates the reads it can change (createBook refetches getBook and listBooks); pass invalidates to change that.

import { useCreateBook, useGetBook } from './gen'

export function BookView(props: { bookId: string }) {
  const book = useGetBook(() => ({ params: { bookId: props.bookId } }))
  const create = useCreateBook()
  return (
    <>
      <h1>{book.data()?.title}</h1>
      <button onClick={() => create.mutate({ json: { title: 'Dune' } })}>Add</button>
    </>
  )
}
try it

Pick what to generate.

Choose plugins. Lathe adds whatever they import and tells you what came along. The file list is what lathe generate writes for the Bookshelf example spec.

plugins

17 files

Dashed: not selected, but a selected plugin's output imports it, so Lathe adds it.

examples/lathe-bookshelf · lathe generate
$ lathe generate openapi.yaml --target web --plugins queries --out src/gen
lathe / Bookshelf 1.2.0
4 models 4 operations target=web
plugins: queries (+schemas, +client - required by them)
+ src/gen/schemas/Author.ts
+ src/gen/schemas/Book.ts
+ src/gen/schemas/Entity.ts
+ src/gen/schemas/NewBook.ts
+ src/gen/schemas.ts
+ src/gen/client.ts
+ src/gen/endpoints/authors.ts
+ src/gen/endpoints/books.ts
+ src/gen/queries/authors.ts
+ src/gen/queries/books.ts
+ src/gen/keys.ts
+ src/gen/endpoints/index.ts
+ src/gen/queries/index.ts
+ src/gen/index.ts
+ src/gen/package.json
+ src/gen/lathe-manifest.json
+ src/gen/api-surface.json
17 of 17 file(s) written
verify SKIPPED no native modules were generated (target is `web`)
real output, replayed · every line as the CLI prints it for this selection, captured from examples/lathe-bookshelf/openapi.yaml, 2026-11-11
what's included

The whole pipeline.

  • lathe init detects orval, hey-api, kubb or openapi-typescript and writes the lathe section of pyreon.config.ts
  • lathe check regenerates in memory and exits 1 when the committed client is stale
  • lathe diff breaking and additive contract changes as text, Markdown, GitHub annotations or JSON
  • Vite plugin @pyreon/lathe/vite regenerates on spec changes; checkOnBuild turns a stale client into a build error
  • Four HTTP clients pyreon, fetch, axios or ky; every file except client.ts, mocks.ts and dev.ts is byte-identical across them
  • Two schema libraries @pyreon/validate or Zod, both reaching native
  • Streams Server-Sent Events and NDJSON as validated async iterators and use<Op>Stream signals, with reconnect and Last-Event-ID
  • Webhooks typed payloads and a webhookHandler that calls your own signature check and caps bodies at 1 MiB
  • MCP tools each JSON-callable operation as a tool definition whose call runs the generated endpoint through your auth and middleware
  • Loss notes anything the spec says that the client cannot honour becomes a note with a stable code and a JSON pointer
recipes

Things to build with it.

An API contract check on every pull request

lathe diff takes git refs. Breaking changes become ::error annotations on the PR, and lathe check fails if someone edited the spec without regenerating.

# .github/workflows/api-contract.yml
name: API contract
on:
  pull_request:
    paths: ['openapi.yaml']
jobs:
  contract:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: oven-sh/setup-bun@v2
      - run: bun install
      - run: bunx lathe diff origin/main:openapi.yaml openapi.yaml --format github --fail-on-breaking
      - run: bunx lathe check
Tests against the spec, no server, no MSW

Mocks are middleware on the generated client, so they behave the same in node and the browser. Factories respect the spec's constraints and are reproducible from a seed. This file passes under vitest against the Bookshelf client.

import { afterEach, beforeEach, expect, it } from 'vitest'
import { createBook, installMocks, mockOperation, resetMocks, seedFaker } from './gen/dev'
import { getBook, listBooks } from './gen'

beforeEach(() => {
  installMocks()
  seedFaker(42)
})
afterEach(() => resetMocks())

it('shows a lost book', async () => {
  const lost = createBook({ status: 'lost' })
  mockOperation('getBook', { json: lost })
  expect((await getBook({ params: { bookId: lost.id } })).status).toBe('lost')
})

it('survives a 404', async () => {
  mockOperation('getBook', { status: 404, json: { message: 'no such book' } })
  await expect(getBook({ params: { bookId: 'missing' } })).rejects.toMatchObject({ status: 404 })
})

it('lists from spec-derived fixtures', async () => {
  expect((await listBooks()).length).toBeGreaterThan(0)
})
Auth that follows the signed-in user

headers is re-read on every request, so a new token applies to the next call. Middleware wraps every request, streams included.

import type { HttpMiddleware } from '@pyreon/http'
import { signal } from '@pyreon/reactivity'
import { configureApi } from './gen'

const token = signal('')

const retryOn401: HttpMiddleware = async (req, next) => {
  const res = await next(req)
  return res.status === 401 ? next(req) : res
}

configureApi({
  headers: () => ({ Authorization: `Bearer ${token()}` }),
  use: [retryOn401],
})
api

Flags, plugins, config and what the client exports.

Every export has a reference page with its signature, an example and the mistakes people make with it.

CLI flags · 10
  • --target
  • --plugins
  • --client
  • --validator
  • --dry-run
  • --watch
  • --strict-native
  • --fail-on-breaking
  • --format
  • --json
plugins · 10
  • types
  • schemas
  • client
  • queries
  • mocks
  • faker
  • components
  • atlas
  • docs
  • mcp
pyreon.config.ts · lathe · 17
  • input
  • output
  • target
  • plugins
  • client
  • validator
  • baseUrl
  • responseValidation
  • filters
  • patches
  • operations
  • naming
  • streams
  • projects
  • remoteRefs
  • int64
  • format
generated (./gen) · 7
  • use<Op>()
  • use<Op>Stream()
  • <op>()
  • configureApi
  • keys
  • optimisticUpdate
  • webhookHandler
generated (./gen/dev) · 6
  • installMocks
  • mockOperation
  • resetMocks
  • mockCalls
  • seedFaker
  • create<Model>()
programmatic (@pyreon/lathe/core · @pyreon/lathe/vite) · 6
  • lathe
  • generate
  • resolveConfig
  • definePlugin
  • contractDiff
  • loadOpenApi
MCP tools (@pyreon/mcp) · 3
  • get_api_client
  • get_api_operation
  • explain_api_diff
good to know

Good to know before you start.

Response headers are not generated

They are reported as a response-headers loss note. Header and cookie parameters are typed call arguments.

Native writes send JSON and path parameters

A POST, PUT, PATCH or DELETE reaches iOS and Android as a mutation component when it sends a JSON body (or none) and returns typed JSON (or nothing). A form or multipart body, a non-JSON response, or a required query or header parameter keeps that write web-only, with the reason in the report. Nothing reaches native without an absolute baseUrl.

No surprise network calls

A remote $ref is reported, not fetched, until you set remoteRefs: 'fetch' or run lathe pull.

Webhook signatures are your hook

webhookHandler calls your verify; it does not know any vendor's signing scheme.

questions

What people ask first.

Do I have to keep orval (or hey-api) installed during the move?

No. lathe init reads the old config as text and never runs it. If the old output directory still holds the old client, Lathe writes beside it so the app keeps working until your imports move.

Will mocks and fake data end up in my production bundle?

They cannot. ./gen/index.ts never names ./mocks, ./faker or ./components, so no import edge exists for a bundler to follow, and the generated package.json declares sideEffects so the rest tree-shakes. The Bookshelf example checks it: grep -c '@faker-js' dist/assets/*.js prints 0.

What happens to the parts of my spec Lathe cannot represent?

Each one becomes a note with a stable code (response-headers, unsupported-security, int64-precision…), a JSON pointer into the spec and a severity. They print in the terminal and land in the generated reference pages under "Not represented".

Which operations reach iOS and Android?

With target: 'multiplatform' and an absolute baseUrl: GET operations (path parameters and required query parameters become component props), writes with a JSON body (a mutation component that refreshes the same reads the web hook does), and typed SSE or NDJSON streams. Lathe runs the native compiler over its own output, checks for the lowering markers, and type-checks with swiftc and kotlinc when they are installed; without the compiler it says the check was skipped. The native targets are experimental.

Can I add my own output?

Yes. A --plugins entry that is not a built-in name is loaded as a plugin module (a path or a package), written with definePlugin from @pyreon/lathe/core.

Your spec already knows the API. Let it write the client.

bun add -D @pyreon/lathe
Read the Lathe guide