@7nohe/openapi-react-query-codegen 4.0.0-beta.5 → 4.0.0-beta.6
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 +19 -1
- package/README.md +5 -2
- package/dist/agentsMd.d.mts +30 -0
- package/dist/agentsMd.mjs +115 -0
- package/dist/check.mjs +8 -4
- package/dist/cli.d.mts +2 -0
- package/dist/generate.mjs +8 -0
- package/dist/runCli.mjs +1 -0
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -17,10 +17,12 @@ Docs: https://openapi-react-query-codegen.vercel.app (summary for LLMs: https://
|
|
|
17
17
|
### Install
|
|
18
18
|
|
|
19
19
|
```bash
|
|
20
|
-
npm install -D @7nohe/openapi-react-query-codegen
|
|
20
|
+
npm install -D @7nohe/openapi-react-query-codegen@beta
|
|
21
21
|
npm install @tanstack/react-query
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
+
v4 is in beta: without `@beta`, npm installs v3, which this file does not describe.
|
|
25
|
+
|
|
24
26
|
`commander` is a peer dependency. If your package manager does not install peers automatically, add it as a devDependency. The generated code compiles with TypeScript 5, 6 and 7; the generator itself does not need the `typescript` package. For `--client axios`, also add `axios`. Nothing else is needed at runtime; the client code is generated into `requests/`.
|
|
25
27
|
|
|
26
28
|
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.
|
|
@@ -47,6 +49,7 @@ Add a script and run it whenever the spec changes:
|
|
|
47
49
|
| `--pageParam <name>` | `page` | query param that turns a GET into an infinite query |
|
|
48
50
|
| `--nextPageParam <path>` | `nextPage` | response field holding the next page (dot path allowed, e.g. `meta.next`) |
|
|
49
51
|
| `--initialPageParam <value>` / `--omitInitialPageParam` | `1` | first page value, or send none |
|
|
52
|
+
| `--agentsMd [file]` | off | also keep a lookup guide for agents in `AGENTS.md` (or the file named), see below |
|
|
50
53
|
| `--check` | off | do not update the output; exit 1 if it is out of date (see below) |
|
|
51
54
|
| `--json` | off | errors as one JSON line on stderr (see below) |
|
|
52
55
|
|
|
@@ -120,6 +123,21 @@ mutate({ body: { name: "Fluffy" } });
|
|
|
120
123
|
|
|
121
124
|
Wrap the app in TanStack Query's `QueryClientProvider` as usual.
|
|
122
125
|
|
|
126
|
+
### Looking an operation up: `--agentsMd`
|
|
127
|
+
|
|
128
|
+
The generated files can be very large. Do not read them whole: an operation's function, hook and types each start a line, so `grep` finds them.
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
# the function of an operation, by a word in its name or by its URL path
|
|
132
|
+
grep -o '^export const [A-Za-z0-9_]*' src/openapi/requests/sdk.gen.ts | grep -i pet
|
|
133
|
+
grep -B7 'url: "/pets/{petId}"' src/openapi/requests/sdk.gen.ts | grep -o 'export const [A-Za-z0-9_]*'
|
|
134
|
+
# what it takes (path, query, body) and what it returns for each status
|
|
135
|
+
grep -n -A30 '^export type FindPetsData = ' src/openapi/requests/types.gen.ts
|
|
136
|
+
grep -n -A12 '^export type FindPetsResponses = ' src/openapi/requests/types.gen.ts
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
With `--agentsMd` in the codegen script, the generator keeps these instructions, with the project's real output path, in a block of the project's `AGENTS.md` (`--agentsMd CLAUDE.md` for another file). The block is between `<!-- openapi-rq:begin <output> -->` and `<!-- openapi-rq:end <output> -->`; do not edit inside it, it is replaced on the next run, and `--check` reports it when it is missing or out of date. If the project has a `CLAUDE.md` that does not import `AGENTS.md`, add `@AGENTS.md` to it.
|
|
140
|
+
|
|
123
141
|
### CI drift check: `--check`
|
|
124
142
|
|
|
125
143
|
```bash
|
package/README.md
CHANGED
|
@@ -13,12 +13,15 @@
|
|
|
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 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
|
+
- **CI- and agent-friendly**: `--check` fails CI when committed output is out of date, `--json` prints errors as machine-readable JSON, `--agentsMd` keeps a guide in your `AGENTS.md` that lets a coding agent look one operation up instead of reading the generated files, and the package ships an [`AGENTS.md`](./AGENTS.md) for coding agents
|
|
17
17
|
|
|
18
18
|
## Quick start
|
|
19
19
|
|
|
20
|
+
> [!NOTE]
|
|
21
|
+
> v4 is in beta, and this README describes it. Install it with `@beta`; a plain `npm install` still gets v3, whose README and docs are in the [`v3` branch](https://github.com/7nohe/openapi-react-query-codegen/tree/v3). What changes from v3 is in [Migrating to v4](https://openapi-react-query-codegen.vercel.app/guides/migrating-to-v4/).
|
|
22
|
+
|
|
20
23
|
```bash
|
|
21
|
-
npm install -D @7nohe/openapi-react-query-codegen
|
|
24
|
+
npm install -D @7nohe/openapi-react-query-codegen@beta
|
|
22
25
|
npx openapi-rq -i ./petstore.yaml
|
|
23
26
|
```
|
|
24
27
|
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { FileChange } from "./check.mjs";
|
|
2
|
+
/** Where `--agentsMd` writes when it is given no file name. */
|
|
3
|
+
export declare const defaultAgentsFile = "AGENTS.md";
|
|
4
|
+
/** The file `--agentsMd` names: the option is `true` without a value. */
|
|
5
|
+
export declare function agentsFilePath(option: string | boolean): string;
|
|
6
|
+
/**
|
|
7
|
+
* What a coding agent needs to use the generated client without reading its
|
|
8
|
+
* files, which are far too large for that: how the names are built, and how to
|
|
9
|
+
* find an operation and its types with `grep`.
|
|
10
|
+
*
|
|
11
|
+
* The block sits between two comments that carry the output path, so that it
|
|
12
|
+
* can be found again and replaced, and a project with two generated clients
|
|
13
|
+
* gets one block for each.
|
|
14
|
+
*/
|
|
15
|
+
export declare function renderAgentsBlock(output: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* Put the block into the content of an instructions file: in place of the
|
|
18
|
+
* block that is there for the same output, or else at the end.
|
|
19
|
+
*/
|
|
20
|
+
export declare function applyAgentsBlock(existing: string | undefined, block: string): string;
|
|
21
|
+
/** Write or refresh the block for `output` in `file`. */
|
|
22
|
+
export declare function writeAgentsBlock(file: string, output: string): Promise<void>;
|
|
23
|
+
/** What `--check` reports for the block, if it is missing or out of date. */
|
|
24
|
+
export declare function checkAgentsBlock(file: string, output: string): Promise<FileChange | undefined>;
|
|
25
|
+
/**
|
|
26
|
+
* Claude Code reads `AGENTS.md` only where there is no `CLAUDE.md`. When the
|
|
27
|
+
* block goes into an `AGENTS.md` next to a `CLAUDE.md` that does not import
|
|
28
|
+
* it, say how to make the block reach Claude Code as well.
|
|
29
|
+
*/
|
|
30
|
+
export declare function claudeImportHint(file: string): Promise<string | undefined>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
|
|
5
|
+
/** Where `--agentsMd` writes when it is given no file name. */
|
|
6
|
+
export const defaultAgentsFile = "AGENTS.md";
|
|
7
|
+
/** The file `--agentsMd` names: the option is `true` without a value. */
|
|
8
|
+
export function agentsFilePath(option) {
|
|
9
|
+
return typeof option === "string" && option !== ""
|
|
10
|
+
? option
|
|
11
|
+
: defaultAgentsFile;
|
|
12
|
+
}
|
|
13
|
+
/** The output directory as an agent working in cwd would write it. */
|
|
14
|
+
function displayPath(output) {
|
|
15
|
+
const relative = path.relative(process.cwd(), path.resolve(output));
|
|
16
|
+
const inside = relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
17
|
+
return (inside ? relative : output).split(path.sep).join("/");
|
|
18
|
+
}
|
|
19
|
+
const begin = (output) => `<!-- openapi-rq:begin ${output} -->`;
|
|
20
|
+
const end = (output) => `<!-- openapi-rq:end ${output} -->`;
|
|
21
|
+
/**
|
|
22
|
+
* What a coding agent needs to use the generated client without reading its
|
|
23
|
+
* files, which are far too large for that: how the names are built, and how to
|
|
24
|
+
* find an operation and its types with `grep`.
|
|
25
|
+
*
|
|
26
|
+
* The block sits between two comments that carry the output path, so that it
|
|
27
|
+
* can be found again and replaced, and a project with two generated clients
|
|
28
|
+
* gets one block for each.
|
|
29
|
+
*/
|
|
30
|
+
export function renderAgentsBlock(output) {
|
|
31
|
+
const out = displayPath(output);
|
|
32
|
+
const sdk = `${out}/${requestsOutputPath}/sdk.gen.ts`;
|
|
33
|
+
const types = `${out}/${requestsOutputPath}/types.gen.ts`;
|
|
34
|
+
return `${begin(out)}
|
|
35
|
+
## Generated API client (\`${out}\`)
|
|
36
|
+
|
|
37
|
+
\`${out}\` is generated by \`openapi-rq\` (\`@7nohe/openapi-react-query-codegen\`) from the OpenAPI document. Do not edit it: change the document or the flags and generate again. Its files can be very large, so look things up as described here instead of reading them.
|
|
38
|
+
|
|
39
|
+
### Names
|
|
40
|
+
|
|
41
|
+
For an operation whose function is \`findPets\` (a GET) or \`addPet\` (any other method):
|
|
42
|
+
|
|
43
|
+
- \`${queriesOutputPath}/queries.ts\`: \`useFindPets(clientOptions?, queryKey?, options?)\` (useQuery) and \`useAddPet(mutationKey?, options?)\` (useMutation, called as \`mutate(clientOptions)\`)
|
|
44
|
+
- \`${queriesOutputPath}/suspense.ts\`: \`useFindPetsSuspense\`. \`${queriesOutputPath}/queryOptions.ts\`: \`findPetsOptions\`. \`${queriesOutputPath}/prefetch.ts\`: \`prefetchUseFindPets\`. \`${queriesOutputPath}/ensureQueryData.ts\`: \`ensureUseFindPetsData\`
|
|
45
|
+
- \`${queriesOutputPath}/common.ts\`: \`useFindPetsKey\` and \`UseFindPetsKeyFn(clientOptions?)\`, for \`invalidateQueries\`
|
|
46
|
+
- Import them from \`${out}/${queriesOutputPath}\`. \`clientOptions\` is \`{ path, query, body, headers }\`.
|
|
47
|
+
|
|
48
|
+
### Finding an operation
|
|
49
|
+
|
|
50
|
+
- By a word in its name: \`grep -o '^export const [A-Za-z0-9_]*' ${sdk} | grep -i pet\`
|
|
51
|
+
- By URL path: \`grep -B7 'url: "/pets/{petId}"' ${sdk} | grep -o 'export const [A-Za-z0-9_]*'\`. The function is the last name before each match.
|
|
52
|
+
|
|
53
|
+
### What an operation takes and returns
|
|
54
|
+
|
|
55
|
+
- \`grep -n -A30 '^export type FindPetsData = ' ${types}\`: \`path\`, \`query\` and \`body\`
|
|
56
|
+
- \`grep -n -A12 '^export type FindPetsResponses = ' ${types}\`: the response for each status
|
|
57
|
+
- A schema one of them names: \`grep -n -A40 '^export type Pet = ' ${types}\`
|
|
58
|
+
${end(out)}
|
|
59
|
+
`;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Put the block into the content of an instructions file: in place of the
|
|
63
|
+
* block that is there for the same output, or else at the end.
|
|
64
|
+
*/
|
|
65
|
+
export function applyAgentsBlock(existing, block) {
|
|
66
|
+
if (existing === undefined || existing.trim() === "")
|
|
67
|
+
return block;
|
|
68
|
+
const [first] = block.split("\n");
|
|
69
|
+
const last = first.replace("openapi-rq:begin", "openapi-rq:end");
|
|
70
|
+
const from = existing.indexOf(first);
|
|
71
|
+
const to = existing.indexOf(last, from);
|
|
72
|
+
if (from === -1 || to === -1) {
|
|
73
|
+
return `${existing.replace(/\n*$/, "\n\n")}${block}`;
|
|
74
|
+
}
|
|
75
|
+
const after = existing.slice(to + last.length).replace(/^\n/, "");
|
|
76
|
+
return `${existing.slice(0, from)}${block}${after}`;
|
|
77
|
+
}
|
|
78
|
+
async function readIfPresent(file) {
|
|
79
|
+
return existsSync(file) ? readFile(file, "utf8") : undefined;
|
|
80
|
+
}
|
|
81
|
+
/** Write or refresh the block for `output` in `file`. */
|
|
82
|
+
export async function writeAgentsBlock(file, output) {
|
|
83
|
+
const existing = await readIfPresent(file);
|
|
84
|
+
const updated = applyAgentsBlock(existing, renderAgentsBlock(output));
|
|
85
|
+
if (updated !== existing) {
|
|
86
|
+
await writeFile(file, updated);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** What `--check` reports for the block, if it is missing or out of date. */
|
|
90
|
+
export async function checkAgentsBlock(file, output) {
|
|
91
|
+
const existing = await readIfPresent(file);
|
|
92
|
+
const block = renderAgentsBlock(output);
|
|
93
|
+
if (existing?.includes(block))
|
|
94
|
+
return undefined;
|
|
95
|
+
const reported = file.split(path.sep).join("/");
|
|
96
|
+
return {
|
|
97
|
+
path: reported,
|
|
98
|
+
status: existing?.includes(block.split("\n")[0]) ? "modified" : "added",
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Claude Code reads `AGENTS.md` only where there is no `CLAUDE.md`. When the
|
|
103
|
+
* block goes into an `AGENTS.md` next to a `CLAUDE.md` that does not import
|
|
104
|
+
* it, say how to make the block reach Claude Code as well.
|
|
105
|
+
*/
|
|
106
|
+
export async function claudeImportHint(file) {
|
|
107
|
+
if (path.basename(file) !== defaultAgentsFile)
|
|
108
|
+
return undefined;
|
|
109
|
+
const claude = path.join(path.dirname(file), "CLAUDE.md");
|
|
110
|
+
const content = await readIfPresent(claude);
|
|
111
|
+
if (content === undefined || content.includes(defaultAgentsFile)) {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
return `${claude} does not mention ${defaultAgentsFile}, so Claude Code will not read the block. Add a line \`@${defaultAgentsFile}\` to ${claude}, or pass --agentsMd CLAUDE.md.`;
|
|
115
|
+
}
|
package/dist/check.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, statSync } from "node:fs";
|
|
|
2
2
|
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { agentsFilePath, checkAgentsBlock } from "./agentsMd.mjs";
|
|
5
6
|
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
|
|
6
7
|
import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
|
|
7
8
|
import { generate } from "./generate.mjs";
|
|
@@ -128,16 +129,19 @@ export async function createScratchOutput(output) {
|
|
|
128
129
|
async function runCheck(options, version) {
|
|
129
130
|
const { scratchRoot, scratchOutput } = await createScratchOutput(options.output);
|
|
130
131
|
try {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
});
|
|
132
|
+
// The agent guide is not part of the output directory: it is compared
|
|
133
|
+
// below, against the file the real run would write.
|
|
134
|
+
await generate({ ...options, output: scratchOutput, agentsMd: undefined }, version, { silent: true });
|
|
134
135
|
const changesPerDir = await Promise.all(checkedSubdirectories.map((subdirectory) => diffDirectories({
|
|
135
136
|
expectedRoot: path.join(scratchOutput, subdirectory),
|
|
136
137
|
actualRoot: path.join(options.output, subdirectory),
|
|
137
138
|
// Reported paths are cwd-relative even for an absolute output.
|
|
138
139
|
displayRoot: path.relative(process.cwd(), path.resolve(options.output, subdirectory)),
|
|
139
140
|
})));
|
|
140
|
-
const
|
|
141
|
+
const guide = options.agentsMd
|
|
142
|
+
? await checkAgentsBlock(agentsFilePath(options.agentsMd), options.output)
|
|
143
|
+
: undefined;
|
|
144
|
+
const files = [...changesPerDir.flat(), ...(guide ? [guide] : [])].sort(byPath);
|
|
141
145
|
return { upToDate: files.length === 0, files };
|
|
142
146
|
}
|
|
143
147
|
finally {
|
package/dist/cli.d.mts
CHANGED
package/dist/generate.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { agentsFilePath, claudeImportHint, writeAgentsBlock, } from "./agentsMd.mjs";
|
|
1
2
|
import { detectImportExtension, findNearestTsConfigPath, generateClient, SpecError, writeGeneratedFiles, } from "./client/index.mjs";
|
|
2
3
|
import { buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, } from "./common.mjs";
|
|
3
4
|
import { createSource } from "./createSource.mjs";
|
|
@@ -88,6 +89,13 @@ async function runGenerate(options, version, runtime) {
|
|
|
88
89
|
format: formattedOptions.format,
|
|
89
90
|
lint: formattedOptions.lint,
|
|
90
91
|
});
|
|
92
|
+
if (options.agentsMd) {
|
|
93
|
+
const file = agentsFilePath(options.agentsMd);
|
|
94
|
+
await writeAgentsBlock(file, options.output);
|
|
95
|
+
const hint = runtime.silent ? undefined : await claudeImportHint(file);
|
|
96
|
+
if (hint)
|
|
97
|
+
console.warn(hint);
|
|
98
|
+
}
|
|
91
99
|
}
|
|
92
100
|
/**
|
|
93
101
|
* Generate the client and the React Query hooks into `options.output`.
|
package/dist/runCli.mjs
CHANGED
|
@@ -45,6 +45,7 @@ export function buildProgram(version, io, { json }) {
|
|
|
45
45
|
.option("--nextPageParam <value>", "Name of the response parameter used for next page", "nextPage")
|
|
46
46
|
.option("--initialPageParam <value>", "Initial page value to query", "1")
|
|
47
47
|
.option("--omitInitialPageParam", "Send no initial page parameter at all (overrides --initialPageParam)")
|
|
48
|
+
.option("--agentsMd [file]", "Also keep a short guide for coding agents (how to look operations up in the output) in AGENTS.md, or in the file named")
|
|
48
49
|
.option("--check", "Do not update the output; exit 1 and list the files that differ if the existing output is out of date")
|
|
49
50
|
.option("--json", "Print errors to stderr as a single line of JSON ({ code, message, details })");
|
|
50
51
|
}
|