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 - 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-typescript
lathe initreads 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.
- 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 checkruns on an unchanged spec. Output is deterministic, so a stale client is a diff, and a diff is exit 1.lathe checkin 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 diffwhen one enum value left the spec, with--fail-on-breakingturning 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 →Your API client, generated and kept honest.
One spec, the whole surface
Schemas, a typed client,
useQueryanduseMutationhooks 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.tsnever imports, so they cannot reach a page bundle.API changes show up in the PR
lathe diff main:openapi.yaml openapi.yaml --format githubputs breaking changes first, each naming the generated code it affects: "affects createBook, useCreateBook (books); getBook, useGetBook (books); listBooks, useListBooks (books)".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.Switch without a rewrite weekend
lathe initreads 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 client you hand-write today, and the one line that replaces it.
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>
}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>
}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.
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 $?
1Coming from orval, openapi-typescript + openapi-fetch or hey-api?
Same hooks, read as signals. No .data.data.
// 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>
)
}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
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 bodyPath 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/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>
</>
)
}@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>
</>
)
}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.
17 files
Dashed: not selected, but a selected plugin's output imports it, so Lathe adds it.
The whole pipeline.
lathe initdetects orval, hey-api, kubb or openapi-typescript and writes thelathesection ofpyreon.config.tslathe checkregenerates in memory and exits 1 when the committed client is stalelathe diffbreaking and additive contract changes as text, Markdown, GitHub annotations or JSON- Vite plugin
@pyreon/lathe/viteregenerates on spec changes;checkOnBuildturns a stale client into a build error - Four HTTP clients
pyreon,fetch,axiosorky; every file exceptclient.ts,mocks.tsanddev.tsis byte-identical across them - Two schema libraries
@pyreon/validateor Zod, both reaching native - Streams Server-Sent Events and NDJSON as validated async iterators and
use<Op>Streamsignals, with reconnect andLast-Event-ID - Webhooks typed payloads and a
webhookHandlerthat calls your own signature check and caps bodies at 1 MiB - MCP tools each JSON-callable operation as a tool definition whose
callruns 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
Things to build with it.
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 checkMocks 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)
})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],
})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.
- --target
- --plugins
- --client
- --validator
- --dry-run
- --watch
- --strict-native
- --fail-on-breaking
- --format
- --json
- types
- schemas
- client
- queries
- mocks
- faker
- components
- atlas
- docs
- mcp
- input
- output
- target
- plugins
- client
- validator
- baseUrl
- responseValidation
- filters
- patches
- operations
- naming
- streams
- projects
- remoteRefs
- int64
- format
- use<Op>()
- use<Op>Stream()
- <op>()
- configureApi
- keys
- optimisticUpdate
- webhookHandler
- installMocks
- mockOperation
- resetMocks
- mockCalls
- seedFaker
- create<Model>()
- lathe
- generate
- resolveConfig
- definePlugin
- contractDiff
- loadOpenApi
- get_api_client
- get_api_operation
- explain_api_diff
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.
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