Skip to content

Latest commit

 

History

History
1212 lines (994 loc) · 75 KB

README.md

File metadata and controls

1212 lines (994 loc) · 75 KB

@workerstack/clients

Generates SDKs (TypeScript, Go, Rust, Python, C#, Java), a CLI and an MCP server from any OpenAPI 3.x document.

Contents

What it generates

Generates SDKs (TypeScript, Go, Rust, Python, C#, Java), a Go command-line client and a Model Context Protocol server from an OpenAPI 3.x document, or straight from a @workerstack/backend app.

Every target reads one intermediate representation and vendors its own small runtime, so a generated SDK has no dependency on backend, and a spec from another framework generates just as well. The output is formatted and deterministic: regenerating an unchanged spec changes nothing on disk.

Install

backend moved to the workerstack org in 1.0.0-rc.23, and the migration note maps each old package name to its new one. 1.0 is out as a release candidate, published under npm's next tag, so an install without a tag gets a deprecated placeholder. Add @next until the final release:

npm install --save-dev @workerstack/clients@next

Node 22.12 or later, or Bun 1.3 or later.

Each target formats what it writes with that language's own formatter, when it can find it:

target formatter found by
go, cli gofmt $GOFMT, $GOROOT/bin/gofmt, gofmt on PATH, beside the go on PATH
python ruff $RUFF, then ruff on PATH
rust rustfmt $RUSTFMT, the active toolchain's own binary beside rustc, PATH
ts oxfmt the oxfmt optional peer, installed beside clients

A formatter it cannot find is named on standard error and skipped: the files go out as the emitter wrote them, which is valid source either way, so generating a Python SDK never requires you to install ruff. Set CLIENTS_REQUIRE_FORMATTERS=1 to make a missing formatter fail the run instead, for a pipeline that would rather stop than ship unformatted code. An override that points at nothing is refused by name.

oxfmt is the exception and says nothing when absent: it is clients' own choice of TypeScript formatter and a declared optional peer, so not having it is the documented normal rather than news. CLIENTS_REQUIRE_FORMATTERS still stops for it.

The csharp and java targets are not formatted today: dotnet format and google-java-format work over a project rather than a stream, which clients' post-pass does not yet do.

Start

From a document:

npx clients generate --spec openapi.json --target ts --target python --out generated

From a backend app module, with no document written first:

npx clients generate --app src/app.ts --target ts --target go --go-module-path github.com/acme/shop/sdk \
  --out generated

The targets are ts, go, rust, python, csharp, java, cli and mcp. Each target's files go under <out>/<target>.

clients generate

clients generate --spec openapi.json --target ts --target cli --out generated \
  --cli-binary-name shop --cli-module-path github.com/acme/shop --cli-repo acme/shop
  • --spec <file>: the OpenAPI document, as JSON.
  • --app <module>[#export]: a backend app module instead of --spec (give one, never both). Its named export, else app, else default, is the app; its document is made by the app's own @workerstack/backend/http/openapi, resolved from the app as at run time, and the module's openApi export, if any, is that document's options (info, securitySchemes, invalidate, …, as generateOpenApi takes them). Started by bun run, the bin hands the load to that Bun, so a module needing Bun's loaders works; a run ends once it has written, whatever the module left open. The module exports the app and serves nothing: one that calls serve() as it loads is outside --app's contract, since backend never serves implicitly and has no switch to stop it.
  • --target <name>: ts, go, rust, python, csharp, java, cli or mcp; repeat it for more than one.
  • --out <dir>: each target's files go under <dir>/<target>.
  • --<target>-<option>: a target's options are its generator's, passed through as given. Each takes a value.
  • --watch: generate again on each change of the spec (or the --app module), each run in a fresh process.
  • -h, --help: the usage text, with every target's options.

Parsing is strict, because a typo that generates the wrong thing silently is worse than a refusal: an unknown flag, a missing value, a stray argument, an unknown target, or an option for a target no --target names is a usage error. --k v and --k=v both work, and a value is never the next flag.

Every flag

One table, since a flag that is not written down is a flag nobody finds:

Flag Target What it sets
--spec <file> — the OpenAPI document to generate from
--app <module>[#export] — a backend app module instead of a document
--target <name> — which target to emit; repeat for more than one
--out <dir> — the output root; each target writes under <dir>/<target>
--watch — regenerate on each change, in a fresh process
-h, --help — the usage text
--ts-name ts the client class's name (default SDK)
--ts-stem ts the file stem the generated modules share
--ts-package-name ts the npm name, and the JSR name when scoped; the stem by default
--ts-version ts the version both registries carry; the document's by default
--ts-single-flight ts also write the single-flight handler; takes no value
--ts-tanstack-query ts also write the TanStack Query adapter; takes no value
--go-module-path go the Go module path the SDK is imported by
--go-version go its semver; from v2 on, the major suffix (/v2) it puts on the module path
--rust-crate-name rust the crate's name
--rust-version rust the crate's version
--rust-description rust what crates.io shows; cargo publish needs one
--rust-license rust its SPDX license; cargo publish needs one
--rust-repository rust the repository crates.io links
--rust-homepage rust the home page crates.io links
--rust-keywords rust its crates.io keywords, comma separated: five at most, each 20 ASCII characters
--rust-categories rust its crates.io category slugs, comma separated: five at most
--rust-documentation rust the https documentation crates.io links; docs.rs by default
--python-package-name python the Python package's name
--python-version python the package's version
--csharp-client-name csharp the client class's name
--csharp-package-id csharp the NuGet package id
--csharp-root-namespace csharp the root namespace
--csharp-version csharp the package's version
--csharp-description csharp what nuget.org shows
--csharp-authors csharp its authors, comma separated
--csharp-license csharp its SPDX license expression
--csharp-homepage csharp the https home page nuget.org links
--csharp-repository csharp the https URL of its git repository
--csharp-copyright csharp the copyright notice nuget.org shows
--csharp-tags csharp its NuGet tags, comma separated
--java-artifact-id java the Maven artifact id; sdk by default
--java-group-id java the Maven group id; com.example by default, yours to publish
--java-package-name java the Java package name
--java-client-name java the client class's name
--java-version java the publication's version
--java-description java the POM's description; the document's by default
--java-homepage java the POM's https project URL
--java-license java its SPDX license id, linked to spdx.org
--java-repository java the https URL of its git repository, the POM's scm
--java-developers java the POM's developers, comma separated: each a name or Name <email>
--cli-binary-name cli the command's own name (shop)
--cli-base-url cli the base URL it calls by default; the document's server by default
--cli-module-path cli the Go module path the CLI is built from
--cli-version cli its semver; from v2 on, the major suffix (/v2) it puts on the module path
--cli-repo cli the GitHub repository its release workflow and install scripts use
--cli-env-prefix cli the prefix of the environment variables it reads
--cli-install-url cli the https directory its install scripts are served from; the release's by default
--cli-description cli what the package managers show; every channel needs one
--cli-homepage cli the home page the package managers link; every channel needs one
--cli-license cli its SPDX license; every channel needs one
--cli-maintainer cli Name <email>, which AUR and the Linux packages name
--cli-homebrew-tap cli the Homebrew tap (owner/name) its cask is pushed to
--cli-scoop-bucket cli the Scoop bucket (owner/name) its manifest is pushed to
--cli-winget-fork cli the winget-pkgs fork (owner/name) its manifests are proposed from
--cli-winget-publisher cli the publisher winget files it under
--cli-aur cli a switch: publish the <bin>-bin AUR package
--cli-packages cli Linux packages beside the archives: deb, rpm, apk, comma separated
--mcp-name mcp the server's name, and the stem of its bin
--mcp-env-prefix mcp the prefix of the environment variables it reads
--mcp-version mcp its server info and package version; the document's by default
--mcp-package-name mcp the npm name it publishes under; <name>-mcp by default
--mcp-mcp-name mcp its MCP registry name (io.github.acme/shop), package.json's mcpName
--metadata-description all what every registry shows
--metadata-homepage all the https home page the registries link
--metadata-repository all the https URL of its git repository
--metadata-license all its SPDX license expression
--metadata-authors all each Name <email> or a name, comma separated
--metadata-keywords all registry keywords, comma separated
--metadata-copyright all the copyright line
--metadata-documentation all the https URL of its documentation
--metadata-changelog all the https URL of its changelog
--metadata-license-file all the license file to ship in each package
--metadata-readme all the README to ship in each package
--metadata-icon all the package icon to ship where the registry shows one

The --metadata-<field> flags fill one package block that every target which publishes reads where its registry has a place for the field, so a description or license is given once, not once per target. A target's own option of the same meaning wins: --java-description over --metadata-description. Each field is checked before anything generates: URLs must be https, the license an SPDX expression, text one line.

--metadata-readme and --metadata-license-file name files on disk, read once relative to where clients runs. Every target writes them into its package root as README.md and LICENSE, and each manifest points at the ones it has: pyproject's readme and license-files, Cargo's readme and include, the .csproj's PackageReadmeFile and packed items, and jsr.json's publish list; npm packs both on its own. The README must be a .md file, and both must be UTF-8 text. --metadata-icon ships only into the C# package, as icon with its own extension in lower case (icon.png, icon.jpeg) under PackageIcon, since nuget.org is the one registry that shows an icon: a PNG or JPEG whose bytes are that image, at most 1 MB.

The six SDKs

Every SDK takes the same configuration — a base URL, the auth the spec's security scheme names, a timeout, retries, hooks around each HTTP call, and per-call overrides — and every one answers the same way: the normal call returns your value and throws a typed error by status, while client.safe answers a result instead. What follows is each language's client in a slice of a compiled example; the SDK recipes page has the whole programs.

The TypeScript SDK

clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen
import { DecodeError, Kitchen, NotFoundError } from "./kitchen"

export function newClient(): Kitchen {
	return new Kitchen({
		baseURL: "https://api.example.com",
		headers: { authorization: `Bearer ${process.env.KITCHEN_TOKEN ?? ""}` },
		timeout: 10_000,
	})
}

export async function organization(client: Kitchen, orgId: string): Promise<string | null> {
	try {
		await client.organizations.retrieve({ params: { orgId } })
		return orgId
	} catch (error) {
		if (error instanceof NotFoundError) return null
		throw error
	}
}

export async function health(client: Kitchen): Promise<string> {
	const result = await client.safe.health.check()
	if (result.ok) return "up"
	if (result.error instanceof DecodeError) return `unreadable answer: ${result.error.message}`
	return `answered ${result.error.status}`
}

Publishing it to npm and JSR

The target writes a package around the SDK, so the output directory publishes as it is. The sources stay where a workspace imports them; they import each other as .js, which every TypeScript resolution and bundler maps to the .ts file. Node will not strip types under node_modules, so dist/ holds each source compiled to ES module JavaScript beside its declarations, and package.json exports those: the root, ./webhook when the document has webhook events, and ./tanstack-query with @tanstack/query-core as an optional peer. A scoped --ts-package-name also gets a jsr.json that publishes the sources themselves, its .js imports mapped to their .ts files. --metadata-* fills description, keywords, homepage, bugs, license, author and repository.

clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen \
  --ts-package-name @acme/kitchen --ts-version 1.4.0 --metadata-license MIT

TanStack Query, from the same document

--ts-tanstack-query writes one more file beside the SDK, <stem>.tanstack-query.gen.ts. It takes no value:

clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen --ts-tanstack-query

Build the QueryClient first, then the SDK with the file's invalidateQueries hook, then the helpers. The QueryClient is the one your framework's adapter exports (@tanstack/solid-query, @tanstack/react-query), or query-core's own, as here:

import { QueryClient } from "@tanstack/query-core"
import { Kitchen } from "./kitchen"
import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"

export const queryClient = new QueryClient()
const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
export const { query, mutation, infiniteQuery, queryKey, mutationKey } = createQueryHelpers(() => sdk)

The five surfaces are nested exactly as the client is, so query.organizations.retrieve(…) sits where client.organizations.retrieve(…) does. createQueryHelpers takes a function that returns the client, and it calls it on every request, so an isomorphic app can return a different client for each request.

The document decides what goes where. A GET is on query, every other method is on mutation, and an event stream, a WebSocket or an x-realtime operation is on neither, because a stream is not a cache entry. Nothing is keyed off a method's name.

Call shapes. Each factory returns only its key and its function. Spread the result into TanStack's own options and put everything else after it, so every other option is typed by TanStack. These use query-core's observers; useQuery(() => ({ ... })) in solid-query, or useQuery({ ... }) in react-query, takes the same object:

import { InfiniteQueryObserver, MutationObserver, QueryClient, QueryObserver } from "@tanstack/query-core"
import { Kitchen } from "./kitchen"
import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"

const queryClient = new QueryClient()
const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
const { query, mutation, infiniteQuery, queryKey } = createQueryHelpers(() => sdk)

export function organization(orgId: string) {
	return new QueryObserver(queryClient, { ...query.organizations.retrieve({ params: { orgId } }), staleTime: 0 })
}

// the second argument is the SDK's own call options; they reach the call, not the key
export const timed = query.organizations.retrieve({ params: { orgId: "org_1" } }, { timeout: 5_000 })

export const greet = new MutationObserver(queryClient, {
	...mutation.hello.create(),
	onMutate: (input) => console.log(`greeting ${input.json.name}`),
})

export const greetings = new InfiniteQueryObserver(queryClient, {
	...infiniteQuery.hello.list((q: string | undefined) => ({ search: { q: q ?? "" } })),
	initialPageParam: undefined,
	getNextPageParam: () => undefined, // read the next page param off the last page, when your API pages
})

export const cached = queryClient.getQueryData(queryKey.hello.list({ search: { q: "Ada" } }))

A read takes the SDK method's request, then optionally its call options (timeout, headers, signal, and the other per-call options). mutate takes exactly what the SDK method takes. A paged read takes a function from the page param to the request. The adapter calls that function once with undefined to build the key, so it must accept undefined. Annotate its parameter and TanStack infers the page param type from it. Every call gets TanStack's abort signal merged with yours, so a cancel, or the last observer unmounting, aborts the request.

Keys. A read's key is [<SDK name>, ...the member path, the request]. The request object goes in whole, so params, search and anything else the SDK sends are all in it. That is what TanStack requires: every input the queryFn depends on belongs in the key, so two reads of one route that differ only by search are two cache entries. The call options are not in the key, since a signal and a timeout say nothing about the answer. A read with no request keys as [<SDK name>, ...the member path]. queryKey.<…>(req) returns exactly the key query.<…>(req) uses, typed so getQueryData infers the answer. A paged read's key is the key of its request for undefined plus a trailing "infinite" marker, because its cached shape is InfiniteData and it must not share the plain read's entry.

Invalidation happens in the SDK, not the helpers. A successful write fires the SDK's onInvalidate with the reads its x-invalidate selectors name, and invalidateQueries(queryClient) makes each of them stale as [<SDK name>, ...the member path, { params }], or as the bare prefix when the target has no params. TanStack matches objects partially and compares only the filter's own positions, so that reaches every search of that read, the paged entry included. Because the SDK fires the hook, a plain sdk.hello.create(…) refreshes the cache just as mutation.hello.create() does. The SDK awaits the hook, so a write resolves only after the active reads it made stale have refetched. A failing refetch holds the write through its retries but never rejects it, and an infinite query refetches every page it holds.

Server rendering. On the server, build the QueryClient and the SDK per request, in that order. Both are dropped when the request ends, and the hook holds no state of its own. If a route preload prefetches, skip the browser's hydration run, or it refetches what the server already sent:

import { QueryClient } from "@tanstack/query-core"
import { Kitchen } from "./kitchen"
import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"

const queryClient = new QueryClient()
const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
const { query } = createQueryHelpers(() => sdk)

// a route preload: `isServer` from your framework (`@solidjs/web` in Solid), `intent` from the router
export function preloadOrganization(isServer: boolean, intent: string, orgId: string): void {
	if (!isServer && intent === "initial") return
	void queryClient.prefetchQuery(query.organizations.retrieve({ params: { orgId } }))
}

@tanstack/query-core is your dependency, not backend's. Install it yourself; the file imports it for types only.

Drop the flag and the next run deletes the file, the way .clients-generated.json deletes anything the previous run wrote and this one did not. The index file never re-exports the adapter, so an SDK generated without the flag names no TanStack type anywhere.

Single-flight, a write and its reads in one request

--ts-single-flight writes <stem>.single-flight.gen.ts, a server's file: singleFlightHandler(getSdk, options) is a fetch handler, and runSingleFlight(sdk, body) runs the same batch with no Request or Response. It takes no value, and the run refuses it for a document with no write whose x-invalidate names a read.

clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen --ts-single-flight

A batch is { v: 1, op, input, reads: [{ id, operationId, input }] } and its answer is { v: 1, write: { status, headers, body }, reads: [{ id, data } | { id, error: { status, body? } }] }. Everything is checked against the service map before anything runs: one REST write, at most maxReads (10) REST JSON reads, and input of only params, search, json (the write's) and idempotencyKey (an idempotent write's). The handler takes only a JSON POST of at most maxBodyBytes (64 KiB), refuses a browser on another site or an origin outside allowedOrigins (its own by default), and answers a refusal as a 400 application/problem+json.

The write runs once on getSdk(request), which you make per request, forwarding only the auth you choose; the handler adds no retry, though the SDK's own hooks may. Only after a 2xx do the reads run, in parallel and past any cache, within readBudgetMs (2000) and maxReadBytes (1 MiB) in all; a read past either ends as its own error entry (504 or 502) and never fails the batch. The write's Set-Cookie headers are copied onto the 200, and a cookie only sticks when the API shares the handler's site.

The index never re-exports the file, so no browser bundle carries the handler; the package exports it at ./single-flight.

The client sends its writes there once you give it singleFlight. A write goes in a batch only when it can: a REST write with a JSON answer whose x-invalidate names reads, called with nothing a batch cannot carry (headers, cookies, body, form, baseURL, raw), its operationId not in exclude, and select picking at least one read. select gets the write's targets and returns the reads to bring back, at most maxReads (10). Every other call goes direct, as does one called with singleFlight: false. The batch is a POST to path (_mutate) under the base URL, so the client's hooks, timeout and signal apply to it. An idempotent write's key is made before the batch, so a resend carries the same one. With TanStack Query, activeReads(queryClient) picks the active reads, and invalidateQueries puts each one in the cache before it marks the rest stale:

import { QueryClient } from "@tanstack/query-core"
import { Kitchen } from "./kitchen"
import { activeReads, invalidateQueries } from "./kitchen.tanstack-query.gen"

const queryClient = new QueryClient()
const sdk = new Kitchen({
	baseURL: "https://app.example.com/api",
	onInvalidate: [invalidateQueries(queryClient)],
	singleFlight: { select: activeReads(queryClient) },
})

The write resolves with the answer a direct call would have, and throws the same error. Its reads reach the onInvalidate hooks first, as event.fresh: each answered read's data by the id select gave it, and in failed the ids that did not come back. A query opts out with meta: { singleFlight: false }, and a mutation with the same meta sends its write direct. A 401 on the write refreshes the token once through onAuthExpired and sends the batch again. When the handler refuses the batch, the client sends the write direct; any other failure throws and the write is never sent twice. A batch answer that is no envelope throws DecodeError, the hooks still called, since the write may have run.

send replaces the POST, for an app that calls its server another way, such as a server function that returns runSingleFlight(sdk, batch). It gets the batch and resolves the envelope. The client cannot tell a refusal through send from a failure, so it throws one and never resends the write:

import { Kitchen, type SingleFlightBatch } from "./kitchen"

declare function mutate(batch: SingleFlightBatch): Promise<object>

export const sdk = new Kitchen({
	baseURL: "https://app.example.com/api",
	singleFlight: {
		select: (targets) =>
			targets.map((target, at) => ({ id: `r${at}`, input: { params: target.params }, operationId: target.operationId })),
		send: mutate,
	},
})

The Go SDK

Idiomatic Go: a Config, context.Context on every call, errors read with errors.As, and an event stream as a range over a function.

clients generate --spec openapi.json --target go --out generated --go-module-path github.com/acme/shop/sdk

Go wants a v2-or-later module's major version at the end of its path, so pass the base path and the version: --go-version 2.1.0 makes go.mod declare github.com/acme/shop/sdk/v2, and the CLI target's --cli-version does the same for its module and the version it links in. A path Go would not publish (no domain first, or a suffix such as /v1) is refused, as is a suffix next to a version, since the version gives it.

func listing(ctx context.Context, client *sdk.Client) string {
	r, err := client.Safe().Root.List(ctx, nil)
	if err != nil {
		return fmt.Sprintf("no answer: %v", err) // never sent, refused, dropped, timed out or canceled
	}
	var unreadable *sdk.DecodeError
	var failed *sdk.ClientError
	switch {
	case r.Ok():
		return fmt.Sprintf("answered %d: %v", r.Response.StatusCode, r.Data)
	case errors.As(r.Err, &unreadable):
		return fmt.Sprintf("answered %d, unreadable: %v", r.Response.StatusCode, unreadable.Err)
	case errors.As(r.Err, &failed):
		return fmt.Sprintf("answered %d: %s", failed.StatusCode, failed.Key)
	}
	return r.Err.Error()
}

The Rust SDK

Async over reqwest, each call taking its options struct, with the safe mirror as a second client style.

clients generate --spec openapi.json --target rust --out generated --rust-crate-name shop-sdk
async fn listing(client: &Client) -> String {
    match client.safe().root().list(&RootListOpts::default()).await {
        Ok(Answer::Ok { data, response }) => format!("answered {}: {data:?}", response.status),
        Ok(Answer::Err {
            error: SafeError::Api(failed),
            response,
        }) => format!("answered {}: {}", response.status, failed.message()),
        Ok(Answer::Err {
            error: SafeError::Decode(unreadable),
            response,
        }) => format!("answered {}, unreadable: {unreadable}", response.status),
        Err(no_answer) => format!("no answer: {no_answer}"), // never sent, refused, timed out or canceled
    }
}

The Python SDK

A sync SDK and an async AsyncSDK, both context managers, typed for mypy --strict, with results as frozen dataclasses to narrow with match.

clients generate --spec openapi.json --target python --out generated --python-package-name shop_sdk

pyproject.toml builds with hatchling and carries what PyPI shows: --metadata-* gives the description, the SPDX license (PEP 639, so no License :: classifier), authors, keywords, and [project.urls] (Homepage, Source, Issues, Documentation, Changelog). The classifiers name the Python versions clients tests and Typing :: Typed, and clients' own manifest stays out of the sdist.

async def health(client: AsyncSDK) -> str:
    match await client.safe.health.check():
        case Ok(data, response):
            return f"answered {response.status}: {data}"
        case Err(DecodeError() as unreadable, response):
            return f"answered {response.status}, unreadable: {unreadable}"
        case Err(error, response):
            return f"answered {response.status}: {error}"

The C# SDK

A .NET project with its own HttpClient pipeline, IAsyncDisposable streams, and client.Safe answering Result<T>.

clients generate --spec openapi.json --target csharp --out generated --csharp-package-id Acme.Shop

nuget.org shows a package's description, authors, license and links: give them with --csharp-description, --csharp-authors, --csharp-license, --csharp-homepage and --csharp-repository, and the .csproj carries them into dotnet pack.

    public static async Task<string> Listing(HttpSdkClient client, string id)
    {
        var result = await client.Safe.Root.ListAsync(id); // no answer (never sent, refused, timed out, canceled) still throws
        return result.Match(
            found => $"answered {result.Response.Status}: {found}",
            error => error switch
            {
                DecodeException unreadable => $"answered {result.Response.Status}, unreadable: {unreadable.Message}",
                ApiStatusException failed => $"answered {failed.Status}: {failed.Key}",
                _ => error.Message,
            });
    }

The Java SDK

A Java 17 library on Jackson 3, with builders, try-with-resources streams, client.safe() answering a sealed Result<T>, and a Gradle publication.

clients generate --spec openapi.json --target java --out generated --java-group-id com.acme

Maven Central refuses a POM without a URL, a license, a developer and scm: give them with --java-homepage, --java-license, --java-developers "Name <email>, Other Name" and --java-repository, or once for every target in the metadata block, whose authors are the POM's developers. Signing the publication stays yours.

  static String listing(KitchenClient client) {
    // no answer (never sent, refused, timed out, canceled) still throws
    Result<ListApiResponse200> result = client.safe().root().list(RootListParams.builder().build());
    int status = result.response().status();
    return result.fold(
        found -> "answered " + status + ": " + found,
        error ->
            error instanceof ApiException failed
                ? "answered " + status + ": " + failed.key()
                : "answered " + status + ", unreadable: " + error.getMessage());
  }

Errors and the safe mirror

Two styles, in all six SDKs, over the same calls:

  • The normal call answers its value and throws on any failure: an error status as its typed error (NotFoundError and so on, each a ClientError), and an undecodable or over-cap 2xx as a DecodeError.
  • client.safe holds the same calls, each answering a result. On ok it carries the data, the raw response, and the declared response headers when the operation has any. Otherwise it carries the error the normal call would have thrown, with the parsed body on it. A declared status narrows the error's type and body; any other status is the base client error with an unknown body.
  • No answer throws in both styles. A call never sent, a refused or dropped connection, a timeout, a cancel, and a stream that drops after it opened are not answers, so there is nothing for a result to carry.

A name of yours that collides with the mirror, or with a runtime type, is renamed and reported on stderr — never silently. An operation or root resource named safe becomes safe_, and a component named like one of the runtime types becomes <Name>Model.

Full reference: generated clients.

The command-line client

--target cli writes a Go command-line client for the API: one command per operation, grouped by its dotted operationId, with --help everywhere, commands and schema for discovery, typed flags, table/JSON/NDJSON/YAML output, streams, pagination, shell completion, and an embedded SKILL.md so an agent can drive it. It ships with a release workflow, which can publish to Homebrew, Scoop, winget, AUR and deb/rpm/apk packages, and, with --cli-repo, install scripts that verify what they install.

clients generate --spec openapi.json --target cli --out ./cli --cli-repo acme/shop-cli
shop orders list --status open --output json
Value Default What it does
a command per operation — grouped by the dotted operationId resource tree
--json off one machine-readable shape on every command
--output <json|ndjson|yaml|table> table human and machine formats
--api-key / --base-url / --config / --timeout / --verbose from config/env auth, target, config file, deadline, logging
commands, schema — a listable command index and per-call schemas
--output <file> stdout a binary response written as bytes, pipe-safe
exit codes usage/standard non-zero on usage error, distinct from a runtime one

Its configuration has one precedence, everywhere: flag, then environment, then config file. The environment variables are the --cli-env-prefix (or the API's name) upper-cased.

Full reference: the generated CLI and releasing it.

Install scripts

The CLI's install.sh and install.ps1 are written by installgen, which ships in this package as the installgen bin and the @workerstack/clients/installers library (it was @lovrozagar/installgen). The generated release workflow checks every release with the installgen of the clients release that generated the module:

npx --yes --package @workerstack/clients@<version> installgen check --default-version v1.2.3

installgen also writes installers for any prebuilt binary, outside a generated CLI:

import { defineConfig } from "@workerstack/clients/installers"

export default defineConfig({
	name: "my-cli",
	baseUrl: "https://dl.example.com/my-cli",
	assetPath: ({ version, os, arch }) => `${version}/my-cli-${os}-${arch}.tar.gz`,
})

Full reference: installgen.

Release tooling

clients release cuts versions for a product's public packages and mirrors each one to its own GitHub repo. A product describes its packages once, in a release.config.ts typed by the @workerstack/clients/release library; each package's dir sits beside the config, and the repo root is the config's git toplevel:

import { defineRelease } from "@workerstack/clients/release"

export default defineRelease({
	project: "acme",
	codegen: ["bun", "run", "codegen"],
	homepage: "https://example.com",
	spec: { committedPath: "openapi.json", deployedUrl: "https://api.example.com/openapi.json" },
	packages: [
		{ name: "sdk", repo: "acme/sdk", description: "Acme SDK", commitMessage: "chore: sync", topics: ["acme"] },
	],
})
clients release bump --config acme-release/release.config.ts [--major]
clients release sync --config acme-release/release.config.ts [--only sdk] [--dry-run] [--validate-only]
clients release bootstrap --config acme-release/release.config.ts (--all | --only sdk) [--force-bootstrap]

bump writes each changed package's version files, CHANGELOG.md and .release-state.json (an API change is a minor, measured by oasdiff through Go on PATH); sync and bootstrap push with GH_TOKEN, committing as committer (default public-sync[bot]).

The MCP server

--target mcp writes a standalone Model Context Protocol server: one tool per operation marked for MCP, its inputSchema from the operation's parameters and body, an outputSchema from its success response, and structuredContent an agent reads as data beside a text rendering. A failure comes back as a tool error with its status and key, never as a successful result. Read-only operations are annotated as such. It speaks stdio by default, and Streamable HTTP with --http.

clients generate --spec openapi.json --target mcp --out ./mcp --mcp-name acme

Its package publishes to npm as written. --mcp-package-name @acme/shop-mcp names it (its bin keeps the server's name), the metadata block fills its description, license, repository and the rest as it does the TS SDK's, and --mcp-mcp-name io.github.acme/shop writes the mcpName the MCP registry checks the npm package by. With it the server also gets the server.json that mcp-publisher publish reads from the package's root, on the registry's 2025-12-11 schema: that name, the description (100 characters at most, else refused), the version npm publishes, the npm package over stdio with every environment variable the server reads, the home page as websiteUrl, and a GitHub or GitLab repository. Where a hosted server runs is yours, so it lists no remotes.

{
	"name": "orders_get",
	"inputSchema": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] },
	"outputSchema": { "type": "object", "properties": { "id": { "type": "string" }, "status": { "type": "string" } } }
}

An event stream is one bounded collect: max_events (1 to 100, 20 by default) and last_event_id in, and { events, last_event_id, ended } out. When the stream names its events, each event's event is required and the declared names are its examples. Each JSON event's data is typed by its name in an anyOf member, and any other event, declared or not, has its data as a string. A stream of tick JSON events and heartbeat text events lists its events as:

{
	"type": "object",
	"properties": { "event": { "type": "string", "examples": ["tick", "heartbeat"] }, "id": { "type": "string" } },
	"required": ["data", "event"],
	"anyOf": [
		{
			"properties": {
				"event": { "const": "tick" },
				"data": { "type": "object", "properties": { "n": { "type": "number" } } }
			}
		},
		{ "properties": { "data": { "type": "string" } } }
	]
}

The server reads its configuration from the environment, under the --mcp-env-prefix (or the document's title, upper-cased):

Variable Default What it does
$<PREFIX>_BASE_URL the document's first server the API every call goes to
$<PREFIX>_API_KEY none the credential, sent as the document's scheme says; scrubbed from every result
$<PREFIX>_HEADERS none a JSON object of headers sent on every call, each scrubbed from results
$<PREFIX>_REDIRECT same-origin same-origin, or follow to follow a redirect off the API's origin with its credentials dropped
$<PREFIX>_TIMEOUT_MS 30000 each call's bound, an event stream's collect included
$<PREFIX>_FILE_ROOT the client's working dir the only directory a { path } file argument is read from
$<PREFIX>_MAX_FILE_BYTES 52428800 the largest file a path may name
$<PREFIX>_MAX_INLINE_BYTES 1048576 all inline files of one call together, decoded
$<PREFIX>_MCP_TOKEN none the bearer token --http requires; it never reaches the API

The standalone server needs Node: it holds a listening socket and reads local files, so it belongs on a machine or a container, never on serverless or Workers. To serve the same tools remotely, mount them in the app instead with mcp() from @workerstack/backend/mcp, which runs wherever the app runs and is guarded by the app's own auth.

Full reference: the generated MCP server.

Configuring generation

In a backend project the generation is configured once, in the Vite plugin, and clients generate --app reads the same app. codegen.mcp writes the handler mcp() mounts, and codegen.openApi the document the SDKs are generated from:

# the whole set, from the app module, in one run
npx clients generate --app src/app.ts \
  --target ts --target go --target python --target cli --target mcp \
  --go-module-path github.com/acme/shop/sdk --cli-repo acme/shop-cli --out generated
{
	"scripts": {
		"generate": "backend generate && clients generate --app src/app.ts --target ts --out generated"
	}
}

What each target names its package, its client class and its environment variables is the --<target>-<option> set above; nothing is read from a config file of ours, so one command line is the whole input and a CI run cannot drift from a developer's.

What a run writes

Stale files are deleted, edited ones kept. Each <out>/<target> keeps .clients-generated.json: every file the run wrote, with its sha256. A file is rewritten only when its bytes change, through a temp file renamed over it. A regeneration deletes a file the last run wrote and this one does not (a cli target's old <name>_cmds.go, say), unless it was edited since: that one is kept and named on stderr. A file the manifest never listed is never deleted, nothing outside <out>/<target> is touched, and no symlink is followed. Without a manifest, nothing is deleted.

Every target is held to the same conformance grid: one shared scenario suite runs against a live reference server for all eight targets, and each decoded answer and each request on the wire must match one expected table. A feature that works in one SDK and breaks in another fails the grid.

To lay the files out yourself, generated(run, document, ctx) from @workerstack/clients returns each target's files unwritten, each as its text but for the C# package's icon, which is its bytes, and its packages: the package on each registry it publishes to, as { registry, name, version } (npm and jsr for a scoped TS SDK, npm and mcp-registry for an MCP server with an mcpName, pypi, crates.io, nuget, maven-central as group:artifact, and go by the module path, its /vN included and no version when none is given). writeTarget(dir, files, packages) writes one target's into a directory you pick under the same rules, keeping MANIFEST (.clients-generated.json) there with the packages recorded beside the files, so a release reads each name and version from it. A file the last call wrote that you leave out of files is stale: deleted if unedited, kept and named in the result's kept if you changed it, and dropped from the manifest either way, so a file you take over by editing is never touched again.

A run kept as data (a release manifest, say) is checked with the same tables the command parses. TARGETS lists every target, and targetOptionSchemas[target] is a Standard Schema for that target's options: its option names only, each a non-empty string, a switch "true" or "false". generated checks each target's options with it before anything generates, and GenerateRun types them by target, so a misspelled option is a type error, then a refusal. GenerateRun's metadata is the --metadata-<field> block as a Metadata object, authors and keywords as arrays, checked with the same rules.

import { TARGETS, targetOptionSchemas } from "@workerstack/clients"

const result = targetOptionSchemas.go["~standard"].validate({ modulePath: "github.com/acme/shop-go" })
export const ok = result.issues === undefined && TARGETS.includes("go")

This package also exports the app-side generators the backend CLI and Vite plugin use: generateRouteTree, generateTypes and extractTypes from @workerstack/clients, and the command's own entry at @workerstack/clients/cli.

Documentation

Releasing a product's public packages

@workerstack/clients releases a product's public packages from the private repo that generates them. One release.config.ts lists the packages. clients release bump cuts each package's next version from what changed. clients release sync mirrors each package into its own public repo and pushes the v<version> tag. Each public repo's release.yml then publishes on that tag through OIDC, with no registry token stored anywhere. Three reusable workflows in workerstack/clients run these steps in CI, so a consumer repo only writes short callers.

Contents

Consumer prerequisites

  • @workerstack/clients in the repo's dependencies. The workflows-v1 workflows need 1.0.0-rc.25 or later, the first version with release codegen and release toolchains. The workflows run the consumer's own installed copy and pin none.

  • @workerstack/system in the repo's dependencies, and a system.config.ts at the repo root that declares every name the release config lists in toolchains, each at the version codegen needs:

    import { defineConfig } from "@workerstack/system"
    
    export default defineConfig({ deps: { go: "1.27.2", rust: "1.99.1", uv: "0.13.1", ruff: "0.17.1" } })
  • packageManager: "bun@<version>" in the root package.json (the workflows read Bun's version from it) and a committed bun.lock (they run bun install --frozen-lockfile, with the repo's scripts on).

release.config.ts

A product's config sits in its own directory. Each package's source dir is a sibling named after the package, and every other non-hidden directory there is an error. A package's public repo is github.com/<repo>.

import { defineRelease } from "@workerstack/clients/release"

export default defineRelease({
	project: "<product>",
	/* regenerates every package from the repo root; bump runs it, and it must honor RELEASE_VERSIONS */
	codegen: ["bun", "scripts/codegen.ts"],
	/* the system.config.ts deps codegen needs, installed in this order before it runs */
	toolchains: ["go", "rust", "uv", "ruff"],
	homepage: "https://<domain>",
	metadata: { license: "MIT", authors: ["<Name> <oss@<domain>>"] },
	packages: [
		{
			name: "cli",
			repo: "<org>/cli",
			description: "<one line: the repo's, every registry's, and the first CHANGELOG entry>",
			topics: ["<product>", "cli"],
			commitMessage: "chore: generate from openapi spec",
			clients: {
				target: "cli",
				options: { binaryName: "<bin>", modulePath: "github.com/<org>/cli", repo: "<org>/cli" },
			},
		},
		{
			name: "sdk-typescript",
			repo: "<org>/sdk-typescript",
			description: "<one line>",
			topics: ["<product>", "sdk"],
			commitMessage: "chore: generate from openapi spec",
			clients: { target: "ts" },
			registries: [{ kind: "npm" }, { kind: "jsr" }],
		},
	],
	spec: {
		committedPath: "api/openapi.public.json",
		deployedUrl: "https://api.<domain>/openapi.json",
	},
})
Field Meaning
project The product's slug: each package's <project>/<name> key, and what codegen filters on
codegen The argv that regenerates every package, run from the repo root. Bump runs it again with RELEASE_VERSIONS (JSON, package name to version) set
toolchains Optional, none by default. The system.config.ts dep names codegen needs; the workflows install them in this order
committer Optional. The identity sync commits as (public-sync[bot] by default); a GitHub App's bot address works
homepage https. Every public repo's website and every registry's homepage
metadata Optional. Package metadata every generated package carries (authors, license, keywords and the rest); a package's own metadata wins over it
packages[].clients How clients generates the package: its target and that target's options. Absent for a hand-kept package (one that publishes the spec itself)
packages[].registries Where the public repo's rendered release.yml publishes: npm, jsr, pypi, crates, go, nuget, maven, or github with assets
packages[].branch The public repo's branch sync pushes to, main by default
packages[].bootstrapExclude Globs the first push leaves out, so the next sync adds them as their own commit
spec The committed spec codegen builds from (repo-relative), and the URL prod serves it at (the deployed spec gate)

New product checklist

  1. Create or pick the GitHub org for the public repos, and an empty public repo <org>/<package> for each package. Sync pushes their content; nobody commits there by hand.
  2. Register the account-backed channels the packages need. Every registry that supports it publishes through a trusted publisher for repo <org>/<package>, workflow release.yml:
    • JSR: create @<scope> and link the package to its repo.
    • npm: npm adds a trusted publisher only to a package that exists, so publish it once by hand with a short-lived granular token, add the trusted publisher, then revoke the token.
    • PyPI: add a pending trusted publisher (it works before the first upload).
    • crates.io: publish once with cargo publish and a short-lived token, then add the trusted publisher.
    • NuGet: add a trusted-publishing policy for the repo and workflow, and set the repo variable NUGET_USER to the nuget.org user that owns it.
    • Maven Central has no OIDC: verify the namespace, generate a Portal user token, create a GPG key whose public half is on keys.openpgp.org, and add the four MAVEN_* secrets to the SDK's repo (see Secrets).
    • Go: nothing to register; the workflow's proxy.golang.org fetch indexes the tag.
    • A CLI's channels are clients cli options, each optional: a Homebrew tap repo, a Scoop bucket repo, a microsoft/winget-pkgs fork, an AUR account with an SSH key. Each one's token goes in the CLI's repo.
  3. Create a GitHub App with contents: write, workflows: write (sync pushes each repo's release.yml) and administration: write (sync sets each repo's description, homepage and topics), install it on the org's public repos, and store its ID and private key as two Actions secrets in the private repo.
  4. Write release.config.ts with a dir per package, add the prerequisites above, and check the config: clients release sync --config <path> --validate-only. A CLI also needs a hand README.md and LICENSE; clients writes its .goreleaser.yaml and .github/workflows/release.yml.
  5. Publishing needs no workflow edits: every public tree carries a release.yml (the CLI's from clients, the rest rendered from registries). Before the first real tag, run a repo's release.yml by hand with workflow_dispatch to see each registry accept it. A repo whose version is already live must get that tag pushed by hand before its first release.yml lands, or sync tags and republishes it.
  6. First release: commit the spec (bump records the commit a release is cut from), run the bump caller (or clients release bump --config <path> locally), and merge the release PR. Each package releases 1.0.0 with its description as the entry. The next sync tags each package.
  7. Verify: each public repo's release run is green (gh run list -R <org>/<package> -w release), its GitHub release has its assets, each registry serves the new version, and a CLI's tap, bucket, winget PR and AUR package show it.

The reusable workflows

A consumer calls each one from its own workflow, pinned to the workflows-v1 tag. The caller owns the triggers, the concurrency group and the permissions it grants. A reusable workflow's job never gets more than its caller grants, and secrets pass only through the declared secrets:, never secrets: inherit across owners. Every job runs the same set-up: checkout, Node 24 (the release config loads as TypeScript), Bun from packageManager, bun install --frozen-lockfile, each toolchains name through system install <name> --upgrade at its system.config.ts pin with those tools first on PATH, then release codegen.

Each workflow also takes cli, the command that runs clients, split on spaces. It defaults to bun x --no-install clients, the bin a consumer's @workerstack/clients install links. A consumer leaves it unset. This repo's own release fixture passes node bin/clients.js, because bun never links a root package's own bin.

# .github/workflows/release-sync.yml
on:
  push:
    branches: [main]
    paths: ["<product>-release/**", "api/**"]
  schedule: [{ cron: "0 3 * * *" }]
  workflow_dispatch:
    inputs:
      dry-run: { type: boolean, default: false }
      only: { type: string, required: false }
concurrency: { group: release-sync, cancel-in-progress: false }
permissions: { contents: read }
jobs:
  sync:
    uses: workerstack/clients/.github/workflows/release-sync.yml@workflows-v1
    with:
      config: <product>-release/release.config.ts
      app-owner: <org>
      dry-run: ${{ inputs.dry-run == true }}
      only: ${{ inputs.only }}
    secrets:
      app-id: ${{ secrets.RELEASE_APP_ID }}
      app-private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
release-sync.yml Meaning
config Required. The release config, repo-relative
app-owner The App installation's owner (the public repos' org); blank means the caller repo's owner
dry-run Stage each tree and report what would be pushed and tagged, pushing nothing
only Comma-separated package names (name or project/name); blank means every package
app-id, app-private-key Secrets, optional. Without both, the token step is skipped and only a dry run works (sync says GH_TOKEN env is required)
# .github/workflows/release-bump.yml
on:
  workflow_dispatch:
    inputs:
      major: { type: boolean, default: false }
permissions: { contents: write, pull-requests: write }
jobs:
  bump:
    uses: workerstack/clients/.github/workflows/release-bump.yml@workflows-v1
    with:
      config: <product>-release/release.config.ts
      major: ${{ inputs.major == true }}

release-bump.yml takes config (required) and major (release every changed package as a major). It also installs go when toolchains does not list it, because bump runs oasdiff through go run. When a package changed, it opens or updates the release PR on branch auto/release-bump with exactly the paths bump printed as wrote:. That PR is opened with the caller's GITHUB_TOKEN, so it starts no workflows of its own: run the validate caller by hand, or review the PR's diff.

# .github/workflows/release-validate.yml
on:
  pull_request:
    paths: ["<product>-release/**"]
permissions: { contents: read }
jobs:
  validate:
    uses: workerstack/clients/.github/workflows/release-validate.yml@workflows-v1
    with:
      config: <product>-release/release.config.ts

release-validate.yml takes config and runs the set-up, codegen, then release sync --validate-only.

A dry run proves the whole path short of the push: the toolchains install, codegen runs, every package's tree is staged against its public repo's current tip, its release.yml is rendered, and the report says which packages would be pushed and which v<version> tags would be created. It leaves out the push, the tag and the repo settings step.

CLI

clients release bump --config <path> [--major]
clients release sync --config <path> [--only <names>] [--dry-run] [--validate-only]
clients release bootstrap --config <path> (--all | --only <names>) [--force-bootstrap]
clients release codegen --config <path>
clients release toolchains --config <path>
  • bump regenerates, decides each package's release, gates generated output on prod, writes versions, regenerates at them, and records the release. It prints one bumped: <name> <version> <kind> line per release and one wrote: <path> line per file it touched.
  • sync mirrors each package and pushes its tag. It needs GH_TOKEN unless --dry-run or --validate-only is set.
  • bootstrap makes the first push to an empty public repo, or over the stub a new repo starts with.
  • codegen runs the config's codegen from the repo root, as bump runs it.
  • toolchains prints the config's toolchains, one per line.

Versioning

bump runs the product's codegen, then compares each package with what its .release-state.json recorded at the last release. It compares the generated output (backend's .clients-generated.json map, or the spec itself for a hand-kept package) and the tracked hand files (version lines normalized, the CHANGELOG and the state file left out). Nothing moved means no release, even when the spec moved.

When the output changed on a moved spec, oasdiff compares the spec with the one the last release was cut from (read back with git show <commit>:<path>). Any API change, breaking or not, is a minor. Output that changed with no API change, and any hand-file change, is a patch. A package stays on its major line: a major comes only from --major, which makes each package that releases a major.

A release writes the new version into every version file the package has (package.json, jsr.json, pyproject.toml). It reruns codegen with RELEASE_VERSIONS, so version-baked output is regenerated at that version. Only then does it record the digests, the spec's commit and the version in .release-state.json, so the merged release PR finds nothing left to release. The spec must be committed first, because the state records HEAD. A refusal writes nothing, so a rerun decides the same. Each public repo's release.yml checks the tag against its version files, so a tag whose files disagree fails before anything publishes.

Tags

Sync tags; the private repo never does. After sync pushes a package, or finds the bot's tip already equal to the source, it pushes v<version> from the package's .release-state.json unless that tag exists. It never moves a tag, so a rerun, or a run after one that stopped between its commit and its tag, converges. A merged release PR therefore releases every bumped package on the next sync. Never delete or move a pushed tag.

Deployed spec gate

Generated code may only describe operations prod serves. The gate fetches spec.deployedUrl and compares it with the committed spec by canonical sha. Sync refuses a package whose changed paths include a file clients generated. Bump refuses the whole run, hand-kept packages included, when a generated package whose output changed would release. On drift both print both shas and the operations on either side. Deploy, then rerun the bump caller; sync reruns on its schedule.

Channels

Package kind Channel Published by
CLI GitHub Release: archives, checksums.txt signed by cosign, build attestations, version.txt backend's release.yml in the CLI's repo
CLI Homebrew cask, Scoop manifest, winget PR, AUR <bin>-bin, deb/rpm/apk assets (each optional) the same, with its channel's secret
TypeScript SDK, MCP server npm (provenance), JSR the rendered release.yml
Go SDK the Go proxy (proxy.golang.org fetch of the tag) the rendered release.yml
Python SDK PyPI (attestations) the rendered release.yml
Rust SDK crates.io the rendered release.yml
C# SDK NuGet the rendered release.yml
Java SDK Maven Central (GPG-signed bundle through the Central Portal) the rendered release.yml
OpenAPI spec GitHub Release with openapi.json the rendered release.yml

A rendered release.yml checks the tag against the version each registry publishes from, publishes, and retries until the registry serves the version. A rejected or repeated upload fails the run; a rerun is workflow_dispatch with the tag. Go modules at 2.0.0 and up carry /v<major> in their path, which codegen adds for the go and cli targets.

Secrets

Secret Where Read by
the App's ID and private key the private repo the sync caller, passed as app-id and app-private-key
HOMEBREW_TAP_TOKEN <org>/cli goreleaser's cask push to the tap
SCOOP_BUCKET_TOKEN <org>/cli goreleaser's manifest push to the bucket
WINGET_TOKEN <org>/cli goreleaser's push to the winget-pkgs fork and its PR to microsoft/winget-pkgs
AUR_SSH_KEY <org>/cli goreleaser's push to aur.archlinux.org/<bin>-bin.git
none for npm, JSR, PyPI, crates.io, NuGet trusted publishers; NuGet's login also reads the repo variable NUGET_USER
MAVEN_CENTRAL_USERNAME, MAVEN_CENTRAL_PASSWORD <org>/sdk-java the Central Portal user token: uploads the bundle and polls until it is published
MAVEN_GPG_PRIVATE_KEY, MAVEN_GPG_PASSPHRASE <org>/sdk-java signs every bundle file; the public key must be on a keyserver Central reads

Gates

Script contract

This repo has these package.json scripts. Hooks and CI call only these names, so a tool change is one line in package.json.

script runs
fmt / fmt:check repo fmt: oxfmt with the standards pack's generated .oxfmtrc.jsonc
lint / lint:fix repo lint: oxlint with the generated .oxlintrc.jsonc, the repo's own plugin in lint/
typecheck tsc -p tsconfig.json: src, tests and scripts
typecheck:src tsc -p tsconfig.src.json: the source under the strict preset
test the repo's suite

The lint and format configs, knip.jsonc and the git hooks are written by bun repo sync from repo.config.ts. The repo's own lint rules are lint.plugins and lint.rules there; a rule that does not fit a file is a lint.skip entry with its reason, and a use knip cannot see is a knip.ignore entry with its reason.

Where each gate runs

when what blocks
pre-commit repo precommit: fmt and lint --fix on the staged files (restaged), lint held to the baseline, typecheck, sync, the related tests, repo check the commit
commit-msg repo commit-msg: Conventional Commits and the change-size rule the commit
pre-push repo link --pre-push, then repo commit-msg --pre-push on each pushed commit the push
CI on every push to main: the commits job (repo commit-msg --range), fmt:check, repo check, typecheck, typecheck:src, test, test:harness new work, until fixed

bun repo sync points core.hooksPath at .githooks/, so the hooks come with bun install.

Push and CI

No full suite runs locally. Each commit runs the tests its change reaches: the touched test files and the tests of the code it changed. Then push, and run bun repo ci wait in the background. It waits for CI's run on the pushed commit and names any failed job and its log. A push cancels the run before it, so batch the commits and push once.

Release

The version bump rides in the final push. Only a commit CI passed on main gets the v* tag. The release workflow runs no tests: it waits for that commit's ci.yml push run and publishes on its success, so a bump made after the green push is a new commit and costs another CI run. The tag's notes are the ## [Unreleased] entry of CHANGELOG.md for a prerelease and the dated ## [x.y.z] - YYYY-MM-DD entry for a final release; scripts/changelog.ts refuses a tag without them.

Browsers

  • Chrome: offscreen --hypr adds a hidden virtual monitor to the running Hyprland; tests drive Chrome on it over CDP. It never takes focus. exec and run are refused in that mode.
  • Safari: the MacBook Air M3 over Tailscale (ssh mac, safaridriver -p 4799), one run at a time.

Red, fix, green

  1. Red: write the test that shows the bug or the missing behavior. Run it. It must fail, for the reason the test names. Record the failing output (BUGS.md for a bug, where the repo has one).
  2. Fix: the smallest change that makes it pass.
  3. Green: run it again and record the passing output. Then run the tests the change reaches, and leave the full gates to CI on the push.

A test that cannot fail proves nothing. Check it: revert or break the fix, and the test must go red.

Commits: the test and the fix may share a commit or come as test(...) then fix(...). A fix or feat commit always contains a test change.

Lint rules follow the same loop. A mistake that a rule could catch mechanically ships with a rule: a RuleTester case that fails first, then the rule, in the repo's lint/ plugin.

License

MIT