@7nohe/openapi-react-query-codegen 3.2.1 → 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 +22 -19
- package/README.md +3 -3
- package/dist/cli.d.mts +6 -1
- 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/format.mjs +0 -1
- package/dist/generate.d.mts +9 -9
- package/dist/generate.mjs +45 -107
- package/dist/runCli.mjs +7 -2
- 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 +6 -6
- 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
CHANGED
|
@@ -9,7 +9,7 @@ This file has two parts:
|
|
|
9
9
|
|
|
10
10
|
`@7nohe/openapi-react-query-codegen` is a CLI (`openapi-rq`) that reads an OpenAPI spec and generates:
|
|
11
11
|
|
|
12
|
-
1. a TypeScript HTTP client (
|
|
12
|
+
1. a TypeScript HTTP client (types, one function per operation and a small fetch or axios runtime) in `<output>/requests/`
|
|
13
13
|
2. TanStack Query v5 hooks and helpers on top of that client in `<output>/queries/`
|
|
14
14
|
|
|
15
15
|
Docs: https://openapi-react-query-codegen.vercel.app (summary for LLMs: https://openapi-react-query-codegen.vercel.app/llms.txt)
|
|
@@ -21,7 +21,7 @@ npm install -D @7nohe/openapi-react-query-codegen
|
|
|
21
21
|
npm install @tanstack/react-query
|
|
22
22
|
```
|
|
23
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
|
|
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
25
|
|
|
26
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
27
|
|
|
@@ -35,15 +35,15 @@ Add a script and run it whenever the spec changes:
|
|
|
35
35
|
|
|
36
36
|
| Flag | Default | Notes |
|
|
37
37
|
| --- | --- | --- |
|
|
38
|
-
| `-i, --input <path\|url\|content>` | (required) | OpenAPI
|
|
38
|
+
| `-i, --input <path\|url\|content>` | (required) | OpenAPI 3.0/3.1 spec |
|
|
39
39
|
| `-o, --output <dir>` | `openapi` | `requests/` and `queries/` are created inside |
|
|
40
|
-
| `-c, --client <name>` |
|
|
40
|
+
| `-c, --client <name>` | `fetch` | or `axios` |
|
|
41
41
|
| `--format <biome\|prettier>` | none | formats `queries/` only |
|
|
42
42
|
| `--lint <biome\|eslint>` | none | lints/fixes `queries/` only |
|
|
43
43
|
| `--enums <javascript\|typescript>` | none | emit enum objects |
|
|
44
|
-
| `--useDateType` | off | `Date` for `date`/`date-time`, converted
|
|
44
|
+
| `--useDateType` | off | `Date` for `date`/`date-time`, converted in successful responses |
|
|
45
45
|
| `--noOperationId` | off | derive names from paths instead of `operationId` |
|
|
46
|
-
| `--noSchemas` / `--schemaType <json\|form>` | schemas on, `json` | JSON schema export |
|
|
46
|
+
| `--noSchemas` / `--schemaType <json\|form>` | schemas on, `json` | JSON schema export (`requests/schemas.gen.ts`) |
|
|
47
47
|
| `--pageParam <name>` | `page` | query param that turns a GET into an infinite query |
|
|
48
48
|
| `--nextPageParam <path>` | `nextPage` | response field holding the next page (dot path allowed, e.g. `meta.next`) |
|
|
49
49
|
| `--initialPageParam <value>` / `--omitInitialPageParam` | `1` | first page value, or send none |
|
|
@@ -65,11 +65,14 @@ Pass the **same flags** every time (keep them in the package.json script). Diffe
|
|
|
65
65
|
│ ├── infiniteQueries.ts# useInfiniteQuery hooks
|
|
66
66
|
│ ├── prefetch.ts # prefetchQuery helpers
|
|
67
67
|
│ └── ensureQueryData.ts# ensureQueryData helpers
|
|
68
|
-
└── requests/ # HTTP client
|
|
68
|
+
└── requests/ # HTTP client (generated by this package too)
|
|
69
69
|
├── client.gen.ts # `client` instance (setConfig, interceptors)
|
|
70
|
+
├── runtime.gen.ts # the fetch or axios runtime the client runs on
|
|
70
71
|
├── sdk.gen.ts # one function per operation
|
|
71
72
|
├── services.gen.ts # compatibility shim: re-exports client.gen + sdk.gen
|
|
72
|
-
|
|
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)
|
|
73
76
|
```
|
|
74
77
|
|
|
75
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.
|
|
@@ -133,7 +136,7 @@ The `queries/` headers include the package version, so after upgrading this pack
|
|
|
133
136
|
| `1` | `--check` found differences |
|
|
134
137
|
| `2` | error (bad flags, unreadable spec, generation failure) |
|
|
135
138
|
|
|
136
|
-
With `--json`, a failure prints exactly one line of JSON on stderr, and
|
|
139
|
+
With `--json`, a failure prints exactly one line of JSON on stderr, and nothing else is written there:
|
|
137
140
|
|
|
138
141
|
```json
|
|
139
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"}]}}
|
|
@@ -142,9 +145,9 @@ With `--json`, a failure prints exactly one line of JSON on stderr, and @hey-api
|
|
|
142
145
|
| `code` | When | `details` |
|
|
143
146
|
| --- | --- | --- |
|
|
144
147
|
| `INVALID_ARGUMENT` | unknown flag, bad choice, missing `-i` | `commanderCode` |
|
|
145
|
-
| `INPUT_NOT_FOUND` | spec file missing or URL request failed | `input` |
|
|
148
|
+
| `INPUT_NOT_FOUND` | spec file missing or URL request failed | `input`, `reason` |
|
|
146
149
|
| `INPUT_PARSE_ERROR` | spec is not valid YAML/JSON | `input`, `reason` |
|
|
147
|
-
| `CLIENT_GENERATION_FAILED` |
|
|
150
|
+
| `CLIENT_GENERATION_FAILED` | the client could not be generated otherwise (an OpenAPI 2.0 spec, an unresolvable `$ref`) | `input`, `reason`, `name` |
|
|
148
151
|
| `GENERATION_FAILED` | hook generation failed | `name` |
|
|
149
152
|
| `OUTPUT_OUT_OF_DATE` | `--check` found differences (exit 1) | `files: [{ path, status }]` |
|
|
150
153
|
|
|
@@ -189,15 +192,15 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
|
|
|
189
192
|
- Commits: clear, descriptive messages (e.g., `fix: align imports for generated queries`, `chore: update ts-morph config`). Avoid bundling unrelated changes.
|
|
190
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.
|
|
191
194
|
|
|
192
|
-
### Architecture: IR Boundary
|
|
193
|
-
-
|
|
194
|
-
-
|
|
195
|
-
- Generation-side modules (`src/tsmorph/build*.mts`, `generateFiles.mts`)
|
|
196
|
-
-
|
|
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.
|
|
197
201
|
|
|
198
|
-
###
|
|
199
|
-
-
|
|
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.
|
|
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.
|
|
201
204
|
|
|
202
205
|
### Agent-Specific Notes
|
|
203
206
|
- Use AST-aware paths (ts-morph/TypeScript factory) when editing generators to keep output structurally valid.
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
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
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
|
|
17
17
|
|
|
18
18
|
## Quick start
|
|
@@ -49,13 +49,13 @@ See the [documentation](https://openapi-react-query-codegen.vercel.app) for CLI
|
|
|
49
49
|
| MSW mock generation | ❌ (out of scope) | ❌ | ✅ | ❌ |
|
|
50
50
|
| Vue / Solid / Svelte / Angular | ❌ React-focused | ✅ | ✅ | ❌ |
|
|
51
51
|
|
|
52
|
-
**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.
|
|
53
53
|
|
|
54
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/).
|
|
55
55
|
|
|
56
56
|
## Stability policy
|
|
57
57
|
|
|
58
|
-
|
|
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`).
|
|
59
59
|
|
|
60
60
|
## Requirements
|
|
61
61
|
|
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;
|
|
@@ -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;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { HEADER } from "./emitSdk.mjs";
|
|
2
|
+
import { propertyKey, uniqueName } from "./naming.mjs";
|
|
3
|
+
import { componentSchemaKey, hasFlag } from "./schema.mjs";
|
|
4
|
+
const DOCUMENTATION_KEYWORDS = [
|
|
5
|
+
"description",
|
|
6
|
+
"title",
|
|
7
|
+
"x-enum-descriptions",
|
|
8
|
+
"x-enum-varnames",
|
|
9
|
+
"x-enumNames",
|
|
10
|
+
];
|
|
11
|
+
/** The keywords that hold one schema, a list of them, or a map of them. */
|
|
12
|
+
const SCHEMA_KEYWORDS = ["additionalProperties", "items", "not"];
|
|
13
|
+
const SCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems"];
|
|
14
|
+
const SCHEMA_MAP_KEYWORDS = ["patternProperties", "properties"];
|
|
15
|
+
/**
|
|
16
|
+
* Copy a schema for one side of the API: without the properties the other side
|
|
17
|
+
* owns, and with its references pointing at that side's schemas.
|
|
18
|
+
*/
|
|
19
|
+
function project(schema, ctx, variant) {
|
|
20
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
21
|
+
return schema;
|
|
22
|
+
}
|
|
23
|
+
const entries = [];
|
|
24
|
+
const removed = new Set();
|
|
25
|
+
for (const [keyword, value] of Object.entries(schema)) {
|
|
26
|
+
if (variant.mode === "form" && DOCUMENTATION_KEYWORDS.includes(keyword)) {
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (keyword === "$ref" && typeof value === "string") {
|
|
30
|
+
const key = componentSchemaKey(value);
|
|
31
|
+
const renamed = key === undefined ? undefined : variant.renamed.get(key);
|
|
32
|
+
entries.push([
|
|
33
|
+
keyword,
|
|
34
|
+
renamed === undefined ? value : `#/components/schemas/${renamed}`,
|
|
35
|
+
]);
|
|
36
|
+
}
|
|
37
|
+
else if (SCHEMA_KEYWORDS.includes(keyword)) {
|
|
38
|
+
entries.push([keyword, project(value, ctx, variant)]);
|
|
39
|
+
}
|
|
40
|
+
else if (SCHEMA_LIST_KEYWORDS.includes(keyword) && Array.isArray(value)) {
|
|
41
|
+
entries.push([
|
|
42
|
+
keyword,
|
|
43
|
+
value.map((member) => project(member, ctx, variant)),
|
|
44
|
+
]);
|
|
45
|
+
}
|
|
46
|
+
else if (SCHEMA_MAP_KEYWORDS.includes(keyword) &&
|
|
47
|
+
value &&
|
|
48
|
+
typeof value === "object" &&
|
|
49
|
+
!Array.isArray(value)) {
|
|
50
|
+
const members = [];
|
|
51
|
+
for (const [name, member] of Object.entries(value)) {
|
|
52
|
+
if (keyword === "properties" &&
|
|
53
|
+
hasFlag(ctx.doc, member, variant.hidden)) {
|
|
54
|
+
removed.add(name);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
members.push([name, project(member, ctx, variant)]);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
entries.push([keyword, Object.fromEntries(members)]);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
entries.push([keyword, value]);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return Object.fromEntries(entries.flatMap(([keyword, value]) => {
|
|
67
|
+
if (keyword !== "required" || removed.size === 0) {
|
|
68
|
+
return [[keyword, value]];
|
|
69
|
+
}
|
|
70
|
+
if (!Array.isArray(value))
|
|
71
|
+
return [[keyword, value]];
|
|
72
|
+
const required = value.filter((name) => !removed.has(name));
|
|
73
|
+
return required.length > 0 ? [[keyword, required]] : [];
|
|
74
|
+
}));
|
|
75
|
+
}
|
|
76
|
+
function literal(value, indent = "") {
|
|
77
|
+
if (value === null || typeof value !== "object") {
|
|
78
|
+
return typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
79
|
+
}
|
|
80
|
+
const inner = `${indent} `;
|
|
81
|
+
if (Array.isArray(value)) {
|
|
82
|
+
if (value.length === 0)
|
|
83
|
+
return "[]";
|
|
84
|
+
const items = value.map((item) => `${inner}${literal(item, inner)},`);
|
|
85
|
+
return `[\n${items.join("\n")}\n${indent}]`;
|
|
86
|
+
}
|
|
87
|
+
const entries = Object.entries(value).filter(([, item]) => item !== undefined);
|
|
88
|
+
if (entries.length === 0)
|
|
89
|
+
return "{}";
|
|
90
|
+
const lines = entries.map(([name, item]) => `${inner}${propertyKey(name)}: ${literal(item, inner)},`);
|
|
91
|
+
return `{\n${lines.join("\n")}\n${indent}}`;
|
|
92
|
+
}
|
|
93
|
+
/** `my-schema` → `my_schema`, as v3 named the constants. */
|
|
94
|
+
function constantName(schemaKey) {
|
|
95
|
+
const name = schemaKey.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
96
|
+
return /^\d/.test(name) ? `_${name}` : name;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Generate `schemas.gen.ts`: every component schema as a constant, the way the
|
|
100
|
+
* specification writes it. A schema with `readOnly` or `writeOnly` properties
|
|
101
|
+
* comes in two: what the API returns, and `…WritableSchema` for what it takes.
|
|
102
|
+
*/
|
|
103
|
+
export function emitSchemas(ctx, mode) {
|
|
104
|
+
const schemas = (ctx.doc.components?.schemas ?? {});
|
|
105
|
+
const keys = Object.keys(schemas);
|
|
106
|
+
if (keys.length === 0)
|
|
107
|
+
return undefined;
|
|
108
|
+
const used = new Set();
|
|
109
|
+
const blocks = [];
|
|
110
|
+
const add = (name, schema, variant) => {
|
|
111
|
+
blocks.push(`export const ${uniqueName(name, used)} = ${literal(project(schema, ctx, variant))} as const;`);
|
|
112
|
+
};
|
|
113
|
+
for (const schemaKey of keys) {
|
|
114
|
+
add(`${constantName(schemaKey)}Schema`, schemas[schemaKey], {
|
|
115
|
+
hidden: "writeOnly",
|
|
116
|
+
renamed: new Map(),
|
|
117
|
+
mode,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const writable = keys.filter((schemaKey) => ctx.writableNames?.has(schemaKey));
|
|
121
|
+
const renamed = new Map(writable.map((schemaKey) => [schemaKey, `${schemaKey}Writable`]));
|
|
122
|
+
for (const schemaKey of writable) {
|
|
123
|
+
add(`${constantName(schemaKey)}WritableSchema`, schemas[schemaKey], {
|
|
124
|
+
hidden: "readOnly",
|
|
125
|
+
renamed,
|
|
126
|
+
mode,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return `${HEADER}\n${blocks.join("\n\n")}\n`;
|
|
130
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type OperationIR } from "./operations.mjs";
|
|
2
|
+
import { type Doc } from "./spec.mjs";
|
|
3
|
+
export type ClientKind = "fetch" | "axios";
|
|
4
|
+
export declare const HEADER = "// This file is auto-generated by @7nohe/openapi-react-query-codegen\n";
|
|
5
|
+
export declare function optionsAreOptional(operation: OperationIR): boolean;
|
|
6
|
+
export declare function emitSdk(doc: Doc, operations: OperationIR[], options: {
|
|
7
|
+
kind: ClientKind;
|
|
8
|
+
ext: string;
|
|
9
|
+
/** SDK function name → response transformer from `transformers.gen.ts`. */
|
|
10
|
+
transformers?: ReadonlyMap<string, string>;
|
|
11
|
+
}): string;
|
|
12
|
+
export declare function emitClientFile(options: {
|
|
13
|
+
kind: ClientKind;
|
|
14
|
+
ext: string;
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
}): string;
|
|
17
|
+
export declare function emitIndexFile(ext: string): string;
|
|
18
|
+
export declare function emitServicesShim(ext: string): string;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { classifyResponses, mediaKind, } from "./operations.mjs";
|
|
2
|
+
import { docComment } from "./schema.mjs";
|
|
3
|
+
import { resolveRef } from "./spec.mjs";
|
|
4
|
+
export const HEADER = "// This file is auto-generated by @7nohe/openapi-react-query-codegen\n";
|
|
5
|
+
const CONTENT_TYPE_BY_KIND = {
|
|
6
|
+
urlencoded: "application/x-www-form-urlencoded",
|
|
7
|
+
};
|
|
8
|
+
function q(value) {
|
|
9
|
+
return JSON.stringify(value);
|
|
10
|
+
}
|
|
11
|
+
function schemaType(doc, schema) {
|
|
12
|
+
const resolved = resolveRef(doc, schema);
|
|
13
|
+
if (!resolved || typeof resolved !== "object")
|
|
14
|
+
return undefined;
|
|
15
|
+
if (Array.isArray(resolved.type)) {
|
|
16
|
+
const types = resolved.type.filter((item) => item !== "null");
|
|
17
|
+
// Alternatives of different shapes have no one type to go by.
|
|
18
|
+
return types.length > 1 && !types.every((item) => PRIMITIVE_TYPES.has(item))
|
|
19
|
+
? undefined
|
|
20
|
+
: types[0];
|
|
21
|
+
}
|
|
22
|
+
if (resolved.type)
|
|
23
|
+
return resolved.type;
|
|
24
|
+
if (resolved.properties)
|
|
25
|
+
return "object";
|
|
26
|
+
if (resolved.items)
|
|
27
|
+
return "array";
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const PRIMITIVE_TYPES = new Set(["boolean", "integer", "number", "string"]);
|
|
31
|
+
/**
|
|
32
|
+
* Query parameters the runtime defaults would serialize differently from the
|
|
33
|
+
* OpenAPI ones. The runtime leaves arrays in `form` style with `explode`, and
|
|
34
|
+
* objects in `deepObject` style, so only the rest is spelled out. OpenAPI
|
|
35
|
+
* defaults a query parameter to `form`, and `explode` to true for `form` only.
|
|
36
|
+
*/
|
|
37
|
+
function querySerializerEntries(doc, parameters) {
|
|
38
|
+
const entries = [];
|
|
39
|
+
for (const parameter of parameters) {
|
|
40
|
+
if (parameter.in !== "query")
|
|
41
|
+
continue;
|
|
42
|
+
if (parameter.json) {
|
|
43
|
+
entries.push(`${q(parameter.name)}: { json: true }`);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const type = schemaType(doc, parameter.schema);
|
|
47
|
+
if (type !== undefined && PRIMITIVE_TYPES.has(type))
|
|
48
|
+
continue;
|
|
49
|
+
const style = parameter.style ?? "form";
|
|
50
|
+
const explode = parameter.explode ?? style === "form";
|
|
51
|
+
if (style === "deepObject")
|
|
52
|
+
continue;
|
|
53
|
+
// A schema without a plain type (`anyOf`, say) can hold either shape.
|
|
54
|
+
const settings = [];
|
|
55
|
+
if (type !== "object" && !(style === "form" && explode)) {
|
|
56
|
+
settings.push(`array: { style: ${q(style)}, explode: ${explode} }`);
|
|
57
|
+
}
|
|
58
|
+
if (type !== "array") {
|
|
59
|
+
settings.push(`object: { style: "form", explode: ${explode} }`);
|
|
60
|
+
}
|
|
61
|
+
if (settings.length > 0) {
|
|
62
|
+
entries.push(`${q(parameter.name)}: { ${settings.join(", ")} }`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return entries;
|
|
66
|
+
}
|
|
67
|
+
/** Path parameters that are not in the default `simple` style. */
|
|
68
|
+
function pathSerializerEntries(doc, parameters) {
|
|
69
|
+
const entries = [];
|
|
70
|
+
for (const parameter of parameters) {
|
|
71
|
+
if (parameter.in !== "path")
|
|
72
|
+
continue;
|
|
73
|
+
if (parameter.json) {
|
|
74
|
+
entries.push(`${q(parameter.name)}: { json: true }`);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const style = parameter.style === "label" || parameter.style === "matrix"
|
|
78
|
+
? parameter.style
|
|
79
|
+
: "simple";
|
|
80
|
+
const explode = parameter.explode ?? false;
|
|
81
|
+
if (style === "simple") {
|
|
82
|
+
// `explode` only changes how an object is written.
|
|
83
|
+
const type = schemaType(doc, parameter.schema);
|
|
84
|
+
if (!explode || type === "array" || PRIMITIVE_TYPES.has(type ?? "")) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
entries.push(`${q(parameter.name)}: { style: ${q(style)}, explode: ${explode} }`);
|
|
89
|
+
}
|
|
90
|
+
return entries;
|
|
91
|
+
}
|
|
92
|
+
function securityLiteral(security) {
|
|
93
|
+
const key = security.key ? `key: ${q(security.key)}, ` : "";
|
|
94
|
+
if (security.type === "apiKey") {
|
|
95
|
+
return `{ in: ${q(security.in ?? "header")}, ${key}name: ${q(security.name ?? "")}, type: "apiKey" }`;
|
|
96
|
+
}
|
|
97
|
+
const scheme = security.scheme === "basic" ? "basic" : "bearer";
|
|
98
|
+
return `{ ${key}scheme: ${q(scheme)}, type: "http" }`;
|
|
99
|
+
}
|
|
100
|
+
/** One alternative: a scheme, or the array of schemes it needs together. */
|
|
101
|
+
function securityRequirementLiteral(requirement) {
|
|
102
|
+
const literals = requirement.map(securityLiteral);
|
|
103
|
+
return literals.length === 1 ? literals[0] : `[${literals.join(", ")}]`;
|
|
104
|
+
}
|
|
105
|
+
function parseKind(mediaType) {
|
|
106
|
+
const kind = mediaKind(mediaType);
|
|
107
|
+
if (kind === "json" || kind === "text")
|
|
108
|
+
return kind;
|
|
109
|
+
if (kind === "form-data")
|
|
110
|
+
return "formData";
|
|
111
|
+
// Readable documents, the same as the runtime when it detects the type.
|
|
112
|
+
const type = mediaType.toLowerCase().split(";")[0].trim();
|
|
113
|
+
return type === "application/xml" || type.endsWith("+xml") ? "text" : "blob";
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* How to read a successful response, when every body the operation can answer
|
|
117
|
+
* with is read the same way. With a mix (`200` JSON and `202` text, say) the
|
|
118
|
+
* runtime has to look at the response itself.
|
|
119
|
+
*/
|
|
120
|
+
function parseAsFor(operation) {
|
|
121
|
+
const kinds = new Set(operation.responses
|
|
122
|
+
.filter((response) => /^2/.test(response.status))
|
|
123
|
+
.flatMap((response) => response.mediaTypes.map(parseKind)));
|
|
124
|
+
return kinds.size === 1 ? [...kinds][0] : undefined;
|
|
125
|
+
}
|
|
126
|
+
export function optionsAreOptional(operation) {
|
|
127
|
+
if (operation.body?.required)
|
|
128
|
+
return false;
|
|
129
|
+
return !operation.parameters.some((parameter) => parameter.required);
|
|
130
|
+
}
|
|
131
|
+
function emitOperation(operation, doc, kind, transformer) {
|
|
132
|
+
const names = operation.typeNames;
|
|
133
|
+
const { responses, errors } = classifyResponses(operation);
|
|
134
|
+
const dataType = names.data;
|
|
135
|
+
const responsesType = responses.length > 0 ? names.responses : "unknown";
|
|
136
|
+
const errorsType = errors.length > 0 ? names.errors : "unknown";
|
|
137
|
+
const usedTypes = [dataType];
|
|
138
|
+
if (responses.length > 0)
|
|
139
|
+
usedTypes.push(responsesType);
|
|
140
|
+
if (errors.length > 0)
|
|
141
|
+
usedTypes.push(errorsType);
|
|
142
|
+
const optional = optionsAreOptional(operation);
|
|
143
|
+
const access = optional ? "options?" : "options";
|
|
144
|
+
const lines = [];
|
|
145
|
+
if (transformer)
|
|
146
|
+
lines.push(`responseTransformer: ${transformer}`);
|
|
147
|
+
// Axios has to know before the response arrives. The fetch runtime follows
|
|
148
|
+
// the response's own Content-Type, or what the client is configured to do.
|
|
149
|
+
const parseAs = kind === "axios" ? parseAsFor(operation) : undefined;
|
|
150
|
+
if (parseAs) {
|
|
151
|
+
lines.push(`responseType: ${q(parseAs === "formData" ? "json" : parseAs)}`);
|
|
152
|
+
}
|
|
153
|
+
const security = operation.security.map(securityRequirementLiteral);
|
|
154
|
+
if (security.length > 0)
|
|
155
|
+
lines.push(`security: [${security.join(", ")}]`);
|
|
156
|
+
const queryEntries = querySerializerEntries(doc, operation.parameters);
|
|
157
|
+
if (queryEntries.length > 0) {
|
|
158
|
+
lines.push(`querySerializer: { parameters: { ${queryEntries.join(", ")} } }`);
|
|
159
|
+
}
|
|
160
|
+
const pathEntries = pathSerializerEntries(doc, operation.parameters);
|
|
161
|
+
if (pathEntries.length > 0) {
|
|
162
|
+
lines.push(`pathSerializer: { parameters: { ${pathEntries.join(", ")} } }`);
|
|
163
|
+
}
|
|
164
|
+
const jsonHeaders = operation.parameters
|
|
165
|
+
.filter((parameter) => parameter.in === "header" && parameter.json)
|
|
166
|
+
.map((parameter) => q(parameter.name));
|
|
167
|
+
if (jsonHeaders.length > 0) {
|
|
168
|
+
lines.push(`jsonHeaders: [${jsonHeaders.join(", ")}]`);
|
|
169
|
+
}
|
|
170
|
+
lines.push(`url: ${q(operation.path)}`);
|
|
171
|
+
const bodyKind = operation.body?.kind;
|
|
172
|
+
if (bodyKind === "json" ||
|
|
173
|
+
bodyKind === "form-data" ||
|
|
174
|
+
bodyKind === "urlencoded") {
|
|
175
|
+
lines.push(`bodyType: ${q(bodyKind)}`);
|
|
176
|
+
}
|
|
177
|
+
lines.push("...options");
|
|
178
|
+
if (operation.body) {
|
|
179
|
+
// Multipart clears any configured value: the boundary has to come from the
|
|
180
|
+
// platform, which only adds the header when there is none.
|
|
181
|
+
const contentType = bodyKind === "form-data"
|
|
182
|
+
? "null"
|
|
183
|
+
: q(CONTENT_TYPE_BY_KIND[operation.body.kind] ??
|
|
184
|
+
operation.body.mediaType);
|
|
185
|
+
lines.push(`headers: {\n "Content-Type": ${contentType},\n ...${access}.headers\n }`);
|
|
186
|
+
}
|
|
187
|
+
const body = lines
|
|
188
|
+
.map((line, index) => ` ${line}${index < lines.length - 1 ? "," : ""}`)
|
|
189
|
+
.join("\n");
|
|
190
|
+
const doc2 = operation.jsDoc ? `${operation.jsDoc}\n` : "";
|
|
191
|
+
const generics = `<${responsesType}, ${errorsType}, ThrowOnError>`;
|
|
192
|
+
const code = `${doc2}export const ${operation.functionName} = <ThrowOnError extends boolean = false>(${optional ? "options?" : "options"}: Options<${dataType}, ThrowOnError>): RequestResult<${responsesType}, ${errorsType}, ThrowOnError> => (${access}.client ?? client).${operation.method}${generics}({\n${body}\n});`;
|
|
193
|
+
return { code, usedTypes };
|
|
194
|
+
}
|
|
195
|
+
export function emitSdk(doc, operations, options) {
|
|
196
|
+
const used = new Set();
|
|
197
|
+
const blocks = [];
|
|
198
|
+
for (const operation of operations) {
|
|
199
|
+
const { code, usedTypes } = emitOperation(operation, doc, options.kind, options.transformers?.get(operation.functionName));
|
|
200
|
+
for (const type of usedTypes)
|
|
201
|
+
used.add(type);
|
|
202
|
+
blocks.push(code);
|
|
203
|
+
}
|
|
204
|
+
const typeImports = [...used].sort().join(", ");
|
|
205
|
+
const imports = [
|
|
206
|
+
`import { client } from "./client.gen${options.ext}";`,
|
|
207
|
+
`import type { Client, Options as Options2, RequestResult, TDataShape } from "./runtime.gen${options.ext}";`,
|
|
208
|
+
];
|
|
209
|
+
const transformers = [...(options.transformers?.values() ?? [])].sort();
|
|
210
|
+
if (transformers.length > 0) {
|
|
211
|
+
imports.push(`import { ${transformers.join(", ")} } from "./transformers.gen${options.ext}";`);
|
|
212
|
+
}
|
|
213
|
+
if (typeImports) {
|
|
214
|
+
imports.push(`import type { ${typeImports} } from "./types.gen${options.ext}";`);
|
|
215
|
+
}
|
|
216
|
+
const optionsType = `export type Options<
|
|
217
|
+
TData extends TDataShape = TDataShape,
|
|
218
|
+
ThrowOnError extends boolean = boolean,
|
|
219
|
+
> = Options2<TData, ThrowOnError> & {
|
|
220
|
+
${docComment({ description: "You can provide a client instance returned by `createClient()` instead of\nindividual options. This might be also useful if you want to implement a\ncustom client." }, " ")} client?: Client;
|
|
221
|
+
${docComment({ description: "You can pass arbitrary values through the `meta` object. This can be\nused to access values that aren't defined as part of the SDK function." }, " ")} meta?: Record<string, unknown>;
|
|
222
|
+
};`;
|
|
223
|
+
return `${HEADER}\n${imports.join("\n")}\n\n${optionsType}\n\n${blocks.join("\n\n")}\n`;
|
|
224
|
+
}
|
|
225
|
+
export function emitClientFile(options) {
|
|
226
|
+
const baseUrlKey = options.kind === "axios" ? "baseURL" : "baseUrl";
|
|
227
|
+
const config = options.baseUrl
|
|
228
|
+
? `{ ${baseUrlKey}: ${q(options.baseUrl)} }`
|
|
229
|
+
: "";
|
|
230
|
+
return `${HEADER}
|
|
231
|
+
import {
|
|
232
|
+
type ClientOptions,
|
|
233
|
+
type Config,
|
|
234
|
+
createClient,
|
|
235
|
+
createConfig,
|
|
236
|
+
} from "./runtime.gen${options.ext}";
|
|
237
|
+
import type { ClientOptions as ClientOptions2 } from "./types.gen${options.ext}";
|
|
238
|
+
|
|
239
|
+
${docComment({
|
|
240
|
+
description: "The `createClientConfig()` function will be called on client initialization\nand the returned object will become the client's initial configuration.\n\nYou may want to initialize your client this way instead of calling\n`setConfig()`. This is useful for example if you're using Next.js\nto ensure your client always has the correct values.",
|
|
241
|
+
})}export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (
|
|
242
|
+
override?: Config<ClientOptions & T>,
|
|
243
|
+
) => Config<Required<ClientOptions> & T>;
|
|
244
|
+
|
|
245
|
+
export const client = createClient(createConfig<ClientOptions2>(${config}));
|
|
246
|
+
`;
|
|
247
|
+
}
|
|
248
|
+
export function emitIndexFile(ext) {
|
|
249
|
+
return `${HEADER}\nexport * from "./sdk.gen${ext}";\nexport * from "./types.gen${ext}";\n`;
|
|
250
|
+
}
|
|
251
|
+
export function emitServicesShim(ext) {
|
|
252
|
+
return `// This file is auto-generated for backward compatibility\nexport * from "./client.gen${ext}";\nexport * from "./sdk.gen${ext}";\n`;
|
|
253
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type OperationIR } from "./operations.mjs";
|
|
2
|
+
import { type SchemaCtx } from "./schema.mjs";
|
|
3
|
+
export type EmittedTransformers = {
|
|
4
|
+
/** The file, or undefined when no response holds a date. */
|
|
5
|
+
content: string | undefined;
|
|
6
|
+
/** SDK function name → name of its exported response transformer. */
|
|
7
|
+
byOperation: Map<string, string>;
|
|
8
|
+
/**
|
|
9
|
+
* Unions whose members cannot be told apart at runtime. Their dates stay
|
|
10
|
+
* strings although the types say `Date`.
|
|
11
|
+
*/
|
|
12
|
+
skipped: string[];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Generate `transformers.gen.ts` for `--useDateType`: a function per operation
|
|
16
|
+
* that turns the `date` and `date-time` strings of its successful response
|
|
17
|
+
* into `Date` objects, as the generated types say they are.
|
|
18
|
+
*/
|
|
19
|
+
export declare function emitTransformers(operations: OperationIR[], ctx: SchemaCtx): EmittedTransformers;
|