@7nohe/openapi-react-query-codegen 3.1.0 → 4.0.0-beta.2
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.
- package/AGENTS.md +207 -0
- package/README.md +7 -3
- package/dist/check.d.mts +59 -0
- package/dist/check.mjs +162 -0
- package/dist/cli.d.mts +6 -1
- package/dist/cli.mjs +4 -31
- package/dist/client/emitSchemas.d.mts +9 -0
- package/dist/client/emitSchemas.mjs +130 -0
- package/dist/client/emitSdk.d.mts +18 -0
- package/dist/client/emitSdk.mjs +253 -0
- package/dist/client/emitTransformers.d.mts +19 -0
- package/dist/client/emitTransformers.mjs +556 -0
- package/dist/client/emitTypes.d.mts +16 -0
- package/dist/client/emitTypes.mjs +204 -0
- package/dist/client/index.d.mts +44 -0
- package/dist/client/index.mjs +126 -0
- package/dist/client/naming.d.mts +41 -0
- package/dist/client/naming.mjs +175 -0
- package/dist/client/operations.d.mts +103 -0
- package/dist/client/operations.mjs +352 -0
- package/dist/client/runtime/axios.runtime.ts +706 -0
- package/dist/client/runtime/fetch.runtime.ts +795 -0
- package/dist/client/schema.d.mts +50 -0
- package/dist/client/schema.mjs +648 -0
- package/dist/client/spec.d.mts +40 -0
- package/dist/client/spec.mjs +387 -0
- package/dist/client/tsconfig.d.mts +13 -0
- package/dist/client/tsconfig.mjs +56 -0
- package/dist/common.d.mts +0 -38
- package/dist/common.mjs +0 -87
- package/dist/constants.d.mts +0 -2
- package/dist/constants.mjs +0 -2
- package/dist/createSource.d.mts +8 -7
- package/dist/createSource.mjs +14 -17
- package/dist/errors.d.mts +43 -0
- package/dist/errors.mjs +61 -0
- package/dist/format.mjs +0 -1
- package/dist/generate.d.mts +25 -3
- package/dist/generate.mjs +83 -83
- package/dist/runCli.d.mts +20 -0
- package/dist/runCli.mjs +105 -0
- package/dist/tsmorph/buildQueryHooks.mjs +19 -11
- package/dist/tsmorph/generateFiles.mjs +105 -161
- package/dist/tsmorph/operationNames.d.mts +2 -13
- package/dist/tsmorph/operationNames.mjs +4 -24
- package/dist/tsmorph/projectFactory.d.mts +7 -2
- package/dist/tsmorph/projectFactory.mjs +16 -9
- package/dist/types.d.mts +14 -26
- package/package.json +8 -8
- package/dist/parseOperations.d.mts +0 -10
- package/dist/parseOperations.mjs +0 -164
- package/dist/service.d.mts +0 -8
- package/dist/service.mjs +0 -98
- package/dist/util.d.mts +0 -2
- package/dist/util.mjs +0 -16
package/AGENTS.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# AGENTS.md
|
|
2
|
+
|
|
3
|
+
This file has two parts:
|
|
4
|
+
|
|
5
|
+
- **[Using this package](#using-this-package)**: for coding agents working in a project that depends on `@7nohe/openapi-react-query-codegen`. This file ships in the npm package, at `node_modules/@7nohe/openapi-react-query-codegen/AGENTS.md`.
|
|
6
|
+
- **[Working on this repository](#working-on-this-repository)**: for agents changing the generator itself.
|
|
7
|
+
|
|
8
|
+
## Using this package
|
|
9
|
+
|
|
10
|
+
`@7nohe/openapi-react-query-codegen` is a CLI (`openapi-rq`) that reads an OpenAPI spec and generates:
|
|
11
|
+
|
|
12
|
+
1. a TypeScript HTTP client (types, one function per operation and a small fetch or axios runtime) in `<output>/requests/`
|
|
13
|
+
2. TanStack Query v5 hooks and helpers on top of that client in `<output>/queries/`
|
|
14
|
+
|
|
15
|
+
Docs: https://openapi-react-query-codegen.vercel.app (summary for LLMs: https://openapi-react-query-codegen.vercel.app/llms.txt)
|
|
16
|
+
|
|
17
|
+
### Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install -D @7nohe/openapi-react-query-codegen
|
|
21
|
+
npm install @tanstack/react-query
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`commander`, `ts-morph` and `typescript` are peer dependencies. If your package manager does not install peers automatically, add them as devDependencies. For `--client axios`, also add `axios`. Nothing else is needed at runtime; the client code is generated into `requests/`.
|
|
25
|
+
|
|
26
|
+
Only the scoped `@7nohe/openapi-react-query-codegen` package belongs to this project. The unscoped `openapi-react-query-codegen` on npm is someone else's.
|
|
27
|
+
|
|
28
|
+
### Run
|
|
29
|
+
|
|
30
|
+
Add a script and run it whenever the spec changes:
|
|
31
|
+
|
|
32
|
+
```json
|
|
33
|
+
{ "scripts": { "codegen": "openapi-rq -i ./openapi.yaml -o ./src/openapi" } }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
| Flag | Default | Notes |
|
|
37
|
+
| --- | --- | --- |
|
|
38
|
+
| `-i, --input <path\|url\|content>` | (required) | OpenAPI 3.0/3.1 spec |
|
|
39
|
+
| `-o, --output <dir>` | `openapi` | `requests/` and `queries/` are created inside |
|
|
40
|
+
| `-c, --client <name>` | `fetch` | or `axios` |
|
|
41
|
+
| `--format <biome\|prettier>` | none | formats `queries/` only |
|
|
42
|
+
| `--lint <biome\|eslint>` | none | lints/fixes `queries/` only |
|
|
43
|
+
| `--enums <javascript\|typescript>` | none | emit enum objects |
|
|
44
|
+
| `--useDateType` | off | `Date` for `date`/`date-time`, converted in successful responses |
|
|
45
|
+
| `--noOperationId` | off | derive names from paths instead of `operationId` |
|
|
46
|
+
| `--noSchemas` / `--schemaType <json\|form>` | schemas on, `json` | JSON schema export (`requests/schemas.gen.ts`) |
|
|
47
|
+
| `--pageParam <name>` | `page` | query param that turns a GET into an infinite query |
|
|
48
|
+
| `--nextPageParam <path>` | `nextPage` | response field holding the next page (dot path allowed, e.g. `meta.next`) |
|
|
49
|
+
| `--initialPageParam <value>` / `--omitInitialPageParam` | `1` | first page value, or send none |
|
|
50
|
+
| `--check` | off | do not update the output; exit 1 if it is out of date (see below) |
|
|
51
|
+
| `--json` | off | errors as one JSON line on stderr (see below) |
|
|
52
|
+
|
|
53
|
+
Pass the **same flags** every time (keep them in the package.json script). Different flags produce different output, so `--check` with other flags reports drift.
|
|
54
|
+
|
|
55
|
+
### Generated layout
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
<output>/
|
|
59
|
+
├── queries/ # TanStack Query layer (this package)
|
|
60
|
+
│ ├── index.ts # re-exports common, queries, queryOptions
|
|
61
|
+
│ ├── common.ts # query keys, key functions, result types
|
|
62
|
+
│ ├── queries.ts # useQuery and useMutation hooks
|
|
63
|
+
│ ├── queryOptions.ts # queryOptions()/infiniteQueryOptions() factories
|
|
64
|
+
│ ├── suspense.ts # useSuspenseQuery hooks
|
|
65
|
+
│ ├── infiniteQueries.ts# useInfiniteQuery hooks
|
|
66
|
+
│ ├── prefetch.ts # prefetchQuery helpers
|
|
67
|
+
│ └── ensureQueryData.ts# ensureQueryData helpers
|
|
68
|
+
└── requests/ # HTTP client (generated by this package too)
|
|
69
|
+
├── client.gen.ts # `client` instance (setConfig, interceptors)
|
|
70
|
+
├── runtime.gen.ts # the fetch or axios runtime the client runs on
|
|
71
|
+
├── sdk.gen.ts # one function per operation
|
|
72
|
+
├── services.gen.ts # compatibility shim: re-exports client.gen + sdk.gen
|
|
73
|
+
├── types.gen.ts # request/response types
|
|
74
|
+
├── schemas.gen.ts # component schemas as constants (unless --noSchemas)
|
|
75
|
+
└── transformers.gen.ts # date conversion (only with --useDateType)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Never edit generated files; change the spec or the flags and regenerate. Whether to commit the output is the project's choice. If it is committed, add the `--check` step below to CI.
|
|
79
|
+
|
|
80
|
+
### Using the generated code
|
|
81
|
+
|
|
82
|
+
Names come from the operation ID (or from the path with `--noOperationId`). For a GET operation `findPets` and a POST `addPet`:
|
|
83
|
+
|
|
84
|
+
| Export | File | Use |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `useFindPets(clientOptions?, queryKey?, options?)` | `queries.ts` | `useQuery` |
|
|
87
|
+
| `useFindPetsSuspense(...)` | `suspense.ts` | `useSuspenseQuery` |
|
|
88
|
+
| `useFindPetsInfinite(...)` | `infiniteQueries.ts` | only when the GET has the `--pageParam` query param |
|
|
89
|
+
| `useFindPetsSuspenseInfinite(...)`, `prefetchUseFindPetsInfinite(...)` | `suspense.ts`, `prefetch.ts` | same condition as above |
|
|
90
|
+
| `findPetsOptions(clientOptions?, queryKey?)` | `queryOptions.ts` | pass to `useQuery`, `useQueries`, loaders |
|
|
91
|
+
| `prefetchUseFindPets(queryClient, clientOptions?, options?)` | `prefetch.ts` | SSR / route loaders |
|
|
92
|
+
| `ensureUseFindPetsData(queryClient, clientOptions?, options?)` | `ensureQueryData.ts` | route loaders |
|
|
93
|
+
| `useFindPetsKey`, `UseFindPetsKeyFn(clientOptions?)` | `common.ts` | `invalidateQueries` with the same key the hook uses |
|
|
94
|
+
| `useAddPet(mutationKey?, options?)` | `queries.ts` | `useMutation`; `mutate({ body, path, query })` |
|
|
95
|
+
|
|
96
|
+
`clientOptions` is the SDK options object: `{ path, query, body, headers }`, typed from `requests/types.gen.ts`. Mutation results are the full SDK response (`data`, plus `response` for fetch or `headers` for axios).
|
|
97
|
+
|
|
98
|
+
```tsx
|
|
99
|
+
// once, at app start: configure the generated client
|
|
100
|
+
import { client } from "./openapi/requests/services.gen";
|
|
101
|
+
client.setConfig({ baseUrl: "https://api.example.com" }); // axios client: baseURL
|
|
102
|
+
|
|
103
|
+
// in components
|
|
104
|
+
import { useQueryClient } from "@tanstack/react-query";
|
|
105
|
+
import { UseFindPetsKeyFn, useAddPet, useFindPets } from "./openapi/queries";
|
|
106
|
+
|
|
107
|
+
const clientOptions = { query: { limit: 10 } };
|
|
108
|
+
const { data } = useFindPets(clientOptions);
|
|
109
|
+
const queryClient = useQueryClient();
|
|
110
|
+
// The first argument of a mutation hook is the mutation key.
|
|
111
|
+
const { mutate } = useAddPet(undefined, {
|
|
112
|
+
// Build the key with the same function and arguments the query hook used.
|
|
113
|
+
onSuccess: () =>
|
|
114
|
+
queryClient.invalidateQueries({ queryKey: UseFindPetsKeyFn(clientOptions) }),
|
|
115
|
+
});
|
|
116
|
+
mutate({ body: { name: "Fluffy" } });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Wrap the app in TanStack Query's `QueryClientProvider` as usual.
|
|
120
|
+
|
|
121
|
+
### CI drift check: `--check`
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
openapi-rq -i ./openapi.yaml -o ./src/openapi --check
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Generates into a temporary directory (`.openapi-rq-check-*` inside `<output>/queries`, removed afterwards), compares it with `<output>/requests` and `<output>/queries`, and changes no existing file. `--format`/`--lint` rules that target the output directory by path also apply to the temporary copy; a rule that names an exact file or depth from the project root (`src/openapi/queries/*.ts`) does not, so write such rules as `src/openapi/queries/**`. Each file is `added` (would be created), `modified` or `removed` (no longer generated).
|
|
128
|
+
|
|
129
|
+
The `queries/` headers include the package version, so after upgrading this package `--check` fails until you regenerate. Upgrade and regenerate in the same change.
|
|
130
|
+
|
|
131
|
+
### Exit codes and `--json`
|
|
132
|
+
|
|
133
|
+
| Exit code | Meaning |
|
|
134
|
+
| --- | --- |
|
|
135
|
+
| `0` | success, or `--check` found no differences |
|
|
136
|
+
| `1` | `--check` found differences |
|
|
137
|
+
| `2` | error (bad flags, unreadable spec, generation failure) |
|
|
138
|
+
|
|
139
|
+
With `--json`, a failure prints exactly one line of JSON on stderr, and nothing else is written there:
|
|
140
|
+
|
|
141
|
+
```json
|
|
142
|
+
{"code":"OUTPUT_OUT_OF_DATE","message":"Generated output is out of date (1 file differs). ...","details":{"files":[{"path":"src/openapi/queries/queries.ts","status":"modified"}]}}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
| `code` | When | `details` |
|
|
146
|
+
| --- | --- | --- |
|
|
147
|
+
| `INVALID_ARGUMENT` | unknown flag, bad choice, missing `-i` | `commanderCode` |
|
|
148
|
+
| `INPUT_NOT_FOUND` | spec file missing or URL request failed | `input`, `reason` |
|
|
149
|
+
| `INPUT_PARSE_ERROR` | spec is not valid YAML/JSON | `input`, `reason` |
|
|
150
|
+
| `CLIENT_GENERATION_FAILED` | the client could not be generated otherwise (an OpenAPI 2.0 spec, an unresolvable `$ref`) | `input`, `reason`, `name` |
|
|
151
|
+
| `GENERATION_FAILED` | hook generation failed | `name` |
|
|
152
|
+
| `OUTPUT_OUT_OF_DATE` | `--check` found differences (exit 1) | `files: [{ path, status }]` |
|
|
153
|
+
|
|
154
|
+
Branch on `code`, not on `message`. Codes are stable; messages may change.
|
|
155
|
+
|
|
156
|
+
### Programmatic API
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import { check, generate } from "@7nohe/openapi-react-query-codegen";
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`generate(options, version)` and `check(options, version)` take the same options as the CLI flags. `version` is written into the header of every `queries/` file, so `check` only matches output generated with the same string: pass the installed package version when the output came from the CLI. `check` resolves to `{ upToDate, files }`. Errors are `CodegenError` instances with `code` and `details`.
|
|
163
|
+
|
|
164
|
+
## Working on this repository
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
### Project Structure & Module Organization
|
|
168
|
+
- Source code lives in `src/` (CLI entry `cli.mts`, generator pipeline `generate.mts`, codegen helpers like `createSource.mts`, `createImports.mts`, `createExports.mts`, `service.mts`, formatting in `format.mts`).
|
|
169
|
+
- Tests reside in `tests/` (Vitest).
|
|
170
|
+
- Example apps under `examples/` (React/Next.js/TanStack Router) consume the generated client.
|
|
171
|
+
- Docs site in `docs/` (Astro). Build artifacts output to `dist/`.
|
|
172
|
+
|
|
173
|
+
### Build, Test, and Development Commands
|
|
174
|
+
- Install: `pnpm install`
|
|
175
|
+
- Build generator: `pnpm build` (cleans `dist/`, runs `tsc`).
|
|
176
|
+
- Lint/format check: `pnpm lint` (Biome). Auto-fix: `pnpm lint:fix`.
|
|
177
|
+
- Tests: `pnpm test` (Vitest with coverage). Snapshots: `pnpm snapshot`.
|
|
178
|
+
- Preview generation into examples: `pnpm preview:react`, `pnpm preview:nextjs`, `pnpm preview:tanstack-router`.
|
|
179
|
+
|
|
180
|
+
### Coding Style & Naming Conventions
|
|
181
|
+
- Language: TypeScript (strict, ESNext, NodeNext). Keep code in modules (`.mts`), output compiled to `dist/`.
|
|
182
|
+
- Formatting/linting via Biome: 2-space indent, double quotes, trailing commas, organized imports. Run formatters before committing.
|
|
183
|
+
- Generated outputs include a header comment with package version; preserve this when modifying generation.
|
|
184
|
+
- Prefer descriptive function names and explicit types; avoid implicit `any`.
|
|
185
|
+
|
|
186
|
+
### Testing Guidelines
|
|
187
|
+
- Framework: Vitest. Coverage enabled by default.
|
|
188
|
+
- Place tests in `tests/`; mirror generator behavior with snapshot tests where helpful.
|
|
189
|
+
- After generator changes, run tests and consider regenerating example outputs to manually diff.
|
|
190
|
+
|
|
191
|
+
### Commit & Pull Request Guidelines
|
|
192
|
+
- Commits: clear, descriptive messages (e.g., `fix: align imports for generated queries`, `chore: update ts-morph config`). Avoid bundling unrelated changes.
|
|
193
|
+
- Pull requests: include summary of changes, affected areas (e.g., codegen output, docs, examples), and test commands run. Link issues when applicable. Add before/after notes or sample generated snippets if behavior changes.
|
|
194
|
+
|
|
195
|
+
### Architecture: IR Boundary
|
|
196
|
+
- `src/client/` is the client generator. It reads the OpenAPI document and writes `requests/` (`types.gen.ts`, `sdk.gen.ts`, `client.gen.ts`, `runtime.gen.ts`, and on request `schemas.gen.ts` and `transformers.gen.ts`). It also returns the normalized operations (`OperationInfo` in `src/types.mts`) for the hook generators, so nothing re-parses the generated SDK.
|
|
197
|
+
- `src/generate.mts` is the only place that turns the client generator's failures into the error codes of `--json` (`mapClientError`).
|
|
198
|
+
- Generation-side modules (`src/tsmorph/build*.mts`, `generateFiles.mts`) consume only `OperationInfo` and `GenerationContext`. Do not teach them about the OpenAPI document or the runtime's internals; extend the IR instead.
|
|
199
|
+
- The generated hooks rely on a small SDK contract: `Options<XData, ThrowOnError>` exported from `sdk.gen`, calls returning `{ data }` and rejecting when `throwOnError` is set, and the `XData` / `XError` type names. Keep it in sync with `src/client/emitSdk.mts` and the runtimes in `src/client/runtime/`.
|
|
200
|
+
- The runtimes (`src/client/runtime/*.runtime.ts`) are plain TypeScript that is copied verbatim into users' projects. Keep them dependency-free (axios aside), strict-mode clean, and free of syntax that needs a newer TypeScript than the generated code supports. `scripts/copy-runtime.mjs` ships them next to the compiled generator.
|
|
201
|
+
|
|
202
|
+
### Dependencies
|
|
203
|
+
- Runtime dependencies are deliberately few (`cross-spawn`, `yaml`). Adding one needs a reason; the generator replaced `@hey-api/openapi-ts` to cut the supply-chain surface.
|
|
204
|
+
|
|
205
|
+
### Agent-Specific Notes
|
|
206
|
+
- Use AST-aware paths (ts-morph/TypeScript factory) when editing generators to keep output structurally valid.
|
|
207
|
+
- Respect ignore patterns in `biome.json` and avoid checking in `dist/` or example-generated artifacts unless explicitly intended.
|
package/README.md
CHANGED
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
- **Custom hooks**: `useQuery`, `useSuspenseQuery`, `useMutation`, `useInfiniteQuery`, and `useSuspenseInfiniteQuery` variants per operation
|
|
13
13
|
- **SSR helpers**: `prefetchQuery`, `prefetchInfiniteQuery`, and `ensureQueryData` functions per operation — ready for Next.js App Router hydration
|
|
14
14
|
- **Hierarchical query keys** with exported key constants and functions: invalidate one exact query, all infinite pages of an operation, or every cache entry of an operation with a single prefix
|
|
15
|
-
- **Pure TypeScript
|
|
15
|
+
- **Pure TypeScript client** (types, SDK functions and a small fetch or axios runtime) generated from the same OpenAPI 3.0/3.1 document — no separate client generator to install
|
|
16
|
+
- **CI- and agent-friendly**: `--check` fails CI when committed output is out of date, `--json` prints errors as machine-readable JSON, and the package ships an [`AGENTS.md`](./AGENTS.md) for coding agents
|
|
16
17
|
|
|
17
18
|
## Quick start
|
|
18
19
|
|
|
@@ -33,6 +34,9 @@ function Pets() {
|
|
|
33
34
|
|
|
34
35
|
See the [documentation](https://openapi-react-query-codegen.vercel.app) for CLI options, SSR recipes, and infinite query usage.
|
|
35
36
|
|
|
37
|
+
> [!IMPORTANT]
|
|
38
|
+
> The only package published by this project is the scoped **`@7nohe/openapi-react-query-codegen`**. The unscoped `openapi-react-query-codegen` and the copies under other scopes on npm are published by third parties, not by this project.
|
|
39
|
+
|
|
36
40
|
## How it compares
|
|
37
41
|
|
|
38
42
|
| | This library | @hey-api tanstack-query plugin | Orval | openapi-react-query |
|
|
@@ -45,13 +49,13 @@ See the [documentation](https://openapi-react-query-codegen.vercel.app) for CLI
|
|
|
45
49
|
| MSW mock generation | ❌ (out of scope) | ❌ | ✅ | ❌ |
|
|
46
50
|
| Vue / Solid / Svelte / Angular | ❌ React-focused | ✅ | ✅ | ❌ |
|
|
47
51
|
|
|
48
|
-
**Scope**: this library is deliberately React-focused and does not generate API mocks — use Orval if MSW mocks are your priority, or hey-api
|
|
52
|
+
**Scope**: this library is deliberately React-focused and does not generate API mocks — use Orval if MSW mocks are your priority, or the hey-api plugin if you need non-React frameworks.
|
|
49
53
|
|
|
50
54
|
**Coming from openapi-typescript / openapi-fetch / openapi-react-query?** See the [migration guide](https://openapi-react-query-codegen.vercel.app/guides/migrating-from-openapi-react-query/).
|
|
51
55
|
|
|
52
56
|
## Stability policy
|
|
53
57
|
|
|
54
|
-
|
|
58
|
+
The client generator is part of this package, so the generated `requests/` directory and the hooks built on it change together and follow SemVer: breaking output changes only happen in major versions, with a migration guide (see [Migrating to v4](https://openapi-react-query-codegen.vercel.app/guides/migrating-to-v4/) if you are coming from v3, where the client was produced by `@hey-api/openapi-ts`).
|
|
55
59
|
|
|
56
60
|
## Requirements
|
|
57
61
|
|
package/dist/check.d.mts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { LimitedUserConfig } from "./cli.mjs";
|
|
2
|
+
import { CodegenError } from "./errors.mjs";
|
|
3
|
+
export type FileChangeStatus = "added" | "modified" | "removed";
|
|
4
|
+
export type FileChange = {
|
|
5
|
+
/** Path of the file in the existing output, relative to cwd, `/`-separated. */
|
|
6
|
+
path: string;
|
|
7
|
+
/**
|
|
8
|
+
* - `added`: regeneration would create it (missing from the existing output)
|
|
9
|
+
* - `modified`: content differs
|
|
10
|
+
* - `removed`: present in the existing output but no longer generated
|
|
11
|
+
*/
|
|
12
|
+
status: FileChangeStatus;
|
|
13
|
+
};
|
|
14
|
+
export type CheckResult = {
|
|
15
|
+
upToDate: boolean;
|
|
16
|
+
files: FileChange[];
|
|
17
|
+
};
|
|
18
|
+
/** Name prefix of the throwaway directory `check` generates into. */
|
|
19
|
+
export declare const scratchPrefix = ".openapi-rq-check-";
|
|
20
|
+
/**
|
|
21
|
+
* Compare a freshly generated directory with the existing one.
|
|
22
|
+
* Returned paths are `displayRoot` joined with the file's relative path.
|
|
23
|
+
*/
|
|
24
|
+
export declare function diffDirectories({ expectedRoot, actualRoot, displayRoot, }: {
|
|
25
|
+
expectedRoot: string;
|
|
26
|
+
actualRoot: string;
|
|
27
|
+
displayRoot: string;
|
|
28
|
+
}): Promise<FileChange[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Pick where the throwaway generation goes.
|
|
31
|
+
*
|
|
32
|
+
* `--format`/`--lint` run on the scratch `queries/` files, and formatter and
|
|
33
|
+
* linter configuration is matched by path (overrides, ignore rules). So the
|
|
34
|
+
* scratch directory is created inside the existing `<output>/queries`, and
|
|
35
|
+
* the output's own path is repeated underneath it:
|
|
36
|
+
*
|
|
37
|
+
* src/openapi/queries/.openapi-rq-check-XXXX/src/openapi/queries/*.ts
|
|
38
|
+
*
|
|
39
|
+
* A rule for `src/openapi/**` or `src/openapi/queries/**` matches through the
|
|
40
|
+
* leading part, a rule for a folder named `openapi` or for
|
|
41
|
+
* `**\/openapi/queries/*.ts` through the trailing part. Only a rule anchored
|
|
42
|
+
* at the project root that also pins the depth or file name (for example
|
|
43
|
+
* `src/openapi/queries/*.ts`) does not carry over.
|
|
44
|
+
*
|
|
45
|
+
* When there is no `queries/` yet every query file is reported as `added`
|
|
46
|
+
* whatever its content, so the scratch directory goes next to the output, or
|
|
47
|
+
* into the OS temp dir when the parent does not exist either.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createScratchOutput(output: string): Promise<{
|
|
50
|
+
scratchRoot: string;
|
|
51
|
+
scratchOutput: string;
|
|
52
|
+
}>;
|
|
53
|
+
/**
|
|
54
|
+
* Generate into a temporary location and compare it with the existing
|
|
55
|
+
* output under `options.output`. Never modifies the existing files.
|
|
56
|
+
* Rejects only with {@link CodegenError}.
|
|
57
|
+
*/
|
|
58
|
+
export declare function check(options: LimitedUserConfig, version: string): Promise<CheckResult>;
|
|
59
|
+
export declare function outOfDateError(files: FileChange[]): CodegenError;
|
package/dist/check.mjs
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
|
+
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
|
|
6
|
+
import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
|
|
7
|
+
import { generate } from "./generate.mjs";
|
|
8
|
+
/** The generator owns exactly these subdirectories of the output path. */
|
|
9
|
+
const checkedSubdirectories = [requestsOutputPath, queriesOutputPath];
|
|
10
|
+
/** Name prefix of the throwaway directory `check` generates into. */
|
|
11
|
+
export const scratchPrefix = ".openapi-rq-check-";
|
|
12
|
+
function isDirectory(target) {
|
|
13
|
+
try {
|
|
14
|
+
return statSync(target).isDirectory();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function listFiles(root) {
|
|
21
|
+
if (!existsSync(root)) {
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
const files = [];
|
|
25
|
+
const walk = async (relativeDirectory) => {
|
|
26
|
+
const entries = await readdir(path.join(root, relativeDirectory), {
|
|
27
|
+
withFileTypes: true,
|
|
28
|
+
});
|
|
29
|
+
for (const entry of entries) {
|
|
30
|
+
// Scratch directories live inside the existing `queries/`. Skip them
|
|
31
|
+
// before descending: one that belongs to another check running at the
|
|
32
|
+
// same time can disappear while it is being read.
|
|
33
|
+
if (entry.name.startsWith(scratchPrefix)) {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const relative = path.join(relativeDirectory, entry.name);
|
|
37
|
+
if (entry.isDirectory()) {
|
|
38
|
+
await walk(relative);
|
|
39
|
+
}
|
|
40
|
+
else if (entry.isFile()) {
|
|
41
|
+
files.push(relative);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
await walk("");
|
|
46
|
+
return files;
|
|
47
|
+
}
|
|
48
|
+
// Code-unit order, not localeCompare, so the listing is identical everywhere.
|
|
49
|
+
const byPath = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
|
|
50
|
+
function toPosix(filePath) {
|
|
51
|
+
return filePath.split(path.sep).join("/");
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Compare a freshly generated directory with the existing one.
|
|
55
|
+
* Returned paths are `displayRoot` joined with the file's relative path.
|
|
56
|
+
*/
|
|
57
|
+
export async function diffDirectories({ expectedRoot, actualRoot, displayRoot, }) {
|
|
58
|
+
const [expectedFiles, actualFiles] = await Promise.all([
|
|
59
|
+
listFiles(expectedRoot),
|
|
60
|
+
listFiles(actualRoot),
|
|
61
|
+
]);
|
|
62
|
+
const actualSet = new Set(actualFiles);
|
|
63
|
+
const expectedSet = new Set(expectedFiles);
|
|
64
|
+
const changes = [];
|
|
65
|
+
for (const file of expectedFiles) {
|
|
66
|
+
const display = toPosix(path.join(displayRoot, file));
|
|
67
|
+
if (!actualSet.has(file)) {
|
|
68
|
+
changes.push({ path: display, status: "added" });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const [expected, actual] = await Promise.all([
|
|
72
|
+
readFile(path.join(expectedRoot, file)),
|
|
73
|
+
readFile(path.join(actualRoot, file)),
|
|
74
|
+
]);
|
|
75
|
+
if (!expected.equals(actual)) {
|
|
76
|
+
changes.push({ path: display, status: "modified" });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const file of actualFiles) {
|
|
80
|
+
if (!expectedSet.has(file)) {
|
|
81
|
+
changes.push({
|
|
82
|
+
path: toPosix(path.join(displayRoot, file)),
|
|
83
|
+
status: "removed",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return changes.sort(byPath);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Pick where the throwaway generation goes.
|
|
91
|
+
*
|
|
92
|
+
* `--format`/`--lint` run on the scratch `queries/` files, and formatter and
|
|
93
|
+
* linter configuration is matched by path (overrides, ignore rules). So the
|
|
94
|
+
* scratch directory is created inside the existing `<output>/queries`, and
|
|
95
|
+
* the output's own path is repeated underneath it:
|
|
96
|
+
*
|
|
97
|
+
* src/openapi/queries/.openapi-rq-check-XXXX/src/openapi/queries/*.ts
|
|
98
|
+
*
|
|
99
|
+
* A rule for `src/openapi/**` or `src/openapi/queries/**` matches through the
|
|
100
|
+
* leading part, a rule for a folder named `openapi` or for
|
|
101
|
+
* `**\/openapi/queries/*.ts` through the trailing part. Only a rule anchored
|
|
102
|
+
* at the project root that also pins the depth or file name (for example
|
|
103
|
+
* `src/openapi/queries/*.ts`) does not carry over.
|
|
104
|
+
*
|
|
105
|
+
* When there is no `queries/` yet every query file is reported as `added`
|
|
106
|
+
* whatever its content, so the scratch directory goes next to the output, or
|
|
107
|
+
* into the OS temp dir when the parent does not exist either.
|
|
108
|
+
*/
|
|
109
|
+
export async function createScratchOutput(output) {
|
|
110
|
+
const resolvedOutput = path.resolve(output);
|
|
111
|
+
const existingQueries = path.join(resolvedOutput, queriesOutputPath);
|
|
112
|
+
const parent = path.dirname(resolvedOutput);
|
|
113
|
+
const scratchParent = isDirectory(existingQueries)
|
|
114
|
+
? existingQueries
|
|
115
|
+
: existsSync(parent)
|
|
116
|
+
? parent
|
|
117
|
+
: tmpdir();
|
|
118
|
+
const scratchRoot = await mkdtemp(path.join(scratchParent, scratchPrefix));
|
|
119
|
+
const relativeOutput = path.relative(process.cwd(), resolvedOutput);
|
|
120
|
+
const insideCwd = relativeOutput !== "" &&
|
|
121
|
+
!relativeOutput.startsWith("..") &&
|
|
122
|
+
!path.isAbsolute(relativeOutput);
|
|
123
|
+
return {
|
|
124
|
+
scratchRoot,
|
|
125
|
+
scratchOutput: path.join(scratchRoot, insideCwd ? relativeOutput : path.basename(resolvedOutput)),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async function runCheck(options, version) {
|
|
129
|
+
const { scratchRoot, scratchOutput } = await createScratchOutput(options.output);
|
|
130
|
+
try {
|
|
131
|
+
await generate({ ...options, output: scratchOutput }, version, {
|
|
132
|
+
silent: true,
|
|
133
|
+
});
|
|
134
|
+
const changesPerDir = await Promise.all(checkedSubdirectories.map((subdirectory) => diffDirectories({
|
|
135
|
+
expectedRoot: path.join(scratchOutput, subdirectory),
|
|
136
|
+
actualRoot: path.join(options.output, subdirectory),
|
|
137
|
+
// Reported paths are cwd-relative even for an absolute output.
|
|
138
|
+
displayRoot: path.relative(process.cwd(), path.resolve(options.output, subdirectory)),
|
|
139
|
+
})));
|
|
140
|
+
const files = changesPerDir.flat().sort(byPath);
|
|
141
|
+
return { upToDate: files.length === 0, files };
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
await rm(scratchRoot, { recursive: true, force: true });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Generate into a temporary location and compare it with the existing
|
|
149
|
+
* output under `options.output`. Never modifies the existing files.
|
|
150
|
+
* Rejects only with {@link CodegenError}.
|
|
151
|
+
*/
|
|
152
|
+
export async function check(options, version) {
|
|
153
|
+
try {
|
|
154
|
+
return await runCheck(options, version);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
throw toCodegenError(error);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
export function outOfDateError(files) {
|
|
161
|
+
return new CodegenError(ErrorCodes.outputOutOfDate, `Generated output is out of date (${files.length} ${files.length === 1 ? "file differs" : "files differ"}). Re-run openapi-rq without --check to update it.`, { files });
|
|
162
|
+
}
|
package/dist/cli.d.mts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `fetch` and `axios` select the generated HTTP client. The `@hey-api/*`
|
|
4
|
+
* spellings are accepted as deprecated aliases for v3 command lines.
|
|
5
|
+
*/
|
|
6
|
+
export type ClientChoice = "fetch" | "axios" | "@hey-api/client-fetch" | "@hey-api/client-axios";
|
|
2
7
|
export type LimitedUserConfig = {
|
|
3
8
|
input: string;
|
|
4
9
|
output: string;
|
|
5
|
-
client?:
|
|
10
|
+
client?: ClientChoice;
|
|
6
11
|
format?: "biome" | "prettier";
|
|
7
12
|
lint?: "biome" | "eslint";
|
|
8
13
|
noOperationId?: boolean;
|
package/dist/cli.mjs
CHANGED
|
@@ -2,39 +2,12 @@
|
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
import { generate } from "./generate.mjs";
|
|
8
|
-
const program = new Command();
|
|
9
|
-
async function setupProgram() {
|
|
5
|
+
import { runCli } from "./runCli.mjs";
|
|
6
|
+
async function main() {
|
|
10
7
|
const __filename = fileURLToPath(import.meta.url);
|
|
11
8
|
const __dirname = dirname(__filename);
|
|
12
9
|
const file = await readFile(join(__dirname, "../package.json"), "utf-8");
|
|
13
10
|
const packageJson = JSON.parse(file);
|
|
14
|
-
|
|
15
|
-
program
|
|
16
|
-
.name("openapi-rq")
|
|
17
|
-
.version(version)
|
|
18
|
-
.description("Generate React Query code based on OpenAPI")
|
|
19
|
-
.requiredOption("-i, --input <value>", "OpenAPI specification, can be a path, url or string content (required)")
|
|
20
|
-
.option("-o, --output <value>", "Output directory", defaultOutputPath)
|
|
21
|
-
.addOption(new Option("-c, --client <value>", "HTTP client to generate")
|
|
22
|
-
.choices(["@hey-api/client-fetch", "@hey-api/client-axios"])
|
|
23
|
-
.default("@hey-api/client-fetch"))
|
|
24
|
-
.addOption(new Option("--format <value>", "Process output folder with formatter?").choices(["biome", "prettier"]))
|
|
25
|
-
.addOption(new Option("--lint <value>", "Process output folder with linter?").choices(["biome", "eslint"]))
|
|
26
|
-
.option("--noOperationId", "Do not use operationId to generate operation names")
|
|
27
|
-
.addOption(new Option("--enums <value>", "Generate JavaScript objects from enum definitions?").choices(["javascript", "typescript"]))
|
|
28
|
-
.option("--useDateType", "Use Date for date/date-time model properties and convert response values to Date objects")
|
|
29
|
-
.option("--debug", "Run in debug mode?")
|
|
30
|
-
.option("--noSchemas", "Disable generating JSON schemas")
|
|
31
|
-
.addOption(new Option("--schemaType <value>", "Type of JSON schema [Default: 'json']").choices(["form", "json"]))
|
|
32
|
-
.option("--pageParam <value>", "Name of the query parameter used for pagination", "page")
|
|
33
|
-
.option("--nextPageParam <value>", "Name of the response parameter used for next page", "nextPage")
|
|
34
|
-
.option("--initialPageParam <value>", "Initial page value to query", "1")
|
|
35
|
-
.option("--omitInitialPageParam", "Send no initial page parameter at all (overrides --initialPageParam)")
|
|
36
|
-
.parse();
|
|
37
|
-
const options = program.opts();
|
|
38
|
-
await generate(options, version);
|
|
11
|
+
process.exitCode = await runCli(process.argv, packageJson.version);
|
|
39
12
|
}
|
|
40
|
-
|
|
13
|
+
main();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type SchemaCtx } from "./schema.mjs";
|
|
2
|
+
/** `form` leaves out what only documents a schema, for use in form libraries. */
|
|
3
|
+
export type SchemasMode = "json" | "form";
|
|
4
|
+
/**
|
|
5
|
+
* Generate `schemas.gen.ts`: every component schema as a constant, the way the
|
|
6
|
+
* specification writes it. A schema with `readOnly` or `writeOnly` properties
|
|
7
|
+
* comes in two: what the API returns, and `…WritableSchema` for what it takes.
|
|
8
|
+
*/
|
|
9
|
+
export declare function emitSchemas(ctx: SchemaCtx, mode: SchemasMode): string | undefined;
|