@jutsustack/api-codegen
v0.2.1
Published
Generate a typed API layer from Postman, Swagger and OpenAPI collections for React, React Native, Next.js, Vue, Angular, Svelte, SolidJS or plain TypeScript, on fetch, axios, react-native-fetch, Angular HttpClient or your own HTTP client
Maintainers
Readme
@jutsustack/api-codegen
Generate a typed API layer from Postman collections, Swagger 2.0 and OpenAPI 3.x documents, so you never hand-write an API call, its types or its loading state again.
New here? Follow the step-by-step guide: Using api-codegen in your app.
- Any framework: React, React Native, Next.js, Vue, Angular, Svelte, SolidJS, or plain TypeScript / JavaScript.
- Any HTTP client:
fetch,axios,@jutsustack/react-native-fetch, AngularHttpClient, or your own function. You choose the client; the generated code doesn't depend on any of them.
const user = await api.users.getUser({ params: { id: 42 } }); // → User
try {
await api.auth.login({ body: { email, password } });
} catch (error) {
const failure = api.auth.login.errorOf(error); // { status: 401; data: LoginError } | undefined
toast(getErrorMessage(error)); // "Wrong email or password." (configurable per API)
}- Duplicate requests become one endpoint. "Login – Success" and "Login – Wrong password"
(or
/users/1and/users/:id) merge into one function with typed success and error bodies. - Per-API control: timeouts, retries with back-off, fallbacks, error messages, logging with secrets redacted, performance metrics and loading state, set globally, per endpoint or per call.
- Bindings for your framework: hooks, composables, signals, stores or primitives with
status,isLoading,error,refetch, built on one tested framework-neutral core. - Codegen only. The package generates code and adds no runtime dependency to your app.
The generated files import only your framework, and the HTTP library only in
client.ts. - Skips work when nothing changed, and never overwrites hand-edited files.
- Strict-mode clean. Generated code compiles under
strict,exactOptionalPropertyTypesandnoUncheckedIndexedAccess.
Install
Pick your package manager. The package works the same with all of them, as ESM or CommonJS.
npm i -D @jutsustack/api-codegen
pnpm add -D @jutsustack/api-codegen
yarn add -D @jutsustack/api-codegen
bun add -d @jutsustack/api-codegenRequirements: Node.js 18.18+ (or Bun) to run the CLI, TypeScript 5+ in the app.
Quick start
npx jutsu-api init --source ./api/my-app.postman_collection.json # creates my-app-api.config.json
npx jutsu-api # generates src/apiUse pnpm exec jutsu-api, yarn jutsu-api or bunx jutsu-api with other package managers.
init reads your package.json to choose framework and httpClient (for example Vue with
axios); override with --framework and --http-client.
✎ src/api/api-collection.json
✎ src/api/runtime.ts
✎ src/api/types.ts
✎ src/api/api.ts
✎ src/api/hooks.ts
✎ src/api/index.ts
✎ src/api/client.ts
✔ Updated 7 file(s) in src/api: 10 endpoints in 4 group(s), 3 merged from duplicate requests [react + fetch]Configure the client once in src/api/client.ts (base URL, auth, retries, logging), then call
api.<group>.<endpoint>(). init adds the .jutsu-api/ cache folder to an existing
.gitignore. If you use ESLint, also ignore the output folder: generated files start with
/* eslint-disable */, which ESLint 9 reports as unused.
How it works
The package is a build-time tool. It reads your Postman or Swagger file and writes a typed
API folder into your app. Your app imports from that folder, not from
@jutsustack/api-codegen, which stays a dev dependency.
Postman / Swagger file ──► npx jutsu-api ──► src/api/ (written for you)
(dev dependency) │
▼
your app imports from src/api1. Generate. A Postman request such as Get user GET {{baseUrl}}/users/:id becomes:
// src/api/types.ts (generated)
export interface GetUserResponse {
id: number;
name: string;
email: string;
}
// src/api/api.ts (generated)
getUser: endpoint<GetUserArgs, GetUserResponse, GetUserErrors>(client, {
id: 'users.getUser',
method: 'GET',
path: '/users/:id',
}),2. Connect your HTTP library, once, in src/api/client.ts. This file is yours and is
never overwritten:
// src/api/client.ts
import axios from 'axios';
import { createApi, createClient } from './index'; // the generated code
const http = axios.create();
http.interceptors.request.use((config) => {
config.headers['x-app-version'] = '1.0.0'; // your axios setup keeps working
return config;
});
export const client = createClient({
baseURL: 'https://api.example.com',
http, // leave it out to use fetch
getToken: () => localStorage.getItem('token'),
retry: true,
});
export const api = createApi(client);3. Call it anywhere, typed:
import { api } from './api/client';
const user = await api.users.getUser({ params: { id: 7 } });
user.name; // stringWhat happens on that call:
api.users.getUser({ params: { id: 7 } }) your code
→ endpoint users.getUser: GET /users/:id src/api/api.ts
→ client: URL, Bearer token, timeout, retries, middleware src/api/runtime.ts
→ your axios instance (interceptors run) axios
→ server: 200 { id: 7, … } or 404
→ client: data typed as GetUserResponse, or an ApiError with your messageWhen the API changes, update the collection and run npx jutsu-api again. To switch HTTP
library, change the http line in client.ts; the rest of your code stays the same.
Config
One file per project, <project-name>-api.config.json, next to package.json. Use
--config when a folder holds several.
{
"$schema": "./node_modules/@jutsustack/api-codegen/schema/config.schema.json",
"project": "shop-app",
"framework": "vue",
"httpClient": "axios",
"output": "src/api",
"sources": [
{ "id": "shop", "path": "./api/shop.postman_collection.json" },
{ "id": "payments", "url": "https://payments.example.com/openapi.yaml" }
]
}| Option | Default | Description |
| ----------------- | ------------------------------- | ---------------------------------------------------------------------------------------- |
| project | required | Project name |
| framework | required | react, react-native, next, vue, angular, svelte, solid or none |
| httpClient | fetch (angular for Angular) | fetch, axios, react-native-fetch, angular or custom: what client.ts wires up |
| output | required | Output folder, relative to the config; must stay inside the project |
| sources | required | See Sources |
| baseUrl | first server found | Base URL for the client.ts scaffold |
| methods | GET POST PUT PATCH DELETE | Methods to generate (HEAD, OPTIONS also allowed) |
| groupBy | folder | folder / tag, path (first path segment) or none |
| hooks | true | Generate the framework bindings |
| include | all | Globs to keep, e.g. "/users/**", "GET /orders/*" |
| exclude | none | Globs to skip |
| format | none | prettier formats output with the project's prettier |
| importExtension | "" | ".js" for apps using moduleResolution: NodeNext |
| cacheDir | .jutsu-api | Cache folder |
| target | deprecated | v0.1 option, still read; see Migrating |
Unknown options are errors, reported with their path (sources[1].url: must be an http(s) URL).
Sources
Each source has a unique id and one of path, url or postman. The format is detected
from the content; type (postman, openapi, swagger) enforces it.
| Source | Example |
| ------------------- | ----------------------------------------------------------------------------------------- |
| File (JSON / YAML) | { "id": "core", "path": "./api/core.postman_collection.json" } |
| URL | { "id": "pets", "url": "https://api.example.com/openapi.json" } |
| URL with auth | { "id": "pets", "url": "…", "headers": { "Authorization": "Bearer ${SPEC_TOKEN}" } } |
| Postman workspace | { "id": "cloud", "postman": { "collectionId": "12345-abcd" } } (key: POSTMAN_API_KEY) |
| Postman environment | add "environment": "./api/dev.postman_environment.json" to resolve {{baseUrl}} |
${VAR} values come from the environment and are never written to disk.
How duplicate requests are merged
Two requests are the same API when the method matches and the paths match after parameter
segments are normalised: GET /users/:id, /users/{{userId}}, /users/42 and a UUID path are
one endpoint.
- Name: the OpenAPI
operationId, else the most common Postman title without scenario words (Login – Success,Login (401)→login), else method + path (getUsersById). - Responses: 2xx examples form the success type; 4xx/5xx examples the error type per status.
- Request body: bodies of all examples are merged; fields only some examples send become optional.
- Precedence: OpenAPI schemas win over Postman examples. Clashing model names from
different specs are renamed
<SourceId><Name>, with a warning.
api-collection.json records every endpoint with its origins, so merges can be reviewed in
pull requests.
What gets generated
| File | Contents |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| api-collection.json | The merged collection |
| runtime.ts | createClient, ApiError, retries, messages, logging, metrics, middleware, request controllers, HTTP library adapters |
| types.ts | Models and XArgs / XResponse / XErrors types per endpoint |
| api.ts | createApi(client, options) → { group: { endpoint } }, plus the Endpoints map |
| bindings | hooks.ts, composables.ts, angular.ts, stores.ts or primitives.ts |
| index.ts | Re-exports (on Next.js, import hooks from ./hooks) |
| client.ts | Yours: created once, never overwritten |
runtime.ts imports nothing: every HTTP library adapter is typed structurally, so it
compiles whether or not axios, Angular or react-native-fetch is installed. Endpoints get
defaults from the sources: skipAuth for requests that opt out of auth (Postman noauth,
OpenAPI security: []), and contentType / responseType for non-JSON bodies.
Choosing the HTTP client
Pass the library you already use as http. Leave it out to use fetch. You can switch at any
time in client.ts without regenerating.
import axios from 'axios';
import { createApi, createClient } from './api';
createClient({ baseURL }); // fetch: browser, Node, Bun, Deno, edge, React Native
createClient({ baseURL, http: myFetch }); // any fetch-compatible function
createClient({ baseURL, http: axios }); // axios itself…
createClient({ baseURL, http: axios.create({ … }) }); // …or your instance: interceptors keep working
createClient({ http: createJutsuClient({ baseURL, ssl, auth }) }); // react-native-fetch: SSL pinning, token refresh
createClient({ baseURL, http: inject(HttpClient) }); // Angular: interceptors, XSRFThe library is recognised by its shape: axios by its interceptors, Angular's HttpClient by
jsonp, any other object with request(method, url, options) as a react-native-fetch
client, and a plain function as fetch. To name it explicitly, use fetchTransport({ fetch, init }),
axiosTransport(instance), reactNativeFetchTransport(client) or
angularHttpTransport(http) as transport.
For any other library, write a small transport function:
import { createClient, encodeBody } from './api';
createClient({
baseURL,
transport: async (request) => {
const headers = { ...request.headers };
const body = encodeBody(request.body, request.contentType, headers); // JSON, form, text…
const res = await myHttp.send(request.method, request.url, {
headers,
body,
signal: request.signal,
});
return { status: res.status, headers: res.headers, data: res.body }; // every status, even 4xx/5xx
},
});Resolve for every HTTP status; throw only when no response arrived (offline, DNS). Return the
library's fields as they are: headers in any shape (mixed case, arrays, a Headers object),
and data as parsed data or JSON text, which the client parses when the response is JSON.
docs/USAGE.md has tested recipes for ky, got,
superagent and ofetch.
The client (not the HTTP library) owns timeouts, retries, error mapping and messages, so they
behave the same whatever you pass. Library-specific options go in adapterOptions (axios
config, Angular options, react-native-fetch's cachePolicy, …).
Middleware
Middleware wraps every attempt, between the client and the transport, so the same code works
with fetch, axios, react-native-fetch, Angular HttpClient or your own transport. It gets the
request and next, and resolves with the response:
import type { Middleware } from './api';
// change the request
const trace: Middleware = (request, next) =>
next({
...request,
headers: { ...request.headers, 'x-trace-id': crypto.randomUUID() },
});
// change the response, e.g. unwrap { data: … }
const unwrap: Middleware = async (request, next) => {
const response = await next(request);
const body = response.data as { data?: unknown } | null;
return { ...response, data: body?.data ?? response.data };
};
// repeat the request: refresh the token once on 401
const refreshOn401: Middleware = async (request, next) => {
const response = await next(request);
if (response.status !== 401 || request.skipAuth) return response;
const token = await session.refresh();
return next({
...request,
headers: { ...request.headers, authorization: 'Bearer ' + token },
});
};
// answer without the network (mocks, offline cache)
const mock: Middleware = async (request, next) =>
request.endpoint === 'products.list'
? { status: 200, headers: {}, data: fixtures.products }
: next(request);Add it at any level. Levels add up (they don't replace each other) and run outermost first: client, then endpoint, then call, then the transport.
const client = createClient({
http: axios,
middleware: [trace, refreshOn401, unwrap],
});
const api = createApi(client, {
endpoints: { 'products.list': { middleware: [mock] } },
});
await api.orders.list({ middleware: [timing] });
// or build a transport once and use it anywhere
const transport = applyMiddleware(fetchTransport(), [trace, unwrap]);The contract is the transport's: resolve for every HTTP status, and throw only when there is no
response. The client then applies timeouts, retries (middleware runs on each attempt and sees
request.attempt), error mapping, messages, logging and metrics as usual. A middleware that
throws gives a NETWORK error with the cause in originalError. A middleware that hangs still
times out. If a middleware sends a request to an origin that isn't trusted (see
Credentials), the client's token and headers are removed
before it goes out.
Middleware or onRequest? onRequest can only change headers, while middleware can also
change the response, repeat or short-circuit a call. Your HTTP library's own interceptors
(axios, Angular) keep working too, inside the transport.
Per-API control
Every option works at three levels: client (createClient), endpoint
(createApi(client, { endpoints }), type-checked against your API) and call (the args of
one call). The more specific level wins.
export const client = createClient({
baseURL: 'https://api.example.com',
getToken: () => session.token, // Bearer header unless the endpoint skips auth
timeoutMs: 15_000, // per attempt (default 30 s)
retry: true, // see Retries
logger: import.meta.env.DEV, // see Logging
slowRequestMs: 2_000,
onMetrics: (m) => analytics.track('api_call', m),
onLoadingChange: (pending) => progressBar.toggle(pending > 0),
messages: { 401: 'Your session expired. Please sign in again.' },
});
export const api = createApi(client, {
endpoints: {
'auth.login': { messages: { 401: 'Wrong email or password.' }, log: false },
'products.list': { retry: 3, fallback: () => cachedProducts() },
'payments.charge': { timeoutMs: 60_000 },
},
});
await api.products.get({
params: { id },
timeoutMs: 5_000,
messages: { 404: 'This product is gone.' },
});Error handling and messages
Every failure is an ApiError with kind (HTTP, NETWORK, TIMEOUT, ABORTED, PARSE),
status, data, headers, endpoint and userMessage, a text safe to show people.
messagesmaps an exact status (404), a class ('4XX','5XX'), a kind ('NETWORK','TIMEOUT') or'default'to a string or a function. Built-in English defaults cover the rest (defaultErrorMessages).- Server error text is not shown by default. Opt in with
messageFromResponse: (e) => e.data?.message. getErrorMessage(error)returns a message for anything thrown;errorOf(error)returns the typed body of a documented error response.ApiError.messageandJSON.stringify(error)leave out the query string, the response body and response headers (Set-Cookie), so they stay out of logs and error trackers. The fields themselves (error.data,error.headers) are still there in code.
Retries
retry: true retries network errors, timeouts and 408 / 429 / 500 / 502 / 503 / 504 up to 2
times, with exponential back-off and jitter, honouring Retry-After.
- Only idempotent methods (GET, HEAD, OPTIONS, PUT, DELETE) are retried, plus calls with an
idempotencyKey(sent asIdempotency-Key). A payment is never sent twice by accident. retry: 3sets the attempts;{ attempts, delayMs, maxDelayMs, retryOn }gives full control. Even a customretryOncannot retry a POST or PATCH that has noidempotencyKey.- Cancelled calls are never retried; a cancel during back-off stops at once.
Fallbacks
fallback: (error) => value resolves with a value instead of throwing, for example a cached
list when the server is down. It is typed against the endpoint's response.
.raw()returnsfromFallback: trueand every binding's state hasfromFallback, so the UI can mark the data as stale or offline. Metrics count it too.- A fallback never runs for cancelled calls. A fallback that throws replaces the error.
Logging
logger: true logs to the console; any object with debug / info / warn / error works
(pino, Sentry breadcrumbs, …).
logLeveldefaults to'info'.- Logs show the method, path template, status and duration. Headers such as
Authorization,CookieandX-Api-Keyare[redacted](redactHeaderssets the list). Query strings and bodies are left out unlesslogBodies: true. logBodiesis for development only: bodies can hold passwords and tokens. Keeplog: falseon auth endpoints if you turn it on.log: falsesilences one endpoint or call.- A logger that throws never breaks a request.
Performance
onMetrics receives every call: endpoint, method, path (template, no ids), status,
ok, errorKind, durationMs, attempts, fromFallback and slow. Calls slower than
slowRequestMs are also logged as warnings. .raw() exposes durationMs and attempts.
Loading state
- Global:
onLoadingChange(pending),client.pendingandclient.subscribe(listener); each binding has ausePendingRequests/injectPendingRequests/pendingRequestshelper. - Per call:
onLoading: (loading) => …runs withtruewhen the call starts andfalsewhen it settles, failures included. - Per component: the bindings below return
status,isLoading,isError,isSuccess,data,error,fromFallbackandrefetch.
Credentials and other origins
getToken and the client headers go only to relative URLs and to baseURL's origin. Any
other absolute URL, such as a presigned upload or a third-party API, gets only the headers of
that call. List extra origins that should receive them in trustedOrigins:
createClient({
baseURL,
transport,
getToken,
trustedOrigins: ['https://files.example.com'],
});timeoutMs and retry delays are validated: a negative or non-numeric value uses the default
instead of turning the timeout off (0 turns it off), and very large values are capped.
Hooks and callbacks
onRequest(request) runs before each attempt and may add headers (trace ids). onResponse and
onError observe results. Observers that throw are ignored, so they can't break a call.
Framework bindings
All bindings wrap the same createQueryController / createMutationController.
- Queries (GET / HEAD / OPTIONS) refetch when their args change by value, abort the previous call, ignore stale responses and keep the last data while reloading.
- Mutations expose
run(never rejects),runAsyncandreset. Thededupeoption blocks double submits; it is off by default because concurrent writes (toggles) are sometimes intended. - Query options:
enabled,keepPreviousData,onSuccess,onError,onSettled. Mutations take the same callbacks plusdedupe. - Every binding also accepts
configureApi(client)for apps with one client.
React and React Native
<ApiProvider client={client}>
<App />
</ApiProvider>;
const user = useGetUser({ params: { id } }, { enabled: !!id });
const login = useLogin({ onSuccess: () => navigate('/home') });
const busy = usePendingRequests();
if (user.isLoading) return <Spinner />;React Native works with any HTTP client, exactly like the web. Pick one in client.ts:
createClient({ baseURL }); // fetch, built into React Native
createClient({ baseURL, http: axios }); // axios, or your axios.create() instance
createClient({ http: createJutsuClient({ baseURL, ssl, auth }) }); // @jutsustack/react-native-fetchUse @jutsustack/react-native-fetch only if you want its SSL pinning and token refresh. Its
refresh handler gets an http that bypasses auth, so the refresh can call a generated endpoint:
const jutsu = createJutsuClient({
baseURL: 'https://api.example.com',
auth: {
tokenStore: createMemoryTokenStore(),
refresh: {
handler: async ({ refreshToken, http }) => {
const t = await createApi(createClient({ http })).auth.refreshSession({
body: { refreshToken: refreshToken ?? '' },
});
return { accessToken: t.accessToken, refreshToken: t.refreshToken };
},
},
},
});
export const client = createClient({ http: jutsu });Multipart file parts on React Native are { uri, name, type }.
Next.js
Endpoints are plain async functions, usable in Server Components, Route Handlers and Server
Actions. With Cache Components (the Next.js 16 default), cache a call in a 'use cache'
function:
export async function getPets() {
'use cache';
cacheLife('minutes');
cacheTag('pets');
return api.pets.listPets();
}Without Cache Components, pass init: { next: { revalidate: 60, tags: ['pets'] } }.
hooks.ts starts with 'use client'; import it from @/lib/api/hooks. The scaffolded
client.ts reads NEXT_PUBLIC_API_BASE_URL. On the server, pass per-request tokens with
headers rather than module state.
Vue 3.3+ (and Nuxt)
app.use(createApiPlugin(client)); // or provideApi(client) in a parent's setup()
const id = ref(1);
const user = useGetUser(() => ({ params: { id: id.value } })); // refs, getters or values
user.data.value;
user.isLoading.value;
user.refetch();Composables are disposed with their effect scope, which aborts calls in flight.
Angular 17+
// app.config.ts
providers: [provideHttpClient(withInterceptors([authInterceptor])), provideApi(createAppClient)];
// a component or service (injection context)
readonly id = signal(1);
readonly user = injectGetUser(() => ({ params: { id: this.id() } })); // signals in, signals out
readonly save = injectUpdateUser({ onSuccess: () => this.user.refetch() });
// template: @if (user.isLoading()) { … } {{ user.data()?.name }}With httpClient: "angular", calls go through HttpClient, so interceptors and XSRF
protection apply. injectApi() returns the api object; from(api.users.getUser(…)) turns a
call into an Observable.
Svelte 4 / 5 (and SvelteKit)
<script>
import { derived, writable } from 'svelte/store';
import { createGetUser, setApiContext } from '$lib/api';
const id = writable(1);
const user = createGetUser(derived(id, (id) => ({ params: { id } })));
</script>
{#if $user.isLoading}…{:else}{$user.data?.name}{/if}Call setApiContext(client) in a root component, or configureApi(client) once. Stores run
while subscribed and abort when the last subscriber leaves. In SvelteKit load functions,
call api directly.
SolidJS 1.8+ and 2.x
const value = apiContextValue(client);
<ApiContext.Provider value={value}>
<App />
</ApiContext.Provider>; // Solid 2: <ApiContext value={value}>
const [id, setId] = createSignal(1);
const user = createGetUser(() => ({ params: { id: id() } }));
user.data();
user.isLoading();Plain TypeScript / JavaScript (framework: "none")
Use api directly. For another UI library (Lit, Qwik, Preact signals, …), bind
createQueryController / createMutationController from runtime.ts. Each has
getState() and subscribe().
Using the generated API
await api.users.getUser({ params: { id: 1 } }); // data
await api.users.getUser.raw({ params: { id: 1 } }); // { data, status, headers, durationMs, attempts, fromFallback }
api.users.getUser.errorOf(error); // typed documented error, or undefined
api.users.getUser.id; // 'users.getUser', the key in createApi(client, { endpoints })params, query and body are required exactly when the API needs them. errorOf(error)
returns { status, data } for documented error responses and undefined for anything else.
A 4XX / 5XX response matches any status of that class, and default matches any error status.
Caching
A run is skipped when the generator version, the config and every source's content hash match
the last run and the generated files are untouched. The state lives in
.jutsu-api/<project>/manifest.json.
- URLs are fetched with
If-None-Match/If-Modified-Since; a 304 reuses the saved copy. - Network errors and 5xx fall back to the saved copy with a warning; 4xx fails.
--offlineuses only saved copies.- Only files whose content changed are rewritten.
Each generated file carries a // @checksum sha256:… header. If a generated file was edited,
or a file with the same name was not created by the tool, generation stops and lists it. Move
the change to client.ts, or use --force.
CLI
jutsu-api [generate|check|collect|init] [options]| Command | Description |
| ---------- | ------------------------------------------------------------------------------------ |
| generate | Build the collection and the client (default) |
| check | Exit 1 when generated files are out of date (CI) |
| collect | Only build api-collection.json |
| init | Create the config (--name, --framework, --http-client, --source, --output) |
Options: -c, --config <file>, --cwd <dir>, -f, --force, --offline, --dry-run,
-q, --quiet, -v, --verbose. Exit codes: 0 ok, 1 failure or stale, 2 usage / config
error.
In CI, commit the generated files and run npx jutsu-api check. It regenerates in memory
and ignores the cache. Remote sources need network access and their secrets in CI.
The same functions are exported for scripts, from import and require alike: generate,
check, collect, init, detectFramework, detectHttpClient, plus parsePostman,
parseOpenApi, buildCollection and emitFiles.
Migrating from 0.1
0.2 makes the HTTP client your choice, so the generated code no longer depends on any library.
Config: replace
"target"with"framework"and add"httpClient".react-nativebecomes"framework": "react-native"+"httpClient": "react-native-fetch".react/nextbecome"framework": "react"/"next"+"httpClient": "fetch".
Old configs still load, with a warning, and map exactly this way.
client.tsis yours, so it isn't regenerated. Wrap your client increateClient.- Web:
createFetchClient({ … })becomescreateClient({ … }). A customfetchbecomeshttp: myFetch;initmoves totransport: fetchTransport({ fetch, init }). - React Native:
createApi(createJutsuClient(…))becomescreateApi(createClient({ http: createJutsuClient(…) })).
Delete
client.tsand regenerate to get the new scaffold.- Web:
React Native hooks now come from the generated
ApiProvider(no<JutsuProvider>needed for them). Theoptimisticmutation option is gone; useonSuccess/onError.React Native call options that belong to the library (
cachePolicy,tag,dedupe) move intoadapterOptions.idempotencyKey,skipAuth,timeoutMsandsignalstay where they are.
Security
- Strings from specs are escaped before they reach generated code; identifiers are reduced
to
[A-Za-z0-9_$]. - API keys and
${VAR}headers are never written to disk or logs, and are not forwarded on redirects to another origin. URLs with embedded credentials are rejected. - Output and cache folders must be inside the project.
- Downloads are capped at 50 MB and 30 s; YAML aliases and schema depth are limited.
- Generated runtime:
- Logs redact credentials and leave out bodies and query strings by default.
- Header values with line breaks are rejected (header injection).
./..path params are rejected (path traversal).- Server error text is not shown to people unless you opt in.
- Non-idempotent requests are not retried without an idempotency key.
- The token and client headers never reach origins you did not trust.
- Serialised errors carry no response bodies,
Set-Cookieor query strings.
Report vulnerabilities privately; see SECURITY.md. The latest quality and security audit is in testcase.md.
Troubleshooting
| Message / symptom | Fix |
| --------------------------------------- | ----------------------------------------------------------------------------------- |
| No <project>-api.config.json | Run npx jutsu-api init or pass --config |
| generated file(s) were edited by hand | Move the change to client.ts, then --force |
| Source "x" … answered 401 | Check headers / POSTMAN_API_KEY; --offline uses the saved copy |
| segment "{name}.{ext}" mixes text … | Pass the whole segment as one param, e.g. nameAndExt: 'a.pdf' |
| A Postman field is unknown | Its example was {{variable}} or null; save a real example |
| Imports fail with NodeNext | Set "importExtension": ".js" |
| No API client: … | Add the provider / plugin the message names, or call configureApi |
| "target" is deprecated | Replace it with framework (and httpClient), see Migrating |
Examples
examples/shop-app is the generated output for a Postman collection
plus an OpenAPI document; CI checks that it is up to date.
examples/demo generates one Postman collection for the public
dummyjson.com API into React Native, React and Next.js apps, with
live tests against the real API. Run them with examples/demo/verify.sh (Node 22).
Development
yarn install
yarn verify # lint, typecheck, tests, ESM + CJS build, CLI smoke test, tarball check
yarn smoke:pm # pack, install and run with npm, pnpm, yarn and bunsrc/parsers reads sources, src/collect merges them into the collection, src/codegen
writes the files, and src/generate.ts handles caching and writes.
test/typecheck.test.tscompiles the generated code for every framework and HTTP client under strict settings, against the real axios, Angular, Vue, Svelte, Solid 1 and 2 and React types.test/runtime.test.tsandtest/bindings*.test.tsrun the generated code in Node, React 19 (StrictMode), Vue and Svelte.
License
MIT © JutsuStack
