@jutsustack/api-codegen 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +574 -141
  2. package/dist/cache/manifest.d.ts +0 -1
  3. package/dist/cache/manifest.d.ts.map +1 -1
  4. package/dist/cache/manifest.js +1 -1
  5. package/dist/cache/manifest.js.map +1 -1
  6. package/dist/cjs/cache/manifest.d.ts +34 -0
  7. package/dist/cjs/cache/manifest.js +45 -0
  8. package/dist/cjs/cli.d.ts +8 -0
  9. package/dist/cjs/cli.js +245 -0
  10. package/dist/cjs/codegen/emit-api.d.ts +6 -0
  11. package/dist/cjs/codegen/emit-api.js +108 -0
  12. package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
  13. package/dist/cjs/codegen/emit-bindings.js +115 -0
  14. package/dist/cjs/codegen/emit-types.d.ts +10 -0
  15. package/dist/cjs/codegen/emit-types.js +232 -0
  16. package/dist/cjs/codegen/emit.d.ts +28 -0
  17. package/dist/cjs/codegen/emit.js +180 -0
  18. package/dist/cjs/codegen/files.d.ts +14 -0
  19. package/dist/cjs/codegen/files.js +66 -0
  20. package/dist/cjs/codegen/plan.d.ts +32 -0
  21. package/dist/cjs/codegen/plan.js +84 -0
  22. package/dist/cjs/codegen/print.d.ts +10 -0
  23. package/dist/cjs/codegen/print.js +65 -0
  24. package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
  25. package/dist/cjs/codegen/templates/bindings.js +707 -0
  26. package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
  27. package/dist/cjs/codegen/templates/runtime.js +1401 -0
  28. package/dist/cjs/codegen/templates/transports.d.ts +1 -0
  29. package/dist/cjs/codegen/templates/transports.js +272 -0
  30. package/dist/cjs/codegen/tsType.d.ts +15 -0
  31. package/dist/cjs/codegen/tsType.js +114 -0
  32. package/dist/cjs/collect/collect.d.ts +16 -0
  33. package/dist/cjs/collect/collect.js +472 -0
  34. package/dist/cjs/collect/naming.d.ts +25 -0
  35. package/dist/cjs/collect/naming.js +149 -0
  36. package/dist/cjs/collect/path.d.ts +10 -0
  37. package/dist/cjs/collect/path.js +67 -0
  38. package/dist/cjs/config/init.d.ts +37 -0
  39. package/dist/cjs/config/init.js +143 -0
  40. package/dist/cjs/config/load.d.ts +11 -0
  41. package/dist/cjs/config/load.js +121 -0
  42. package/dist/cjs/config/types.d.ts +88 -0
  43. package/dist/cjs/config/types.js +2 -0
  44. package/dist/cjs/config/validate.d.ts +8 -0
  45. package/dist/cjs/config/validate.js +200 -0
  46. package/dist/cjs/generate.d.ts +55 -0
  47. package/dist/cjs/generate.js +263 -0
  48. package/dist/cjs/index.d.ts +23 -0
  49. package/dist/cjs/index.js +48 -0
  50. package/dist/cjs/model/collection.d.ts +83 -0
  51. package/dist/cjs/model/collection.js +16 -0
  52. package/dist/cjs/model/infer.d.ts +7 -0
  53. package/dist/cjs/model/infer.js +95 -0
  54. package/dist/cjs/model/merge.d.ts +3 -0
  55. package/dist/cjs/model/merge.js +131 -0
  56. package/dist/cjs/model/reserved.d.ts +2 -0
  57. package/dist/cjs/model/reserved.js +128 -0
  58. package/dist/cjs/model/schema.d.ts +54 -0
  59. package/dist/cjs/model/schema.js +2 -0
  60. package/dist/cjs/package.json +1 -0
  61. package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
  62. package/dist/cjs/parsers/openapi-schema.js +241 -0
  63. package/dist/cjs/parsers/openapi.d.ts +8 -0
  64. package/dist/cjs/parsers/openapi.js +435 -0
  65. package/dist/cjs/parsers/postman.d.ts +20 -0
  66. package/dist/cjs/parsers/postman.js +493 -0
  67. package/dist/cjs/parsers/types.d.ts +52 -0
  68. package/dist/cjs/parsers/types.js +2 -0
  69. package/dist/cjs/sources/load.d.ts +25 -0
  70. package/dist/cjs/sources/load.js +296 -0
  71. package/dist/cjs/sources/parse.d.ts +4 -0
  72. package/dist/cjs/sources/parse.js +50 -0
  73. package/dist/cjs/util/errors.d.ts +9 -0
  74. package/dist/cjs/util/errors.js +23 -0
  75. package/dist/cjs/util/fs.d.ts +7 -0
  76. package/dist/cjs/util/fs.js +44 -0
  77. package/dist/cjs/util/hash.d.ts +3 -0
  78. package/dist/cjs/util/hash.js +26 -0
  79. package/dist/cjs/util/json.d.ts +10 -0
  80. package/dist/cjs/util/json.js +31 -0
  81. package/dist/cjs/util/log.d.ts +22 -0
  82. package/dist/cjs/util/log.js +45 -0
  83. package/dist/cjs/version.d.ts +2 -0
  84. package/dist/cjs/version.js +6 -0
  85. package/dist/cli.d.ts +3 -1
  86. package/dist/cli.d.ts.map +1 -1
  87. package/dist/cli.js +42 -12
  88. package/dist/cli.js.map +1 -1
  89. package/dist/codegen/emit-api.d.ts +3 -1
  90. package/dist/codegen/emit-api.d.ts.map +1 -1
  91. package/dist/codegen/emit-api.js +32 -7
  92. package/dist/codegen/emit-api.js.map +1 -1
  93. package/dist/codegen/emit-bindings.d.ts +9 -0
  94. package/dist/codegen/emit-bindings.d.ts.map +1 -0
  95. package/dist/codegen/emit-bindings.js +112 -0
  96. package/dist/codegen/emit-bindings.js.map +1 -0
  97. package/dist/codegen/emit-types.d.ts +8 -1
  98. package/dist/codegen/emit-types.d.ts.map +1 -1
  99. package/dist/codegen/emit-types.js +10 -8
  100. package/dist/codegen/emit-types.js.map +1 -1
  101. package/dist/codegen/emit.d.ts +10 -1
  102. package/dist/codegen/emit.d.ts.map +1 -1
  103. package/dist/codegen/emit.js +142 -37
  104. package/dist/codegen/emit.js.map +1 -1
  105. package/dist/codegen/files.d.ts +3 -12
  106. package/dist/codegen/files.d.ts.map +1 -1
  107. package/dist/codegen/files.js +3 -12
  108. package/dist/codegen/files.js.map +1 -1
  109. package/dist/codegen/print.d.ts +1 -4
  110. package/dist/codegen/print.d.ts.map +1 -1
  111. package/dist/codegen/print.js +1 -4
  112. package/dist/codegen/print.js.map +1 -1
  113. package/dist/codegen/templates/bindings.d.ts +14 -0
  114. package/dist/codegen/templates/bindings.d.ts.map +1 -0
  115. package/dist/codegen/templates/bindings.js +705 -0
  116. package/dist/codegen/templates/bindings.js.map +1 -0
  117. package/dist/codegen/templates/runtime.d.ts +2 -1
  118. package/dist/codegen/templates/runtime.d.ts.map +1 -1
  119. package/dist/codegen/templates/runtime.js +1192 -279
  120. package/dist/codegen/templates/runtime.js.map +1 -1
  121. package/dist/codegen/templates/transports.d.ts +2 -0
  122. package/dist/codegen/templates/transports.d.ts.map +1 -0
  123. package/dist/codegen/templates/transports.js +270 -0
  124. package/dist/codegen/templates/transports.js.map +1 -0
  125. package/dist/collect/collect.d.ts +1 -11
  126. package/dist/collect/collect.d.ts.map +1 -1
  127. package/dist/collect/collect.js +21 -28
  128. package/dist/collect/collect.js.map +1 -1
  129. package/dist/collect/naming.d.ts +1 -4
  130. package/dist/collect/naming.d.ts.map +1 -1
  131. package/dist/collect/naming.js +1 -4
  132. package/dist/collect/naming.js.map +1 -1
  133. package/dist/collect/path.d.ts +2 -9
  134. package/dist/collect/path.d.ts.map +1 -1
  135. package/dist/collect/path.js +2 -9
  136. package/dist/collect/path.js.map +1 -1
  137. package/dist/config/init.d.ts +11 -2
  138. package/dist/config/init.d.ts.map +1 -1
  139. package/dist/config/init.js +55 -7
  140. package/dist/config/init.js.map +1 -1
  141. package/dist/config/load.d.ts.map +1 -1
  142. package/dist/config/load.js +26 -1
  143. package/dist/config/load.js.map +1 -1
  144. package/dist/config/types.d.ts +13 -5
  145. package/dist/config/types.d.ts.map +1 -1
  146. package/dist/config/validate.d.ts +2 -6
  147. package/dist/config/validate.d.ts.map +1 -1
  148. package/dist/config/validate.js +18 -7
  149. package/dist/config/validate.js.map +1 -1
  150. package/dist/generate.d.ts +2 -8
  151. package/dist/generate.d.ts.map +1 -1
  152. package/dist/generate.js +13 -12
  153. package/dist/generate.js.map +1 -1
  154. package/dist/index.d.ts +4 -4
  155. package/dist/index.d.ts.map +1 -1
  156. package/dist/index.js +4 -4
  157. package/dist/index.js.map +1 -1
  158. package/dist/model/infer.d.ts +2 -9
  159. package/dist/model/infer.d.ts.map +1 -1
  160. package/dist/model/infer.js +2 -9
  161. package/dist/model/infer.js.map +1 -1
  162. package/dist/model/merge.d.ts +1 -5
  163. package/dist/model/merge.d.ts.map +1 -1
  164. package/dist/model/merge.js +1 -5
  165. package/dist/model/merge.js.map +1 -1
  166. package/dist/model/reserved.d.ts +1 -4
  167. package/dist/model/reserved.d.ts.map +1 -1
  168. package/dist/model/reserved.js +63 -4
  169. package/dist/model/reserved.js.map +1 -1
  170. package/dist/model/schema.d.ts +1 -4
  171. package/dist/model/schema.d.ts.map +1 -1
  172. package/dist/parsers/openapi-schema.d.ts +1 -5
  173. package/dist/parsers/openapi-schema.d.ts.map +1 -1
  174. package/dist/parsers/openapi-schema.js +2 -5
  175. package/dist/parsers/openapi-schema.js.map +1 -1
  176. package/dist/parsers/postman.d.ts +0 -3
  177. package/dist/parsers/postman.d.ts.map +1 -1
  178. package/dist/parsers/postman.js +2 -5
  179. package/dist/parsers/postman.js.map +1 -1
  180. package/dist/sources/load.d.ts +0 -6
  181. package/dist/sources/load.d.ts.map +1 -1
  182. package/dist/sources/load.js +4 -7
  183. package/dist/sources/load.js.map +1 -1
  184. package/dist/sources/parse.d.ts +0 -2
  185. package/dist/sources/parse.d.ts.map +1 -1
  186. package/dist/sources/parse.js +1 -1
  187. package/dist/sources/parse.js.map +1 -1
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/package.json +40 -12
  191. package/schema/config.schema.json +58 -12
  192. package/dist/codegen/emit-hooks.d.ts +0 -5
  193. package/dist/codegen/emit-hooks.d.ts.map +0 -1
  194. package/dist/codegen/emit-hooks.js +0 -67
  195. package/dist/codegen/emit-hooks.js.map +0 -1
  196. package/dist/codegen/templates/hooks.d.ts +0 -11
  197. package/dist/codegen/templates/hooks.d.ts.map +0 -1
  198. package/dist/codegen/templates/hooks.js +0 -272
  199. package/dist/codegen/templates/hooks.js.map +0 -1
package/README.md CHANGED
@@ -1,7 +1,15 @@
1
1
  # @jutsustack/api-codegen
2
2
 
3
- Generate a typed API layer for **React Native**, **React** and **Next.js** from **Postman
4
- collections**, **Swagger 2.0** and **OpenAPI 3.x** documents.
3
+ Generate a typed API layer from **Postman collections**, **Swagger 2.0** and **OpenAPI 3.x**
4
+ documents, so you never hand-write an API call, its types or its loading state again.
5
+
6
+ New here? Follow the step-by-step guide: **[Using api-codegen in your app](docs/USAGE.md)**.
7
+
8
+ - **Any framework:** React, React Native, Next.js, Vue, Angular, Svelte, SolidJS, or plain
9
+ TypeScript / JavaScript.
10
+ - **Any HTTP client:** `fetch`, `axios`, `@jutsustack/react-native-fetch`, Angular
11
+ `HttpClient`, or your own function. You choose the client; the generated code doesn't depend
12
+ on any of them.
5
13
 
6
14
  ```ts
7
15
  const user = await api.users.getUser({ params: { id: 42 } }); // → User
@@ -10,34 +18,46 @@ try {
10
18
  await api.auth.login({ body: { email, password } });
11
19
  } catch (error) {
12
20
  const failure = api.auth.login.errorOf(error); // { status: 401; data: LoginError } | undefined
21
+ toast(getErrorMessage(error)); // "Wrong email or password." (configurable per API)
13
22
  }
14
23
  ```
15
24
 
16
25
  - **Duplicate requests become one endpoint.** "Login – Success" and "Login – Wrong password"
17
26
  (or `/users/1` and `/users/:id`) merge into one function with typed success and error bodies.
18
- - **Three targets.** On React Native the code runs on
19
- [`@jutsustack/react-native-fetch`](https://github.com/JutsuStack/react-native-fetch), so SSL
20
- pinning, token refresh and retries keep working. React and Next.js get a small generated
21
- `fetch` client.
22
- - **Skips work when nothing changed.** Unchanged sources, config and generator version mean
23
- nothing is parsed or written.
24
- - **Safe to re-run.** Hand-edited generated files are detected, never silently overwritten.
25
- - **Strict-mode clean**, one runtime dependency (`yaml`).
27
+ - **Per-API control:** timeouts, retries with back-off, fallbacks, error messages, logging with
28
+ secrets redacted, performance metrics and loading state, set globally, per endpoint or per call.
29
+ - **Bindings for your framework:** hooks, composables, signals, stores or primitives with
30
+ `status`, `isLoading`, `error`, `refetch`, built on one tested framework-neutral core.
31
+ - **Codegen only.** The package generates code and adds no runtime dependency to your app.
32
+ The generated files import only your framework, and the HTTP library only in `client.ts`.
33
+ - **Skips work when nothing changed**, and **never overwrites hand-edited files**.
34
+ - **Strict-mode clean.** Generated code compiles under `strict`, `exactOptionalPropertyTypes`
35
+ and `noUncheckedIndexedAccess`.
36
+
37
+ ## Install
26
38
 
27
- ## Requirements
39
+ Pick your package manager. The package works the same with all of them, as ESM or CommonJS.
28
40
 
29
- - Node.js 18.18+ for the CLI, TypeScript 5+ in the app
30
- - `react-native` target: `@jutsustack/react-native-fetch` installed in the app
31
- - Hooks: React 18 or 19
41
+ ```bash
42
+ npm i -D @jutsustack/api-codegen
43
+ pnpm add -D @jutsustack/api-codegen
44
+ yarn add -D @jutsustack/api-codegen
45
+ bun add -d @jutsustack/api-codegen
46
+ ```
47
+
48
+ Requirements: Node.js 18.18+ (or Bun) to run the CLI, TypeScript 5+ in the app.
32
49
 
33
50
  ## Quick start
34
51
 
35
52
  ```bash
36
- npm i -D @jutsustack/api-codegen
37
53
  npx jutsu-api init --source ./api/my-app.postman_collection.json # creates my-app-api.config.json
38
54
  npx jutsu-api # generates src/api
39
55
  ```
40
56
 
57
+ Use `pnpm exec jutsu-api`, `yarn jutsu-api` or `bunx jutsu-api` with other package managers.
58
+ `init` reads your `package.json` to choose `framework` and `httpClient` (for example Vue with
59
+ axios); override with `--framework` and `--http-client`.
60
+
41
61
  ```text
42
62
  ✎ src/api/api-collection.json
43
63
  ✎ src/api/runtime.ts
@@ -46,39 +66,91 @@ npx jutsu-api # generates s
46
66
  ✎ src/api/hooks.ts
47
67
  ✎ src/api/index.ts
48
68
  ✎ src/api/client.ts
49
- ✔ Updated 7 file(s) in src/api: 10 endpoints in 4 group(s), 3 merged from duplicate requests [react-native]
69
+ ✔ Updated 7 file(s) in src/api: 10 endpoints in 4 group(s), 3 merged from duplicate requests [react + fetch]
50
70
  ```
51
71
 
52
- Configure the client once in `src/api/client.ts` (base URL, auth, SSL pins), then call
53
- `api.<group>.<endpoint>()`. `init` adds the `.jutsu-api/` cache folder to an existing `.gitignore`. If you
54
- use ESLint, also ignore the output folder: generated files start with `/* eslint-disable */`,
55
- which ESLint 9 reports as unused.
72
+ Configure the client once in `src/api/client.ts` (base URL, auth, retries, logging), then call
73
+ `api.<group>.<endpoint>()`. `init` adds the `.jutsu-api/` cache folder to an existing
74
+ `.gitignore`. If you use ESLint, also ignore the output folder: generated files start with
75
+ `/* eslint-disable */`, which ESLint 9 reports as unused.
56
76
 
57
- ## Examples
77
+ ## How it works
58
78
 
59
- [`examples/demo`](examples/demo) generates one Postman collection for the public
60
- [dummyjson.com](https://dummyjson.com) API into three apps. The collection holds success and
61
- failure examples of the same requests, which merge into one typed endpoint each.
62
-
63
- | App | Shows |
64
- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
65
- | [`rn-app`](examples/demo/rn-app) | React Native 0.86 on `@jutsustack/react-native-fetch`: hooks, typed 400/404, login into the token store, 401 → refresh |
66
- | [`react-app`](examples/demo/react-app) | Vite + React 19: generated hooks, tested with Testing Library against the live API |
67
- | [`next-app`](examples/demo/next-app) | Next.js 16: Server Component with `'use cache'`, typed 404 in `<Suspense>`, Route Handler, client hooks |
68
-
69
- <p>
70
- <img src="examples/demo/screenshots/rn-app-1.png" alt="React Native app: product, typed 404 and product list" width="200">
71
- <img src="examples/demo/screenshots/rn-app-2-login-error.png" alt="React Native app: wrong password shows the typed 400 error" width="200">
72
- <img src="examples/demo/screenshots/rn-app-3-login-ok.png" alt="React Native app: login succeeds and /auth/me returns the user" width="200">
73
- </p>
74
- <p>
75
- <img src="examples/demo/screenshots/react-app.png" alt="React app built with Vite" width="300">
76
- <img src="examples/demo/screenshots/next-app.png" alt="Next.js app: Server Components and client hooks" width="300">
77
- </p>
78
-
79
- Run them with the steps in [`examples/demo/README.md`](examples/demo/README.md).
80
- [`examples/shop-app`](examples/shop-app) is the generated output for a Postman collection plus
81
- an OpenAPI document; CI checks that it is up to date.
79
+ The package is a **build-time tool**. It reads your Postman or Swagger file and writes a typed
80
+ API folder into your app. Your app imports from that folder, not from
81
+ `@jutsustack/api-codegen`, which stays a dev dependency.
82
+
83
+ ```text
84
+ Postman / Swagger file ──► npx jutsu-api ──► src/api/ (written for you)
85
+ (dev dependency) │
86
+ ▼
87
+ your app imports from src/api
88
+ ```
89
+
90
+ **1. Generate.** A Postman request such as `Get user GET {{baseUrl}}/users/:id` becomes:
91
+
92
+ ```ts
93
+ // src/api/types.ts (generated)
94
+ export interface GetUserResponse {
95
+ id: number;
96
+ name: string;
97
+ email: string;
98
+ }
99
+
100
+ // src/api/api.ts (generated)
101
+ getUser: endpoint<GetUserArgs, GetUserResponse, GetUserErrors>(client, {
102
+ id: 'users.getUser',
103
+ method: 'GET',
104
+ path: '/users/:id',
105
+ }),
106
+ ```
107
+
108
+ **2. Connect your HTTP library**, once, in `src/api/client.ts`. This file is yours and is
109
+ never overwritten:
110
+
111
+ ```ts
112
+ // src/api/client.ts
113
+ import axios from 'axios';
114
+ import { createApi, createClient } from './index'; // the generated code
115
+
116
+ const http = axios.create();
117
+ http.interceptors.request.use((config) => {
118
+ config.headers['x-app-version'] = '1.0.0'; // your axios setup keeps working
119
+ return config;
120
+ });
121
+
122
+ export const client = createClient({
123
+ baseURL: 'https://api.example.com',
124
+ http, // leave it out to use fetch
125
+ getToken: () => localStorage.getItem('token'),
126
+ retry: true,
127
+ });
128
+
129
+ export const api = createApi(client);
130
+ ```
131
+
132
+ **3. Call it** anywhere, typed:
133
+
134
+ ```ts
135
+ import { api } from './api/client';
136
+
137
+ const user = await api.users.getUser({ params: { id: 7 } });
138
+ user.name; // string
139
+ ```
140
+
141
+ **What happens on that call:**
142
+
143
+ ```text
144
+ api.users.getUser({ params: { id: 7 } }) your code
145
+ → endpoint users.getUser: GET /users/:id src/api/api.ts
146
+ → client: URL, Bearer token, timeout, retries, middleware src/api/runtime.ts
147
+ → your axios instance (interceptors run) axios
148
+ → server: 200 { id: 7, … } or 404
149
+ → client: data typed as GetUserResponse, or an ApiError with your message
150
+ ```
151
+
152
+ When the API changes, update the collection and run `npx jutsu-api` again. To switch HTTP
153
+ library, change the `http` line in `client.ts`; the rest of your code stays the same.
82
154
 
83
155
  ## Config
84
156
 
@@ -89,7 +161,8 @@ One file per project, **`<project-name>-api.config.json`**, next to `package.jso
89
161
  {
90
162
  "$schema": "./node_modules/@jutsustack/api-codegen/schema/config.schema.json",
91
163
  "project": "shop-app",
92
- "target": "react-native",
164
+ "framework": "vue",
165
+ "httpClient": "axios",
93
166
  "output": "src/api",
94
167
  "sources": [
95
168
  { "id": "shop", "path": "./api/shop.postman_collection.json" },
@@ -98,21 +171,23 @@ One file per project, **`<project-name>-api.config.json`**, next to `package.jso
98
171
  }
99
172
  ```
100
173
 
101
- | Option | Default | Description |
102
- | ----------------- | --------------------------- | ------------------------------------------------------------------- |
103
- | `project` | required | Project name |
104
- | `target` | required | `react-native`, `react` or `next` |
105
- | `output` | required | Output folder, relative to the config; must stay inside the project |
106
- | `sources` | required | See [Sources](#sources) |
107
- | `baseUrl` | first server found | Base URL for the `client.ts` scaffold |
108
- | `methods` | `GET POST PUT PATCH DELETE` | Methods to generate (`HEAD`, `OPTIONS` also allowed) |
109
- | `groupBy` | `folder` | `folder` / `tag`, `path` (first path segment) or `none` |
110
- | `hooks` | `true` | Generate React hooks |
111
- | `include` | all | Globs to keep, e.g. `"/users/**"`, `"GET /orders/*"` |
112
- | `exclude` | none | Globs to skip |
113
- | `format` | `none` | `prettier` formats output with the project's prettier |
114
- | `importExtension` | `""` | `".js"` for apps using `moduleResolution: NodeNext` |
115
- | `cacheDir` | `.jutsu-api` | Cache folder |
174
+ | Option | Default | Description |
175
+ | ----------------- | ------------------------------- | ---------------------------------------------------------------------------------------- |
176
+ | `project` | required | Project name |
177
+ | `framework` | required | `react`, `react-native`, `next`, `vue`, `angular`, `svelte`, `solid` or `none` |
178
+ | `httpClient` | `fetch` (`angular` for Angular) | `fetch`, `axios`, `react-native-fetch`, `angular` or `custom`: what `client.ts` wires up |
179
+ | `output` | required | Output folder, relative to the config; must stay inside the project |
180
+ | `sources` | required | See [Sources](#sources) |
181
+ | `baseUrl` | first server found | Base URL for the `client.ts` scaffold |
182
+ | `methods` | `GET POST PUT PATCH DELETE` | Methods to generate (`HEAD`, `OPTIONS` also allowed) |
183
+ | `groupBy` | `folder` | `folder` / `tag`, `path` (first path segment) or `none` |
184
+ | `hooks` | `true` | Generate the framework bindings |
185
+ | `include` | all | Globs to keep, e.g. `"/users/**"`, `"GET /orders/*"` |
186
+ | `exclude` | none | Globs to skip |
187
+ | `format` | `none` | `prettier` formats output with the project's prettier |
188
+ | `importExtension` | `""` | `".js"` for apps using `moduleResolution: NodeNext` |
189
+ | `cacheDir` | `.jutsu-api` | Cache folder |
190
+ | `target` | deprecated | v0.1 option, still read; see [Migrating](#migrating-from-01) |
116
191
 
117
192
  Unknown options are errors, reported with their path (`sources[1].url: must be an http(s) URL`).
118
193
 
@@ -151,98 +226,322 @@ pull requests.
151
226
 
152
227
  ## What gets generated
153
228
 
154
- | File | Contents |
155
- | --------------------- | --------------------------------------------------------------------- |
156
- | `api-collection.json` | The merged collection |
157
- | `runtime.ts` | Transport types, the `endpoint()` helper; on web, `createFetchClient` |
158
- | `types.ts` | Models and `XArgs` / `XResponse` / `XErrors` types per endpoint |
159
- | `api.ts` | `createApi(client)` → `{ group: { endpoint } }` |
160
- | `hooks.ts` | Query hooks for GET/HEAD, mutation hooks for the rest |
161
- | `index.ts` | Re-exports (on Next.js, import hooks from `./hooks`) |
162
- | `client.ts` | **Yours:** created once, never overwritten |
163
-
164
- Endpoints get defaults from the sources: `skipAuth` for requests that opt out of auth
165
- (Postman `noauth`, OpenAPI `security: []`), and `contentType` / `responseType` for non-JSON
166
- bodies. [`examples/shop-app`](examples/shop-app) shows the full output, and
167
- [Examples](#examples) shows it running.
229
+ | File | Contents |
230
+ | --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
231
+ | `api-collection.json` | The merged collection |
232
+ | `runtime.ts` | `createClient`, `ApiError`, retries, messages, logging, metrics, middleware, request controllers, HTTP library adapters |
233
+ | `types.ts` | Models and `XArgs` / `XResponse` / `XErrors` types per endpoint |
234
+ | `api.ts` | `createApi(client, options)` → `{ group: { endpoint } }`, plus the `Endpoints` map |
235
+ | bindings | `hooks.ts`, `composables.ts`, `angular.ts`, `stores.ts` or `primitives.ts` |
236
+ | `index.ts` | Re-exports (on Next.js, import hooks from `./hooks`) |
237
+ | `client.ts` | **Yours:** created once, never overwritten |
168
238
 
169
- ## Using the generated API
239
+ `runtime.ts` imports nothing: every HTTP library adapter is typed structurally, so it
240
+ compiles whether or not axios, Angular or react-native-fetch is installed. Endpoints get
241
+ defaults from the sources: `skipAuth` for requests that opt out of auth (Postman `noauth`,
242
+ OpenAPI `security: []`), and `contentType` / `responseType` for non-JSON bodies.
243
+
244
+ ## Choosing the HTTP client
245
+
246
+ Pass the library you already use as `http`. Leave it out to use `fetch`. You can switch at any
247
+ time in `client.ts` without regenerating.
170
248
 
171
249
  ```ts
172
- await api.users.getUser({ params: { id: 1 } }); // data
173
- await api.users.getUser.raw({ params: { id: 1 } }); // { data, status, headers, … }
174
- api.users.getUser.errorOf(error); // typed documented error, or undefined
250
+ import axios from 'axios';
251
+ import { createApi, createClient } from './api';
252
+
253
+ createClient({ baseURL }); // fetch: browser, Node, Bun, Deno, edge, React Native
254
+ createClient({ baseURL, http: myFetch }); // any fetch-compatible function
255
+ createClient({ baseURL, http: axios }); // axios itself…
256
+ createClient({ baseURL, http: axios.create({ … }) }); // …or your instance: interceptors keep working
257
+ createClient({ http: createJutsuClient({ baseURL, ssl, auth }) }); // react-native-fetch: SSL pinning, token refresh
258
+ createClient({ baseURL, http: inject(HttpClient) }); // Angular: interceptors, XSRF
175
259
  ```
176
260
 
177
- `params`, `query` and `body` are required exactly when the API needs them; every other
178
- option of the transport can be passed too.
261
+ The library is recognised by its shape: axios by its interceptors, Angular's `HttpClient` by
262
+ `jsonp`, any other object with `request(method, url, options)` as a react-native-fetch
263
+ client, and a plain function as fetch. To name it explicitly, use `fetchTransport({ fetch, init })`,
264
+ `axiosTransport(instance)`, `reactNativeFetchTransport(client)` or
265
+ `angularHttpTransport(http)` as `transport`.
266
+
267
+ For any other library, write a small `transport` function:
268
+
269
+ ```ts
270
+ import { createClient, encodeBody } from './api';
271
+
272
+ createClient({
273
+ baseURL,
274
+ transport: async (request) => {
275
+ const headers = { ...request.headers };
276
+ const body = encodeBody(request.body, request.contentType, headers); // JSON, form, text…
277
+ const res = await myHttp.send(request.method, request.url, {
278
+ headers,
279
+ body,
280
+ signal: request.signal,
281
+ });
282
+ return { status: res.status, headers: res.headers, data: res.body }; // every status, even 4xx/5xx
283
+ },
284
+ });
285
+ ```
179
286
 
180
- `errorOf(error)` returns `{ status, data }` for documented error responses and `undefined`
181
- for anything else. A `4XX` / `5XX` response matches any status of that class, and
182
- `default` any error status.
287
+ Resolve for every HTTP status; throw only when no response arrived (offline, DNS). Return the
288
+ library's fields as they are: headers in any shape (mixed case, arrays, a `Headers` object),
289
+ and `data` as parsed data or JSON text, which the client parses when the response is JSON.
290
+ [docs/USAGE.md](docs/USAGE.md#recipes-for-popular-libraries) has tested recipes for ky, got,
291
+ superagent and ofetch.
183
292
 
184
- ### React Native
293
+ The client (not the HTTP library) owns timeouts, retries, error mapping and messages, so they
294
+ behave the same whatever you pass. Library-specific options go in `adapterOptions` (axios
295
+ config, Angular options, react-native-fetch's `cachePolicy`, …).
296
+
297
+ ## Middleware
298
+
299
+ Middleware wraps every attempt, between the client and the transport, so the same code works
300
+ with fetch, axios, react-native-fetch, Angular `HttpClient` or your own transport. It gets the
301
+ request and `next`, and resolves with the response:
185
302
 
186
303
  ```ts
187
- // src/api/client.ts
188
- export const client = createJutsuClient({
304
+ import type { Middleware } from './api';
305
+
306
+ // change the request
307
+ const trace: Middleware = (request, next) =>
308
+ next({
309
+ ...request,
310
+ headers: { ...request.headers, 'x-trace-id': crypto.randomUUID() },
311
+ });
312
+
313
+ // change the response, e.g. unwrap { data: … }
314
+ const unwrap: Middleware = async (request, next) => {
315
+ const response = await next(request);
316
+ const body = response.data as { data?: unknown } | null;
317
+ return { ...response, data: body?.data ?? response.data };
318
+ };
319
+
320
+ // repeat the request: refresh the token once on 401
321
+ const refreshOn401: Middleware = async (request, next) => {
322
+ const response = await next(request);
323
+ if (response.status !== 401 || request.skipAuth) return response;
324
+ const token = await session.refresh();
325
+ return next({
326
+ ...request,
327
+ headers: { ...request.headers, authorization: 'Bearer ' + token },
328
+ });
329
+ };
330
+
331
+ // answer without the network (mocks, offline cache)
332
+ const mock: Middleware = async (request, next) =>
333
+ request.endpoint === 'products.list'
334
+ ? { status: 200, headers: {}, data: fixtures.products }
335
+ : next(request);
336
+ ```
337
+
338
+ Add it at any level. Levels add up (they don't replace each other) and run outermost first:
339
+ client, then endpoint, then call, then the transport.
340
+
341
+ ```ts
342
+ const client = createClient({
343
+ http: axios,
344
+ middleware: [trace, refreshOn401, unwrap],
345
+ });
346
+ const api = createApi(client, {
347
+ endpoints: { 'products.list': { middleware: [mock] } },
348
+ });
349
+ await api.orders.list({ middleware: [timing] });
350
+
351
+ // or build a transport once and use it anywhere
352
+ const transport = applyMiddleware(fetchTransport(), [trace, unwrap]);
353
+ ```
354
+
355
+ The contract is the transport's: resolve for every HTTP status, and throw only when there is no
356
+ response. The client then applies timeouts, retries (middleware runs on each attempt and sees
357
+ `request.attempt`), error mapping, messages, logging and metrics as usual. A middleware that
358
+ throws gives a `NETWORK` error with the cause in `originalError`. A middleware that hangs still
359
+ times out. If a middleware sends a request to an origin that isn't trusted (see
360
+ [Credentials](#credentials-and-other-origins)), the client's token and headers are removed
361
+ before it goes out.
362
+
363
+ Middleware or `onRequest`? `onRequest` can only change headers, while middleware can also
364
+ change the response, repeat or short-circuit a call. Your HTTP library's own interceptors
365
+ (axios, Angular) keep working too, inside the transport.
366
+
367
+ ## Per-API control
368
+
369
+ Every option works at three levels: **client** (`createClient`), **endpoint**
370
+ (`createApi(client, { endpoints })`, type-checked against your API) and **call** (the args of
371
+ one call). The more specific level wins.
372
+
373
+ ```ts
374
+ export const client = createClient({
189
375
  baseURL: 'https://api.example.com',
190
- auth: {
191
- tokenStore: createMemoryTokenStore(),
192
- // the refresh handler's `http` bypasses auth, so it can call a generated endpoint
193
- refresh: {
194
- handler: async ({ refreshToken, http }) => {
195
- const t = await createApi(http).auth.refreshSession({
196
- body: { refreshToken: refreshToken ?? '' },
197
- });
198
- return { accessToken: t.accessToken, refreshToken: t.refreshToken };
199
- },
200
- },
376
+ getToken: () => session.token, // Bearer header unless the endpoint skips auth
377
+ timeoutMs: 15_000, // per attempt (default 30 s)
378
+ retry: true, // see Retries
379
+ logger: import.meta.env.DEV, // see Logging
380
+ slowRequestMs: 2_000,
381
+ onMetrics: (m) => analytics.track('api_call', m),
382
+ onLoadingChange: (pending) => progressBar.toggle(pending > 0),
383
+ messages: { 401: 'Your session expired. Please sign in again.' },
384
+ });
385
+
386
+ export const api = createApi(client, {
387
+ endpoints: {
388
+ 'auth.login': { messages: { 401: 'Wrong email or password.' }, log: false },
389
+ 'products.list': { retry: 3, fallback: () => cachedProducts() },
390
+ 'payments.charge': { timeoutMs: 60_000 },
201
391
  },
202
392
  });
203
- export const api = createApi(client);
393
+
394
+ await api.products.get({
395
+ params: { id },
396
+ timeoutMs: 5_000,
397
+ messages: { 404: 'This product is gone.' },
398
+ });
204
399
  ```
205
400
 
401
+ ### Error handling and messages
402
+
403
+ Every failure is an `ApiError` with `kind` (`HTTP`, `NETWORK`, `TIMEOUT`, `ABORTED`, `PARSE`),
404
+ `status`, `data`, `headers`, `endpoint` and `userMessage`, a text safe to show people.
405
+
406
+ - `messages` maps an exact status (`404`), a class (`'4XX'`, `'5XX'`), a kind (`'NETWORK'`,
407
+ `'TIMEOUT'`) or `'default'` to a string or a function. Built-in English defaults cover the
408
+ rest (`defaultErrorMessages`).
409
+ - Server error text is **not** shown by default. Opt in with
410
+ `messageFromResponse: (e) => e.data?.message`.
411
+ - `getErrorMessage(error)` returns a message for anything thrown; `errorOf(error)` returns the
412
+ typed body of a documented error response.
413
+ - `ApiError.message` and `JSON.stringify(error)` leave out the query string, the response body
414
+ and response headers (`Set-Cookie`), so they stay out of logs and error trackers. The fields
415
+ themselves (`error.data`, `error.headers`) are still there in code.
416
+
417
+ ### Retries
418
+
419
+ `retry: true` retries network errors, timeouts and 408 / 429 / 500 / 502 / 503 / 504 up to 2
420
+ times, with exponential back-off and jitter, honouring `Retry-After`.
421
+
422
+ - Only idempotent methods (GET, HEAD, OPTIONS, PUT, DELETE) are retried, plus calls with an
423
+ `idempotencyKey` (sent as `Idempotency-Key`). A payment is never sent twice by accident.
424
+ - `retry: 3` sets the attempts; `{ attempts, delayMs, maxDelayMs, retryOn }` gives full
425
+ control. Even a custom `retryOn` cannot retry a POST or PATCH that has no `idempotencyKey`.
426
+ - Cancelled calls are never retried; a cancel during back-off stops at once.
427
+
428
+ ### Fallbacks
429
+
430
+ `fallback: (error) => value` resolves with a value instead of throwing, for example a cached
431
+ list when the server is down. It is typed against the endpoint's response.
432
+
433
+ - `.raw()` returns `fromFallback: true` and every binding's state has `fromFallback`, so the UI
434
+ can mark the data as stale or offline. Metrics count it too.
435
+ - A fallback never runs for cancelled calls. A fallback that throws replaces the error.
436
+
437
+ ### Logging
438
+
439
+ `logger: true` logs to the console; any object with `debug` / `info` / `warn` / `error` works
440
+ (pino, Sentry breadcrumbs, …).
441
+
442
+ - `logLevel` defaults to `'info'`.
443
+ - Logs show the method, path template, status and duration. Headers such as `Authorization`,
444
+ `Cookie` and `X-Api-Key` are `[redacted]` (`redactHeaders` sets the list). Query strings
445
+ and bodies are left out unless `logBodies: true`.
446
+ - `logBodies` is for development only: bodies can hold passwords and tokens. Keep `log: false`
447
+ on auth endpoints if you turn it on.
448
+ - `log: false` silences one endpoint or call.
449
+ - A logger that throws never breaks a request.
450
+
451
+ ### Performance
452
+
453
+ `onMetrics` receives every call: `endpoint`, `method`, `path` (template, no ids), `status`,
454
+ `ok`, `errorKind`, `durationMs`, `attempts`, `fromFallback` and `slow`. Calls slower than
455
+ `slowRequestMs` are also logged as warnings. `.raw()` exposes `durationMs` and `attempts`.
456
+
457
+ ### Loading state
458
+
459
+ - **Global:** `onLoadingChange(pending)`, `client.pending` and `client.subscribe(listener)`;
460
+ each binding has a `usePendingRequests` / `injectPendingRequests` / `pendingRequests`
461
+ helper.
462
+ - **Per call:** `onLoading: (loading) => …` runs with `true` when the call starts and `false`
463
+ when it settles, failures included.
464
+ - **Per component:** the bindings below return `status`, `isLoading`, `isError`, `isSuccess`,
465
+ `data`, `error`, `fromFallback` and `refetch`.
466
+
467
+ ### Credentials and other origins
468
+
469
+ `getToken` and the client `headers` go only to relative URLs and to `baseURL`'s origin. Any
470
+ other absolute URL, such as a presigned upload or a third-party API, gets only the headers of
471
+ that call. List extra origins that should receive them in `trustedOrigins`:
472
+
206
473
  ```ts
207
- await api.users.listUsers({
208
- query: { page: 1 },
209
- cachePolicy: 'stale-while-revalidate',
474
+ createClient({
475
+ baseURL,
476
+ transport,
477
+ getToken,
478
+ trustedOrigins: ['https://files.example.com'],
210
479
  });
211
- const { data, status, refetch } = useGetUser({ params: { id: 1 } }); // inside <JutsuProvider>
212
480
  ```
213
481
 
214
- Jest needs react-native-fetch's ES modules transformed and its test setup:
482
+ `timeoutMs` and retry delays are validated: a negative or non-numeric value uses the default
483
+ instead of turning the timeout off (`0` turns it off), and very large values are capped.
215
484
 
216
- ```js
217
- module.exports = {
218
- preset: '@react-native/jest-preset',
219
- transformIgnorePatterns: [
220
- 'node_modules/(?!((jest-)?react-native|@react-native(-community)?|@jutsustack)/)',
221
- ],
222
- setupFiles: ['@jutsustack/react-native-fetch/testing/jestSetup'],
223
- };
485
+ ### Hooks and callbacks
486
+
487
+ `onRequest(request)` runs before each attempt and may add headers (trace ids). `onResponse` and
488
+ `onError` observe results. Observers that throw are ignored, so they can't break a call.
489
+
490
+ ## Framework bindings
491
+
492
+ All bindings wrap the same `createQueryController` / `createMutationController`.
493
+
494
+ - **Queries** (GET / HEAD / OPTIONS) refetch when their args change by value, abort the
495
+ previous call, ignore stale responses and keep the last data while reloading.
496
+ - **Mutations** expose `run` (never rejects), `runAsync` and `reset`. The `dedupe` option
497
+ blocks double submits; it is off by default because concurrent writes (toggles) are
498
+ sometimes intended.
499
+ - **Query options:** `enabled`, `keepPreviousData`, `onSuccess`, `onError`, `onSettled`.
500
+ Mutations take the same callbacks plus `dedupe`.
501
+ - Every binding also accepts `configureApi(client)` for apps with one client.
502
+
503
+ ### React and React Native
504
+
505
+ ```tsx
506
+ <ApiProvider client={client}>
507
+ <App />
508
+ </ApiProvider>;
509
+
510
+ const user = useGetUser({ params: { id } }, { enabled: !!id });
511
+ const login = useLogin({ onSuccess: () => navigate('/home') });
512
+ const busy = usePendingRequests();
513
+ if (user.isLoading) return <Spinner />;
224
514
  ```
225
515
 
226
- ### React
516
+ On React Native, `httpClient: "react-native-fetch"` keeps SSL pinning and token refresh:
227
517
 
228
518
  ```ts
229
- export const client = createFetchClient({
519
+ const jutsu = createJutsuClient({
230
520
  baseURL: 'https://api.example.com',
231
- getToken: () => sessionToken, // sent as Bearer unless the endpoint skips auth
232
- timeoutMs: 15_000,
521
+ auth: {
522
+ tokenStore: createMemoryTokenStore(),
523
+ refresh: {
524
+ handler: async ({ refreshToken, http }) => {
525
+ // the refresh handler's `http` bypasses auth, so it can call a generated endpoint
526
+ const refreshApi = createApi(createClient({ http }));
527
+ const t = await refreshApi.auth.refreshSession({
528
+ body: { refreshToken: refreshToken ?? '' },
529
+ });
530
+ return { accessToken: t.accessToken, refreshToken: t.refreshToken };
531
+ },
532
+ },
533
+ },
233
534
  });
234
- export const api = createApi(client);
535
+ export const client = createClient({ http: jutsu });
235
536
  ```
236
537
 
237
- Wrap the tree in `<ApiProvider client={client}>` to use the hooks. Other options: `headers`,
238
- `fetch`, `init`, `arrayFormat`, `onError`. Errors are `ApiError` (`kind`, `status`, `data`,
239
- `url`); `isApiError()` checks for one.
538
+ `fetch` and `axios` work on React Native too. Multipart file parts are `{ uri, name, type }`.
240
539
 
241
540
  ### Next.js
242
541
 
243
542
  Endpoints are plain async functions, usable in Server Components, Route Handlers and Server
244
543
  Actions. With Cache Components (the Next.js 16 default), cache a call in a `'use cache'`
245
- function and wrap uncached ones in `<Suspense>`:
544
+ function:
246
545
 
247
546
  ```ts
248
547
  export async function getPets() {
@@ -255,7 +554,89 @@ export async function getPets() {
255
554
 
256
555
  Without Cache Components, pass `init: { next: { revalidate: 60, tags: ['pets'] } }`.
257
556
  `hooks.ts` starts with `'use client'`; import it from `@/lib/api/hooks`. The scaffolded
258
- `client.ts` reads `NEXT_PUBLIC_API_BASE_URL`.
557
+ `client.ts` reads `NEXT_PUBLIC_API_BASE_URL`. On the server, pass per-request tokens with
558
+ `headers` rather than module state.
559
+
560
+ ### Vue 3.3+ (and Nuxt)
561
+
562
+ ```ts
563
+ app.use(createApiPlugin(client)); // or provideApi(client) in a parent's setup()
564
+
565
+ const id = ref(1);
566
+ const user = useGetUser(() => ({ params: { id: id.value } })); // refs, getters or values
567
+ user.data.value;
568
+ user.isLoading.value;
569
+ user.refetch();
570
+ ```
571
+
572
+ Composables are disposed with their effect scope, which aborts calls in flight.
573
+
574
+ ### Angular 17+
575
+
576
+ ```ts
577
+ // app.config.ts
578
+ providers: [provideHttpClient(withInterceptors([authInterceptor])), provideApi(createAppClient)];
579
+
580
+ // a component or service (injection context)
581
+ readonly id = signal(1);
582
+ readonly user = injectGetUser(() => ({ params: { id: this.id() } })); // signals in, signals out
583
+ readonly save = injectUpdateUser({ onSuccess: () => this.user.refetch() });
584
+ // template: @if (user.isLoading()) { … } {{ user.data()?.name }}
585
+ ```
586
+
587
+ With `httpClient: "angular"`, calls go through `HttpClient`, so interceptors and XSRF
588
+ protection apply. `injectApi()` returns the api object; `from(api.users.getUser(…))` turns a
589
+ call into an Observable.
590
+
591
+ ### Svelte 4 / 5 (and SvelteKit)
592
+
593
+ ```svelte
594
+ <script>
595
+ import { derived, writable } from 'svelte/store';
596
+ import { createGetUser, setApiContext } from '$lib/api';
597
+ const id = writable(1);
598
+ const user = createGetUser(derived(id, (id) => ({ params: { id } })));
599
+ </script>
600
+
601
+ {#if $user.isLoading}…{:else}{$user.data?.name}{/if}
602
+ ```
603
+
604
+ Call `setApiContext(client)` in a root component, or `configureApi(client)` once. Stores run
605
+ while subscribed and abort when the last subscriber leaves. In SvelteKit `load` functions,
606
+ call `api` directly.
607
+
608
+ ### SolidJS 1.8+ and 2.x
609
+
610
+ ```tsx
611
+ const value = apiContextValue(client);
612
+ <ApiContext.Provider value={value}>
613
+ <App />
614
+ </ApiContext.Provider>; // Solid 2: <ApiContext value={value}>
615
+
616
+ const [id, setId] = createSignal(1);
617
+ const user = createGetUser(() => ({ params: { id: id() } }));
618
+ user.data();
619
+ user.isLoading();
620
+ ```
621
+
622
+ ### Plain TypeScript / JavaScript (`framework: "none"`)
623
+
624
+ Use `api` directly. For another UI library (Lit, Qwik, Preact signals, …), bind
625
+ `createQueryController` / `createMutationController` from `runtime.ts`. Each has
626
+ `getState()` and `subscribe()`.
627
+
628
+ ## Using the generated API
629
+
630
+ ```ts
631
+ await api.users.getUser({ params: { id: 1 } }); // data
632
+ await api.users.getUser.raw({ params: { id: 1 } }); // { data, status, headers, durationMs, attempts, fromFallback }
633
+ api.users.getUser.errorOf(error); // typed documented error, or undefined
634
+ api.users.getUser.id; // 'users.getUser', the key in createApi(client, { endpoints })
635
+ ```
636
+
637
+ `params`, `query` and `body` are required exactly when the API needs them. `errorOf(error)`
638
+ returns `{ status, data }` for documented error responses and `undefined` for anything else.
639
+ A `4XX` / `5XX` response matches any status of that class, and `default` matches any error status.
259
640
 
260
641
  ## Caching
261
642
 
@@ -278,12 +659,12 @@ the change to `client.ts`, or use `--force`.
278
659
  jutsu-api [generate|check|collect|init] [options]
279
660
  ```
280
661
 
281
- | Command | Description |
282
- | ---------- | ---------------------------------------------------------------- |
283
- | `generate` | Build the collection and the client (default) |
284
- | `check` | Exit 1 when generated files are out of date (CI) |
285
- | `collect` | Only build `api-collection.json` |
286
- | `init` | Create the config (`--name`, `--target`, `--source`, `--output`) |
662
+ | Command | Description |
663
+ | ---------- | ------------------------------------------------------------------------------------ |
664
+ | `generate` | Build the collection and the client (default) |
665
+ | `check` | Exit 1 when generated files are out of date (CI) |
666
+ | `collect` | Only build `api-collection.json` |
667
+ | `init` | Create the config (`--name`, `--framework`, `--http-client`, `--source`, `--output`) |
287
668
 
288
669
  Options: `-c, --config <file>`, `--cwd <dir>`, `-f, --force`, `--offline`, `--dry-run`,
289
670
  `-q, --quiet`, `-v, --verbose`. Exit codes: `0` ok, `1` failure or stale, `2` usage / config
@@ -292,8 +673,33 @@ error.
292
673
  In CI, commit the generated files and run `npx jutsu-api check`. It regenerates in memory
293
674
  and ignores the cache. Remote sources need network access and their secrets in CI.
294
675
 
295
- The same functions are exported for scripts: `generate`, `check`, `collect`, `init`, plus
296
- `parsePostman`, `parseOpenApi`, `buildCollection` and `emitFiles`.
676
+ The same functions are exported for scripts, from `import` and `require` alike: `generate`,
677
+ `check`, `collect`, `init`, `detectFramework`, `detectHttpClient`, plus `parsePostman`,
678
+ `parseOpenApi`, `buildCollection` and `emitFiles`.
679
+
680
+ ## Migrating from 0.1
681
+
682
+ 0.2 makes the HTTP client your choice, so the generated code no longer depends on any library.
683
+
684
+ 1. **Config:** replace `"target"` with `"framework"` and add `"httpClient"`.
685
+ - `react-native` becomes `"framework": "react-native"` + `"httpClient": "react-native-fetch"`.
686
+ - `react` / `next` become `"framework": "react"` / `"next"` + `"httpClient": "fetch"`.
687
+
688
+ Old configs still load, with a warning, and map exactly this way.
689
+
690
+ 2. **`client.ts`** is yours, so it isn't regenerated. Wrap your client in `createClient`.
691
+ - Web: `createFetchClient({ … })` becomes `createClient({ … })`. A custom `fetch` becomes
692
+ `http: myFetch`; `init` moves to `transport: fetchTransport({ fetch, init })`.
693
+ - React Native: `createApi(createJutsuClient(…))` becomes
694
+ `createApi(createClient({ http: createJutsuClient(…) }))`.
695
+
696
+ Delete `client.ts` and regenerate to get the new scaffold.
697
+
698
+ 3. **React Native hooks** now come from the generated `ApiProvider` (no `<JutsuProvider>`
699
+ needed for them). The `optimistic` mutation option is gone; use `onSuccess` / `onError`.
700
+ 4. React Native call options that belong to the library (`cachePolicy`, `tag`, `dedupe`) move
701
+ into `adapterOptions`. `idempotencyKey`, `skipAuth`, `timeoutMs` and `signal` stay where
702
+ they are.
297
703
 
298
704
  ## Security
299
705
 
@@ -303,29 +709,56 @@ The same functions are exported for scripts: `generate`, `check`, `collect`, `in
303
709
  redirects to another origin. URLs with embedded credentials are rejected.
304
710
  - Output and cache folders must be inside the project.
305
711
  - Downloads are capped at 50 MB and 30 s; YAML aliases and schema depth are limited.
712
+ - Generated runtime:
713
+ - Logs redact credentials and leave out bodies and query strings by default.
714
+ - Header values with line breaks are rejected (header injection).
715
+ - `.` / `..` path params are rejected (path traversal).
716
+ - Server error text is not shown to people unless you opt in.
717
+ - Non-idempotent requests are not retried without an idempotency key.
718
+ - The token and client headers never reach origins you did not trust.
719
+ - Serialised errors carry no response bodies, `Set-Cookie` or query strings.
720
+
721
+ Report vulnerabilities privately; see [SECURITY.md](SECURITY.md). The latest quality and
722
+ security audit is in [testcase.md](testcase.md).
306
723
 
307
724
  ## Troubleshooting
308
725
 
309
- | Message / symptom | Fix |
310
- | --------------------------------------- | -------------------------------------------------------------------- |
311
- | `No <project>-api.config.json` | Run `npx jutsu-api init` or pass `--config` |
312
- | `generated file(s) were edited by hand` | Move the change to `client.ts`, then `--force` |
313
- | `Source "x" … answered 401` | Check `headers` / `POSTMAN_API_KEY`; `--offline` uses the saved copy |
314
- | `segment "{name}.{ext}" mixes text …` | Pass the whole segment as one param, e.g. `nameAndExt: 'a.pdf'` |
315
- | A Postman field is `unknown` | Its example was `{{variable}}` or `null`; save a real example |
316
- | Imports fail with `NodeNext` | Set `"importExtension": ".js"` |
726
+ | Message / symptom | Fix |
727
+ | --------------------------------------- | ----------------------------------------------------------------------------------- |
728
+ | `No <project>-api.config.json` | Run `npx jutsu-api init` or pass `--config` |
729
+ | `generated file(s) were edited by hand` | Move the change to `client.ts`, then `--force` |
730
+ | `Source "x" … answered 401` | Check `headers` / `POSTMAN_API_KEY`; `--offline` uses the saved copy |
731
+ | `segment "{name}.{ext}" mixes text …` | Pass the whole segment as one param, e.g. `nameAndExt: 'a.pdf'` |
732
+ | A Postman field is `unknown` | Its example was `{{variable}}` or `null`; save a real example |
733
+ | Imports fail with `NodeNext` | Set `"importExtension": ".js"` |
734
+ | `No API client: …` | Add the provider / plugin the message names, or call `configureApi` |
735
+ | `"target" is deprecated` | Replace it with `framework` (and `httpClient`), see [Migrating](#migrating-from-01) |
736
+
737
+ ## Examples
738
+
739
+ [`examples/shop-app`](examples/shop-app) is the generated output for a Postman collection
740
+ plus an OpenAPI document; CI checks that it is up to date.
741
+
742
+ [`examples/demo`](examples/demo) generates one Postman collection for the public
743
+ [dummyjson.com](https://dummyjson.com) API into React Native, React and Next.js apps, with
744
+ live tests against the real API. Run them with `examples/demo/verify.sh` (Node 22).
317
745
 
318
746
  ## Development
319
747
 
320
748
  ```bash
321
749
  yarn install
322
- yarn verify # lint, typecheck, tests, build, CLI smoke test
750
+ yarn verify # lint, typecheck, tests, ESM + CJS build, CLI smoke test, tarball check
751
+ yarn smoke:pm # pack, install and run with npm, pnpm, yarn and bun
323
752
  ```
324
753
 
325
754
  `src/parsers` reads sources, `src/collect` merges them into the collection, `src/codegen`
326
- writes the files, and `src/generate.ts` handles caching and writes. `test/typecheck.test.ts`
327
- compiles generated code for every target under strict settings. `test/stubs/` mirrors the
328
- react-native-fetch types that generated code uses; update it when those types change.
755
+ writes the files, and `src/generate.ts` handles caching and writes.
756
+
757
+ - `test/typecheck.test.ts` compiles the generated code for every framework and HTTP client
758
+ under strict settings, against the real axios, Angular, Vue, Svelte, Solid 1 and 2 and
759
+ React types.
760
+ - `test/runtime.test.ts` and `test/bindings*.test.ts` run the generated code in Node, React 19
761
+ (StrictMode), Vue and Svelte.
329
762
 
330
763
  ## License
331
764