@7nohe/openapi-react-query-codegen 3.1.0 → 3.2.1
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 +204 -0
- package/README.md +4 -0
- package/dist/check.d.mts +59 -0
- package/dist/check.mjs +162 -0
- package/dist/cli.mjs +4 -31
- package/dist/createSource.mjs +2 -2
- package/dist/errors.d.mts +43 -0
- package/dist/errors.mjs +61 -0
- package/dist/generate.d.mts +23 -1
- package/dist/generate.mjs +64 -2
- package/dist/runCli.d.mts +20 -0
- package/dist/runCli.mjs +100 -0
- package/package.json +4 -4
package/AGENTS.md
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
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 (via `@hey-api/openapi-ts`) 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 @hey-api/client-axios`, also add `axios`. Do not install `@hey-api/client-fetch` / `@hey-api/client-axios`; 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 2.0/3.x spec |
|
|
39
|
+
| `-o, --output <dir>` | `openapi` | `requests/` and `queries/` are created inside |
|
|
40
|
+
| `-c, --client <name>` | `@hey-api/client-fetch` | or `@hey-api/client-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 at runtime |
|
|
45
|
+
| `--noOperationId` | off | derive names from paths instead of `operationId` |
|
|
46
|
+
| `--noSchemas` / `--schemaType <json\|form>` | schemas on, `json` | JSON schema export |
|
|
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 from @hey-api/openapi-ts
|
|
69
|
+
├── client.gen.ts # `client` instance (setConfig, interceptors)
|
|
70
|
+
├── sdk.gen.ts # one function per operation
|
|
71
|
+
├── services.gen.ts # compatibility shim: re-exports client.gen + sdk.gen
|
|
72
|
+
└── types.gen.ts # request/response types
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
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.
|
|
76
|
+
|
|
77
|
+
### Using the generated code
|
|
78
|
+
|
|
79
|
+
Names come from the operation ID (or from the path with `--noOperationId`). For a GET operation `findPets` and a POST `addPet`:
|
|
80
|
+
|
|
81
|
+
| Export | File | Use |
|
|
82
|
+
| --- | --- | --- |
|
|
83
|
+
| `useFindPets(clientOptions?, queryKey?, options?)` | `queries.ts` | `useQuery` |
|
|
84
|
+
| `useFindPetsSuspense(...)` | `suspense.ts` | `useSuspenseQuery` |
|
|
85
|
+
| `useFindPetsInfinite(...)` | `infiniteQueries.ts` | only when the GET has the `--pageParam` query param |
|
|
86
|
+
| `useFindPetsSuspenseInfinite(...)`, `prefetchUseFindPetsInfinite(...)` | `suspense.ts`, `prefetch.ts` | same condition as above |
|
|
87
|
+
| `findPetsOptions(clientOptions?, queryKey?)` | `queryOptions.ts` | pass to `useQuery`, `useQueries`, loaders |
|
|
88
|
+
| `prefetchUseFindPets(queryClient, clientOptions?, options?)` | `prefetch.ts` | SSR / route loaders |
|
|
89
|
+
| `ensureUseFindPetsData(queryClient, clientOptions?, options?)` | `ensureQueryData.ts` | route loaders |
|
|
90
|
+
| `useFindPetsKey`, `UseFindPetsKeyFn(clientOptions?)` | `common.ts` | `invalidateQueries` with the same key the hook uses |
|
|
91
|
+
| `useAddPet(mutationKey?, options?)` | `queries.ts` | `useMutation`; `mutate({ body, path, query })` |
|
|
92
|
+
|
|
93
|
+
`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).
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
// once, at app start: configure the generated client
|
|
97
|
+
import { client } from "./openapi/requests/services.gen";
|
|
98
|
+
client.setConfig({ baseUrl: "https://api.example.com" }); // axios client: baseURL
|
|
99
|
+
|
|
100
|
+
// in components
|
|
101
|
+
import { useQueryClient } from "@tanstack/react-query";
|
|
102
|
+
import { UseFindPetsKeyFn, useAddPet, useFindPets } from "./openapi/queries";
|
|
103
|
+
|
|
104
|
+
const clientOptions = { query: { limit: 10 } };
|
|
105
|
+
const { data } = useFindPets(clientOptions);
|
|
106
|
+
const queryClient = useQueryClient();
|
|
107
|
+
// The first argument of a mutation hook is the mutation key.
|
|
108
|
+
const { mutate } = useAddPet(undefined, {
|
|
109
|
+
// Build the key with the same function and arguments the query hook used.
|
|
110
|
+
onSuccess: () =>
|
|
111
|
+
queryClient.invalidateQueries({ queryKey: UseFindPetsKeyFn(clientOptions) }),
|
|
112
|
+
});
|
|
113
|
+
mutate({ body: { name: "Fluffy" } });
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Wrap the app in TanStack Query's `QueryClientProvider` as usual.
|
|
117
|
+
|
|
118
|
+
### CI drift check: `--check`
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
openapi-rq -i ./openapi.yaml -o ./src/openapi --check
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
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).
|
|
125
|
+
|
|
126
|
+
The `queries/` headers include the package version, so after upgrading this package `--check` fails until you regenerate. Upgrade and regenerate in the same change.
|
|
127
|
+
|
|
128
|
+
### Exit codes and `--json`
|
|
129
|
+
|
|
130
|
+
| Exit code | Meaning |
|
|
131
|
+
| --- | --- |
|
|
132
|
+
| `0` | success, or `--check` found no differences |
|
|
133
|
+
| `1` | `--check` found differences |
|
|
134
|
+
| `2` | error (bad flags, unreadable spec, generation failure) |
|
|
135
|
+
|
|
136
|
+
With `--json`, a failure prints exactly one line of JSON on stderr, and @hey-api/openapi-ts's own logs are silenced:
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{"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"}]}}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| `code` | When | `details` |
|
|
143
|
+
| --- | --- | --- |
|
|
144
|
+
| `INVALID_ARGUMENT` | unknown flag, bad choice, missing `-i` | `commanderCode` |
|
|
145
|
+
| `INPUT_NOT_FOUND` | spec file missing or URL request failed | `input` |
|
|
146
|
+
| `INPUT_PARSE_ERROR` | spec is not valid YAML/JSON | `input`, `reason` |
|
|
147
|
+
| `CLIENT_GENERATION_FAILED` | @hey-api/openapi-ts failed otherwise | `input`, `reason`, `name` |
|
|
148
|
+
| `GENERATION_FAILED` | hook generation failed | `name` |
|
|
149
|
+
| `OUTPUT_OUT_OF_DATE` | `--check` found differences (exit 1) | `files: [{ path, status }]` |
|
|
150
|
+
|
|
151
|
+
Branch on `code`, not on `message`. Codes are stable; messages may change.
|
|
152
|
+
|
|
153
|
+
### Programmatic API
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { check, generate } from "@7nohe/openapi-react-query-codegen";
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`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`.
|
|
160
|
+
|
|
161
|
+
## Working on this repository
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
### Project Structure & Module Organization
|
|
165
|
+
- 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`).
|
|
166
|
+
- Tests reside in `tests/` (Vitest).
|
|
167
|
+
- Example apps under `examples/` (React/Next.js/TanStack Router) consume the generated client.
|
|
168
|
+
- Docs site in `docs/` (Astro). Build artifacts output to `dist/`.
|
|
169
|
+
|
|
170
|
+
### Build, Test, and Development Commands
|
|
171
|
+
- Install: `pnpm install`
|
|
172
|
+
- Build generator: `pnpm build` (cleans `dist/`, runs `tsc`).
|
|
173
|
+
- Lint/format check: `pnpm lint` (Biome). Auto-fix: `pnpm lint:fix`.
|
|
174
|
+
- Tests: `pnpm test` (Vitest with coverage). Snapshots: `pnpm snapshot`.
|
|
175
|
+
- Preview generation into examples: `pnpm preview:react`, `pnpm preview:nextjs`, `pnpm preview:tanstack-router`.
|
|
176
|
+
|
|
177
|
+
### Coding Style & Naming Conventions
|
|
178
|
+
- Language: TypeScript (strict, ESNext, NodeNext). Keep code in modules (`.mts`), output compiled to `dist/`.
|
|
179
|
+
- Formatting/linting via Biome: 2-space indent, double quotes, trailing commas, organized imports. Run formatters before committing.
|
|
180
|
+
- Generated outputs include a header comment with package version; preserve this when modifying generation.
|
|
181
|
+
- Prefer descriptive function names and explicit types; avoid implicit `any`.
|
|
182
|
+
|
|
183
|
+
### Testing Guidelines
|
|
184
|
+
- Framework: Vitest. Coverage enabled by default.
|
|
185
|
+
- Place tests in `tests/`; mirror generator behavior with snapshot tests where helpful.
|
|
186
|
+
- After generator changes, run tests and consider regenerating example outputs to manually diff.
|
|
187
|
+
|
|
188
|
+
### Commit & Pull Request Guidelines
|
|
189
|
+
- Commits: clear, descriptive messages (e.g., `fix: align imports for generated queries`, `chore: update ts-morph config`). Avoid bundling unrelated changes.
|
|
190
|
+
- 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.
|
|
191
|
+
|
|
192
|
+
### Architecture: IR Boundary (Backend Portability)
|
|
193
|
+
- The generation pipeline is split by an intermediate representation (IR): `OperationInfo` and `GenerationContext` in `src/types.mts`.
|
|
194
|
+
- hey-api-specific knowledge must stay confined to the parsing side: the `createClient` invocation in `src/generate.mts` and the `sdk.gen`/`types.gen` parsing in `src/service.mts` / `src/createSource.mts`.
|
|
195
|
+
- Generation-side modules (`src/tsmorph/build*.mts`, `generateFiles.mts`) should consume only the IR. Do not add new hey-api-specific parsing or imports there; extend the IR instead.
|
|
196
|
+
- This boundary is what keeps the generator portable to a different SDK backend without rewriting the generation layer. Treat leaks across it as review findings.
|
|
197
|
+
|
|
198
|
+
### hey-api Version Policy
|
|
199
|
+
- `@hey-api/openapi-ts` is pinned to an exact version and patched via `pnpm.patchedDependencies` when needed (see `patches/`).
|
|
200
|
+
- Upgrades: bump the pin, run the full snapshot suite, regenerate an example app and type-check it, then release as a minor version. Breaking changes in hey-api are absorbed here — they must not leak into the generated API surface outside a major version.
|
|
201
|
+
|
|
202
|
+
### Agent-Specific Notes
|
|
203
|
+
- Use AST-aware paths (ts-morph/TypeScript factory) when editing generators to keep output structurally valid.
|
|
204
|
+
- Respect ignore patterns in `biome.json` and avoid checking in `dist/` or example-generated artifacts unless explicitly intended.
|
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
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
15
|
- **Pure TypeScript clients** generated by [@hey-api/openapi-ts](https://github.com/hey-api/openapi-ts) (fetch and axios)
|
|
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 |
|
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.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();
|
package/dist/createSource.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
2
|
import { Project } from "ts-morph";
|
|
3
3
|
import { buildGenerationContext, parseOperations } from "./parseOperations.mjs";
|
|
4
4
|
import { generateAllFiles } from "./tsmorph/index.mjs";
|
|
@@ -10,7 +10,7 @@ export const createSource = async ({ outputPath, client, version, pageParam, nex
|
|
|
10
10
|
const project = new Project({
|
|
11
11
|
skipAddingFilesFromTsConfig: true,
|
|
12
12
|
});
|
|
13
|
-
const sourceFiles =
|
|
13
|
+
const sourceFiles = resolve(process.cwd(), outputPath);
|
|
14
14
|
project.addSourceFilesAtPaths(`${sourceFiles}/**/*`);
|
|
15
15
|
// Parse operations from the service file
|
|
16
16
|
const operations = await parseOperations(project, pageParam);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable, machine-readable error codes printed by `--json`.
|
|
3
|
+
* Changing or removing a code is a breaking change.
|
|
4
|
+
*/
|
|
5
|
+
export declare const ErrorCodes: {
|
|
6
|
+
readonly invalidArgument: "INVALID_ARGUMENT";
|
|
7
|
+
readonly inputNotFound: "INPUT_NOT_FOUND";
|
|
8
|
+
readonly inputParseError: "INPUT_PARSE_ERROR";
|
|
9
|
+
readonly clientGenerationFailed: "CLIENT_GENERATION_FAILED";
|
|
10
|
+
readonly generationFailed: "GENERATION_FAILED";
|
|
11
|
+
readonly outputOutOfDate: "OUTPUT_OUT_OF_DATE";
|
|
12
|
+
};
|
|
13
|
+
export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
|
|
14
|
+
export declare const ExitCodes: {
|
|
15
|
+
readonly success: 0;
|
|
16
|
+
readonly outOfDate: 1;
|
|
17
|
+
readonly error: 2;
|
|
18
|
+
};
|
|
19
|
+
export type ErrorDetails = Record<string, unknown>;
|
|
20
|
+
export declare class CodegenError extends Error {
|
|
21
|
+
readonly code: ErrorCode;
|
|
22
|
+
readonly details: ErrorDetails;
|
|
23
|
+
constructor(code: ErrorCode, message: string, details?: ErrorDetails, options?: {
|
|
24
|
+
cause?: unknown;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Anything that is not already a {@link CodegenError} is an unexpected
|
|
29
|
+
* failure in our own pipeline.
|
|
30
|
+
*/
|
|
31
|
+
export declare function toCodegenError(error: unknown): CodegenError;
|
|
32
|
+
export type JsonError = {
|
|
33
|
+
code: ErrorCode;
|
|
34
|
+
message: string;
|
|
35
|
+
details: ErrorDetails;
|
|
36
|
+
};
|
|
37
|
+
export declare function toJsonError(error: CodegenError): JsonError;
|
|
38
|
+
export declare function formatErrorJson(error: CodegenError): string;
|
|
39
|
+
/**
|
|
40
|
+
* Human-readable rendering for the default (non-JSON) mode.
|
|
41
|
+
* Unexpected failures keep their stack trace so they stay debuggable.
|
|
42
|
+
*/
|
|
43
|
+
export declare function formatErrorText(error: CodegenError): string;
|
package/dist/errors.mjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable, machine-readable error codes printed by `--json`.
|
|
3
|
+
* Changing or removing a code is a breaking change.
|
|
4
|
+
*/
|
|
5
|
+
export const ErrorCodes = {
|
|
6
|
+
invalidArgument: "INVALID_ARGUMENT",
|
|
7
|
+
inputNotFound: "INPUT_NOT_FOUND",
|
|
8
|
+
inputParseError: "INPUT_PARSE_ERROR",
|
|
9
|
+
clientGenerationFailed: "CLIENT_GENERATION_FAILED",
|
|
10
|
+
generationFailed: "GENERATION_FAILED",
|
|
11
|
+
outputOutOfDate: "OUTPUT_OUT_OF_DATE",
|
|
12
|
+
};
|
|
13
|
+
export const ExitCodes = {
|
|
14
|
+
success: 0,
|
|
15
|
+
outOfDate: 1,
|
|
16
|
+
error: 2,
|
|
17
|
+
};
|
|
18
|
+
export class CodegenError extends Error {
|
|
19
|
+
code;
|
|
20
|
+
details;
|
|
21
|
+
constructor(code, message, details = {}, options) {
|
|
22
|
+
super(message, options);
|
|
23
|
+
this.name = "CodegenError";
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.details = details;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Anything that is not already a {@link CodegenError} is an unexpected
|
|
30
|
+
* failure in our own pipeline.
|
|
31
|
+
*/
|
|
32
|
+
export function toCodegenError(error) {
|
|
33
|
+
if (error instanceof CodegenError) {
|
|
34
|
+
return error;
|
|
35
|
+
}
|
|
36
|
+
if (error instanceof Error) {
|
|
37
|
+
return new CodegenError(ErrorCodes.generationFailed, error.message, { name: error.name }, { cause: error });
|
|
38
|
+
}
|
|
39
|
+
return new CodegenError(ErrorCodes.generationFailed, String(error));
|
|
40
|
+
}
|
|
41
|
+
export function toJsonError(error) {
|
|
42
|
+
return {
|
|
43
|
+
code: error.code,
|
|
44
|
+
message: error.message,
|
|
45
|
+
details: error.details,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function formatErrorJson(error) {
|
|
49
|
+
return JSON.stringify(toJsonError(error));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Human-readable rendering for the default (non-JSON) mode.
|
|
53
|
+
* Unexpected failures keep their stack trace so they stay debuggable.
|
|
54
|
+
*/
|
|
55
|
+
export function formatErrorText(error) {
|
|
56
|
+
const cause = error.cause;
|
|
57
|
+
if (error.code === ErrorCodes.generationFailed && cause instanceof Error) {
|
|
58
|
+
return `error [${error.code}]: ${cause.stack ?? cause.message}`;
|
|
59
|
+
}
|
|
60
|
+
return `error [${error.code}]: ${error.message}`;
|
|
61
|
+
}
|
package/dist/generate.d.mts
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
1
|
import type { LimitedUserConfig } from "./cli.mjs";
|
|
2
|
+
import { CodegenError } from "./errors.mjs";
|
|
2
3
|
export declare function findNearestTsConfigPath(startDir: string): string | undefined;
|
|
3
|
-
export
|
|
4
|
+
export type GenerateRuntimeOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Silence @hey-api/openapi-ts logs and stop it from writing crash-report
|
|
7
|
+
* files into cwd. Used by `--json` (stderr must carry only our JSON) and
|
|
8
|
+
* by `--check` (which must leave nothing behind).
|
|
9
|
+
*/
|
|
10
|
+
silent?: boolean;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Translate @hey-api/openapi-ts failures into our stable error codes.
|
|
14
|
+
* hey-api's error classes live in a transitive dependency, so they are
|
|
15
|
+
* matched by name rather than imported. This is the only place that knows
|
|
16
|
+
* about them (see the IR boundary notes in AGENTS.md).
|
|
17
|
+
*/
|
|
18
|
+
export declare function mapClientError(error: unknown, input: unknown): CodegenError;
|
|
19
|
+
/**
|
|
20
|
+
* Generate the client and the React Query hooks into `options.output`.
|
|
21
|
+
* Rejects only with {@link CodegenError}, so callers can branch on `code`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function generate(options: LimitedUserConfig, version: string, runtime?: GenerateRuntimeOptions): Promise<void>;
|
|
24
|
+
export { type CheckResult, check, type FileChange, type FileChangeStatus, } from "./check.mjs";
|
|
25
|
+
export { CodegenError, type ErrorCode, ErrorCodes, ExitCodes, } from "./errors.mjs";
|
package/dist/generate.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { createClient } from "@hey-api/openapi-ts";
|
|
5
5
|
import { buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, } from "./common.mjs";
|
|
6
6
|
import { createSource } from "./createSource.mjs";
|
|
7
|
+
import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
|
|
7
8
|
import { formatOutput, processOutput } from "./format.mjs";
|
|
8
9
|
import { print } from "./print.mjs";
|
|
9
10
|
// openapi-ts's own tsconfig auto-detection walks up from its *install*
|
|
@@ -25,7 +26,36 @@ export function findNearestTsConfigPath(startDir) {
|
|
|
25
26
|
dir = parent;
|
|
26
27
|
}
|
|
27
28
|
}
|
|
28
|
-
|
|
29
|
+
/** Keep inline spec content out of error details; it can be huge. */
|
|
30
|
+
function describeInput(input) {
|
|
31
|
+
if (typeof input === "string" && !input.includes("\n")) {
|
|
32
|
+
return input;
|
|
33
|
+
}
|
|
34
|
+
return "(inline specification)";
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Translate @hey-api/openapi-ts failures into our stable error codes.
|
|
38
|
+
* hey-api's error classes live in a transitive dependency, so they are
|
|
39
|
+
* matched by name rather than imported. This is the only place that knows
|
|
40
|
+
* about them (see the IR boundary notes in AGENTS.md).
|
|
41
|
+
*/
|
|
42
|
+
export function mapClientError(error, input) {
|
|
43
|
+
if (error instanceof CodegenError) {
|
|
44
|
+
return error;
|
|
45
|
+
}
|
|
46
|
+
const inputDescription = describeInput(input);
|
|
47
|
+
const err = error;
|
|
48
|
+
const original = err?.originalError?.error;
|
|
49
|
+
const reason = original?.message ?? err?.message ?? String(error);
|
|
50
|
+
if (err?.name === "InputError") {
|
|
51
|
+
return new CodegenError(ErrorCodes.inputNotFound, `OpenAPI input could not be read: ${inputDescription}`, { input: inputDescription, reason }, { cause: error });
|
|
52
|
+
}
|
|
53
|
+
if (err?.name === "JobError" && original?.code === "EPARSER") {
|
|
54
|
+
return new CodegenError(ErrorCodes.inputParseError, `OpenAPI input could not be parsed: ${inputDescription}`, { input: inputDescription, reason }, { cause: error });
|
|
55
|
+
}
|
|
56
|
+
return new CodegenError(ErrorCodes.clientGenerationFailed, `@hey-api/openapi-ts failed to generate the client: ${reason}`, { input: inputDescription, reason, name: err?.name ?? "Error" }, { cause: error });
|
|
57
|
+
}
|
|
58
|
+
async function runGenerate(options, version, runtime) {
|
|
29
59
|
const openApiOutputPath = buildRequestsOutputPath(options.output);
|
|
30
60
|
const formattedOptions = formatOptions(options);
|
|
31
61
|
// Map CLI options to new plugins system
|
|
@@ -80,8 +110,23 @@ export async function generate(options, version) {
|
|
|
80
110
|
tsConfigPath: findNearestTsConfigPath(process.cwd()) ?? null,
|
|
81
111
|
},
|
|
82
112
|
plugins,
|
|
113
|
+
...(runtime.silent
|
|
114
|
+
? { logs: { level: "silent", file: false } }
|
|
115
|
+
: {}),
|
|
83
116
|
};
|
|
84
|
-
|
|
117
|
+
let contexts;
|
|
118
|
+
try {
|
|
119
|
+
contexts = await createClient(config);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
throw mapClientError(error, formattedOptions.input);
|
|
123
|
+
}
|
|
124
|
+
// openapi-ts swallows input errors (file not found, HTTP failure), logs
|
|
125
|
+
// them and resolves with no contexts instead of throwing.
|
|
126
|
+
if (contexts.length === 0) {
|
|
127
|
+
const inputDescription = describeInput(formattedOptions.input);
|
|
128
|
+
throw new CodegenError(ErrorCodes.inputNotFound, `OpenAPI input could not be read (file not found or request failed): ${inputDescription}`, { input: inputDescription });
|
|
129
|
+
}
|
|
85
130
|
// Generate backward-compatible services.gen.ts shim
|
|
86
131
|
// client.gen.ts has the `client` instance; sdk.gen.ts has SDK functions.
|
|
87
132
|
// Mirror whatever extension convention openapi-ts used for its own
|
|
@@ -108,3 +153,20 @@ export async function generate(options, version) {
|
|
|
108
153
|
lint: formattedOptions.lint,
|
|
109
154
|
});
|
|
110
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Generate the client and the React Query hooks into `options.output`.
|
|
158
|
+
* Rejects only with {@link CodegenError}, so callers can branch on `code`.
|
|
159
|
+
*/
|
|
160
|
+
export async function generate(options, version, runtime = {}) {
|
|
161
|
+
try {
|
|
162
|
+
await runGenerate(options, version, runtime);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
throw toCodegenError(error);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// Public library surface for the agent-facing features. `check` imports
|
|
169
|
+
// `generate` from this module; the cycle is safe because both are hoisted
|
|
170
|
+
// function declarations.
|
|
171
|
+
export { check, } from "./check.mjs";
|
|
172
|
+
export { CodegenError, ErrorCodes, ExitCodes, } from "./errors.mjs";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { type CheckResult } from "./check.mjs";
|
|
3
|
+
import type { LimitedUserConfig } from "./cli.mjs";
|
|
4
|
+
import { type GenerateRuntimeOptions } from "./generate.mjs";
|
|
5
|
+
export type CliIO = {
|
|
6
|
+
stdout: (text: string) => void;
|
|
7
|
+
stderr: (text: string) => void;
|
|
8
|
+
};
|
|
9
|
+
export type CliDependencies = {
|
|
10
|
+
generate: (options: LimitedUserConfig, version: string, runtime?: GenerateRuntimeOptions) => Promise<void>;
|
|
11
|
+
check: (options: LimitedUserConfig, version: string) => Promise<CheckResult>;
|
|
12
|
+
};
|
|
13
|
+
export declare function buildProgram(version: string, io: CliIO, { json }: {
|
|
14
|
+
json: boolean;
|
|
15
|
+
}): Command;
|
|
16
|
+
/**
|
|
17
|
+
* Run the CLI and resolve with the process exit code:
|
|
18
|
+
* 0 = success / up to date, 1 = `--check` found drift, 2 = error.
|
|
19
|
+
*/
|
|
20
|
+
export declare function runCli(argv: readonly string[], version: string, io?: CliIO, dependencies?: CliDependencies): Promise<number>;
|
package/dist/runCli.mjs
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Command, CommanderError, Option } from "commander";
|
|
2
|
+
import { check, outOfDateError } from "./check.mjs";
|
|
3
|
+
import { defaultOutputPath } from "./constants.mjs";
|
|
4
|
+
import { CodegenError, ErrorCodes, ExitCodes, formatErrorJson, formatErrorText, toCodegenError, } from "./errors.mjs";
|
|
5
|
+
import { generate } from "./generate.mjs";
|
|
6
|
+
const defaultIO = {
|
|
7
|
+
stdout: (text) => process.stdout.write(text),
|
|
8
|
+
stderr: (text) => process.stderr.write(text),
|
|
9
|
+
};
|
|
10
|
+
const defaultDependencies = { generate, check };
|
|
11
|
+
export function buildProgram(version, io, { json }) {
|
|
12
|
+
return new Command()
|
|
13
|
+
.name("openapi-rq")
|
|
14
|
+
.version(version)
|
|
15
|
+
.description("Generate React Query code based on OpenAPI")
|
|
16
|
+
.exitOverride()
|
|
17
|
+
.configureOutput({
|
|
18
|
+
writeOut: io.stdout,
|
|
19
|
+
writeErr: io.stderr,
|
|
20
|
+
// With --json the error is reported once, as JSON, by runCli.
|
|
21
|
+
outputError: (text, write) => {
|
|
22
|
+
if (!json)
|
|
23
|
+
write(text);
|
|
24
|
+
},
|
|
25
|
+
})
|
|
26
|
+
.requiredOption("-i, --input <value>", "OpenAPI specification, can be a path, url or string content (required)")
|
|
27
|
+
.option("-o, --output <value>", "Output directory", defaultOutputPath)
|
|
28
|
+
.addOption(new Option("-c, --client <value>", "HTTP client to generate")
|
|
29
|
+
.choices(["@hey-api/client-fetch", "@hey-api/client-axios"])
|
|
30
|
+
.default("@hey-api/client-fetch"))
|
|
31
|
+
.addOption(new Option("--format <value>", "Process output folder with formatter?").choices(["biome", "prettier"]))
|
|
32
|
+
.addOption(new Option("--lint <value>", "Process output folder with linter?").choices(["biome", "eslint"]))
|
|
33
|
+
.option("--noOperationId", "Do not use operationId to generate operation names")
|
|
34
|
+
.addOption(new Option("--enums <value>", "Generate JavaScript objects from enum definitions?").choices(["javascript", "typescript"]))
|
|
35
|
+
.option("--useDateType", "Use Date for date/date-time model properties and convert response values to Date objects")
|
|
36
|
+
.option("--debug", "Run in debug mode?")
|
|
37
|
+
.option("--noSchemas", "Disable generating JSON schemas")
|
|
38
|
+
.addOption(new Option("--schemaType <value>", "Type of JSON schema [Default: 'json']").choices(["form", "json"]))
|
|
39
|
+
.option("--pageParam <value>", "Name of the query parameter used for pagination", "page")
|
|
40
|
+
.option("--nextPageParam <value>", "Name of the response parameter used for next page", "nextPage")
|
|
41
|
+
.option("--initialPageParam <value>", "Initial page value to query", "1")
|
|
42
|
+
.option("--omitInitialPageParam", "Send no initial page parameter at all (overrides --initialPageParam)")
|
|
43
|
+
.option("--check", "Do not update the output; exit 1 and list the files that differ if the existing output is out of date")
|
|
44
|
+
.option("--json", "Print errors to stderr as a single line of JSON ({ code, message, details })");
|
|
45
|
+
}
|
|
46
|
+
function reportError(error, io, json) {
|
|
47
|
+
if (json) {
|
|
48
|
+
io.stderr(`${formatErrorJson(error)}\n`);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
io.stderr(`${formatErrorText(error)}\n`);
|
|
52
|
+
if (error.code === ErrorCodes.outputOutOfDate) {
|
|
53
|
+
const files = error.details.files;
|
|
54
|
+
for (const file of files) {
|
|
55
|
+
io.stderr(` ${file.status.padEnd(8)} ${file.path}\n`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Run the CLI and resolve with the process exit code:
|
|
61
|
+
* 0 = success / up to date, 1 = `--check` found drift, 2 = error.
|
|
62
|
+
*/
|
|
63
|
+
export async function runCli(argv, version, io = defaultIO, dependencies = defaultDependencies) {
|
|
64
|
+
// Decided before parsing so that argument errors can be JSON too.
|
|
65
|
+
const json = argv.includes("--json");
|
|
66
|
+
const program = buildProgram(version, io, { json });
|
|
67
|
+
try {
|
|
68
|
+
program.parse([...argv]);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (!(error instanceof CommanderError))
|
|
72
|
+
throw error;
|
|
73
|
+
// --help and --version also exit through exitOverride.
|
|
74
|
+
if (error.exitCode === 0)
|
|
75
|
+
return ExitCodes.success;
|
|
76
|
+
const codegenError = new CodegenError(ErrorCodes.invalidArgument, error.message.replace(/^error: /, ""), { commanderCode: error.code });
|
|
77
|
+
// Commander already printed its own message in text mode.
|
|
78
|
+
if (json)
|
|
79
|
+
reportError(codegenError, io, json);
|
|
80
|
+
return ExitCodes.error;
|
|
81
|
+
}
|
|
82
|
+
const { check: checkMode, json: _json, ...options } = program.opts();
|
|
83
|
+
try {
|
|
84
|
+
if (checkMode) {
|
|
85
|
+
const result = await dependencies.check(options, version);
|
|
86
|
+
if (result.upToDate) {
|
|
87
|
+
io.stdout("✔ Generated output is up to date.\n");
|
|
88
|
+
return ExitCodes.success;
|
|
89
|
+
}
|
|
90
|
+
reportError(outOfDateError(result.files), io, json);
|
|
91
|
+
return ExitCodes.outOfDate;
|
|
92
|
+
}
|
|
93
|
+
await dependencies.generate(options, version, { silent: json });
|
|
94
|
+
return ExitCodes.success;
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
reportError(toCodegenError(error), io, json);
|
|
98
|
+
return ExitCodes.error;
|
|
99
|
+
}
|
|
100
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@7nohe/openapi-react-query-codegen",
|
|
3
|
-
"version": "3.1
|
|
3
|
+
"version": "3.2.1",
|
|
4
4
|
"description": "OpenAPI React Query Codegen",
|
|
5
5
|
"bin": {
|
|
6
6
|
"openapi-rq": "dist/cli.mjs"
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"homepage": "https://github.com/7nohe/openapi-react-query-codegen",
|
|
25
25
|
"bugs": "https://github.com/7nohe/openapi-react-query-codegen/issues",
|
|
26
26
|
"files": [
|
|
27
|
-
"dist"
|
|
27
|
+
"dist",
|
|
28
|
+
"AGENTS.md"
|
|
28
29
|
],
|
|
29
30
|
"keywords": [
|
|
30
31
|
"codegen",
|
|
@@ -50,7 +51,6 @@
|
|
|
50
51
|
"@vitest/coverage-v8": "^4.1.12",
|
|
51
52
|
"commander": "^15.0.0",
|
|
52
53
|
"lefthook": "^2.1.10",
|
|
53
|
-
"rimraf": "^6.1.3",
|
|
54
54
|
"ts-morph": "^28.0.0",
|
|
55
55
|
"typescript": "^6.0.3",
|
|
56
56
|
"vite": "^7.3.7",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"pnpm": ">=9"
|
|
68
68
|
},
|
|
69
69
|
"scripts": {
|
|
70
|
-
"build": "
|
|
70
|
+
"build": "node scripts/clean.mjs dist && tsc -p tsconfig.json",
|
|
71
71
|
"lint": "biome check .",
|
|
72
72
|
"lint:fix": "biome check --write .",
|
|
73
73
|
"preview:react": "npm run build && npm -C examples/react-app run generate:api",
|