@7nohe/openapi-react-query-codegen 4.0.0-beta.4 → 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.
Files changed (51) hide show
  1. package/AGENTS.md +23 -1
  2. package/README.md +5 -2
  3. package/dist/agentsMd.d.mts +30 -0
  4. package/dist/agentsMd.mjs +115 -0
  5. package/dist/check.mjs +8 -4
  6. package/dist/cli.d.mts +2 -0
  7. package/dist/client/emitSchemas.mjs +12 -9
  8. package/dist/client/emitSdk.d.mts +2 -0
  9. package/dist/client/emitSdk.mjs +24 -27
  10. package/dist/client/emitTransformers.mjs +21 -72
  11. package/dist/client/emitTypes.d.mts +2 -1
  12. package/dist/client/emitTypes.mjs +5 -5
  13. package/dist/client/index.mjs +13 -5
  14. package/dist/client/naming.d.mts +5 -2
  15. package/dist/client/naming.mjs +7 -3
  16. package/dist/client/operations.d.mts +3 -2
  17. package/dist/client/operations.mjs +10 -47
  18. package/dist/client/runtime/axios.runtime.ts +15 -10
  19. package/dist/client/schema.d.mts +24 -2
  20. package/dist/client/schema.mjs +135 -33
  21. package/dist/client/spec.d.mts +6 -0
  22. package/dist/client/spec.mjs +15 -5
  23. package/dist/common.d.mts +0 -2
  24. package/dist/common.mjs +0 -10
  25. package/dist/createSource.d.mts +1 -1
  26. package/dist/createSource.mjs +1 -3
  27. package/dist/generate.mjs +9 -2
  28. package/dist/hooks/buildCommon.d.mts +12 -16
  29. package/dist/hooks/buildCommon.mjs +25 -35
  30. package/dist/hooks/buildMutationHooks.d.mts +3 -2
  31. package/dist/hooks/buildMutationHooks.mjs +6 -11
  32. package/dist/hooks/buildQueryHooks.d.mts +21 -15
  33. package/dist/hooks/buildQueryHooks.mjs +35 -69
  34. package/dist/hooks/buildQueryOptions.d.mts +4 -3
  35. package/dist/hooks/buildQueryOptions.mjs +9 -22
  36. package/dist/hooks/generateFiles.mjs +54 -81
  37. package/dist/hooks/hookNames.d.mts +69 -0
  38. package/dist/hooks/hookNames.mjs +82 -0
  39. package/dist/hooks/imports.d.mts +27 -52
  40. package/dist/hooks/imports.mjs +82 -164
  41. package/dist/hooks/operationNames.d.mts +10 -0
  42. package/dist/hooks/operationNames.mjs +22 -0
  43. package/dist/hooks/statement.d.mts +15 -6
  44. package/dist/hooks/statement.mjs +19 -14
  45. package/dist/runCli.mjs +1 -0
  46. package/dist/types.d.mts +5 -7
  47. package/package.json +1 -1
  48. package/dist/hooks/index.d.mts +0 -4
  49. package/dist/hooks/index.mjs +0 -4
  50. package/dist/print.d.mts +0 -5
  51. package/dist/print.mjs +0 -22
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
 
@@ -93,6 +96,8 @@ Names come from the operation ID (or from the path with `--noOperationId`). For
93
96
  | `useFindPetsKey`, `UseFindPetsKeyFn(clientOptions?)` | `common.ts` | `invalidateQueries` with the same key the hook uses |
94
97
  | `useAddPet(mutationKey?, options?)` | `queries.ts` | `useMutation`; `mutate({ body, path, query })` |
95
98
 
99
+ A name in this table that is already taken where it would be declared gets a number, and the name from the spec stays as it is: with the operations `getUser` and `getUserOptions`, the factory of `getUser` is `getUserOptions2` (`getUserOptions` is the SDK function), and with `getApi` and `getApiKey`, `useGetApiKey` is the hook of `getApiKey` and the key of `getApi` is `useGetApiKey2`.
100
+
96
101
  `clientOptions` is the SDK options object: `{ path, query, body, headers }`, typed from `requests/types.gen.ts`. Mutation results are the full SDK response (`data`, plus `response` for fetch or `headers` for axios).
97
102
 
98
103
  ```tsx
@@ -118,6 +123,21 @@ mutate({ body: { name: "Fluffy" } });
118
123
 
119
124
  Wrap the app in TanStack Query's `QueryClientProvider` as usual.
120
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
+
121
141
  ### CI drift check: `--check`
122
142
 
123
143
  ```bash
@@ -196,6 +216,8 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
196
216
  - `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
217
  - `src/generate.mts` is the only place that turns the client generator's failures into the error codes of `--json` (`mapClientError`).
198
218
  - Generation-side modules (`src/hooks/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.
219
+ - A hook builder takes the names it declares and refers to from `hookNames(op)` (`src/hooks/hookNames.mts`), never from the operation's name directly: `settleHookNames` numbers a name that its file already imports or declares, and the files are then built again with those names.
220
+ - A hook builder declares what its statement needs from the generated client: `service` (the SDK function) and `models` (types from `types.gen`). The fixed names (TanStack Query, `Options`, `Common`, `AxiosError`) are imported when the code mentions them, which is only safe because the client generator reserves them. When hook code starts using a new name, add it to `RESERVED_TYPE_NAMES` or `RESERVED_FUNCTION_NAMES` and to the list in `tests/hooks/imports.test.ts`.
199
221
  - 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
222
  - The runtimes (`src/client/runtime/*.runtime.ts`) are plain TypeScript that is copied verbatim into users' projects. Keep them dependency-free (axios aside), strict-mode clean, and free of syntax that needs a newer TypeScript than the generated code supports. `scripts/copy-runtime.mjs` ships them next to the compiled generator.
201
223
 
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
- await generate({ ...options, output: scratchOutput }, version, {
132
- silent: true,
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 files = changesPerDir.flat().sort(byPath);
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
@@ -20,4 +20,6 @@ export type LimitedUserConfig = {
20
20
  nextPageParam: string;
21
21
  initialPageParam: string | number;
22
22
  omitInitialPageParam?: boolean;
23
+ /** `--agentsMd`: the file to keep the agent guide in, or `true` for `AGENTS.md`. */
24
+ agentsMd?: string | boolean;
23
25
  };
@@ -1,6 +1,7 @@
1
1
  import { HEADER } from "./emitSdk.mjs";
2
2
  import { propertyKey, uniqueName } from "./naming.mjs";
3
3
  import { componentSchemaKey, hasFlag } from "./schema.mjs";
4
+ import { COMPONENT_SCHEMA_PREFIX } from "./spec.mjs";
4
5
  const DOCUMENTATION_KEYWORDS = [
5
6
  "description",
6
7
  "title",
@@ -31,7 +32,7 @@ function project(schema, ctx, variant) {
31
32
  const renamed = key === undefined ? undefined : variant.renamed.get(key);
32
33
  entries.push([
33
34
  keyword,
34
- renamed === undefined ? value : `#/components/schemas/${renamed}`,
35
+ renamed === undefined ? value : `${COMPONENT_SCHEMA_PREFIX}${renamed}`,
35
36
  ]);
36
37
  }
37
38
  else if (SCHEMA_KEYWORDS.includes(keyword)) {
@@ -63,15 +64,17 @@ function project(schema, ctx, variant) {
63
64
  entries.push([keyword, value]);
64
65
  }
65
66
  }
66
- return Object.fromEntries(entries.flatMap(([keyword, value]) => {
67
- if (keyword !== "required" || removed.size === 0) {
68
- return [[keyword, value]];
67
+ const projected = Object.fromEntries(entries);
68
+ if (removed.size > 0 && Array.isArray(projected.required)) {
69
+ const required = projected.required.filter((name) => !removed.has(name));
70
+ if (required.length > 0) {
71
+ projected.required = required;
69
72
  }
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
- }));
73
+ else {
74
+ delete projected.required;
75
+ }
76
+ }
77
+ return projected;
75
78
  }
76
79
  function literal(value, indent = "") {
77
80
  if (value === null || typeof value !== "object") {
@@ -9,6 +9,8 @@ export declare function emitSdk(doc: Doc, operations: OperationIR[], options: {
9
9
  /** SDK function name → response transformer from `transformers.gen.ts`. */
10
10
  transformers?: ReadonlyMap<string, string>;
11
11
  }): string;
12
+ /** The option that holds the base URL, spelled the way each client does. */
13
+ export declare function baseUrlKey(kind: ClientKind): string;
12
14
  export declare function emitClientFile(options: {
13
15
  kind: ClientKind;
14
16
  ext: string;
@@ -1,6 +1,6 @@
1
1
  import { classifyResponses, mediaKind, } from "./operations.mjs";
2
- import { docComment } from "./schema.mjs";
3
- import { resolveRef } from "./spec.mjs";
2
+ import { docComment, schemaKinds } from "./schema.mjs";
3
+ import { baseMediaType } from "./spec.mjs";
4
4
  export const HEADER = "// This file is auto-generated by @7nohe/openapi-react-query-codegen\n";
5
5
  const CONTENT_TYPE_BY_KIND = {
6
6
  urlencoded: "application/x-www-form-urlencoded",
@@ -8,26 +8,20 @@ const CONTENT_TYPE_BY_KIND = {
8
8
  function q(value) {
9
9
  return JSON.stringify(value);
10
10
  }
11
- function schemaType(doc, schema) {
12
- const resolved = resolveRef(doc, schema);
13
- if (!resolved || typeof resolved !== "object")
11
+ /**
12
+ * What a parameter's value is, for the serializer: a primitive, an array or an
13
+ * object. Undefined when the schema allows more than one of them, or does not
14
+ * say.
15
+ */
16
+ function parameterShape(doc, schema) {
17
+ const kinds = schemaKinds(doc, schema);
18
+ kinds.delete("null");
19
+ if (kinds.has("other"))
14
20
  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;
21
+ const shapes = new Set([...kinds].map((kind) => kind === "array" || kind === "object" ? kind : "primitive"));
22
+ const [only] = shapes;
23
+ return shapes.size === 1 ? only : undefined;
29
24
  }
30
- const PRIMITIVE_TYPES = new Set(["boolean", "integer", "number", "string"]);
31
25
  /**
32
26
  * Query parameters the runtime defaults would serialize differently from the
33
27
  * OpenAPI ones. The runtime leaves arrays in `form` style with `explode`, and
@@ -43,8 +37,8 @@ function querySerializerEntries(doc, parameters) {
43
37
  entries.push(`${q(parameter.name)}: { json: true }`);
44
38
  continue;
45
39
  }
46
- const type = schemaType(doc, parameter.schema);
47
- if (type !== undefined && PRIMITIVE_TYPES.has(type))
40
+ const type = parameterShape(doc, parameter.schema);
41
+ if (type === "primitive")
48
42
  continue;
49
43
  const style = parameter.style ?? "form";
50
44
  const explode = parameter.explode ?? style === "form";
@@ -80,8 +74,8 @@ function pathSerializerEntries(doc, parameters) {
80
74
  const explode = parameter.explode ?? false;
81
75
  if (style === "simple") {
82
76
  // `explode` only changes how an object is written.
83
- const type = schemaType(doc, parameter.schema);
84
- if (!explode || type === "array" || PRIMITIVE_TYPES.has(type ?? "")) {
77
+ const type = parameterShape(doc, parameter.schema);
78
+ if (!explode || type === "array" || type === "primitive") {
85
79
  continue;
86
80
  }
87
81
  }
@@ -109,7 +103,7 @@ function parseKind(mediaType) {
109
103
  if (kind === "form-data")
110
104
  return "formData";
111
105
  // Readable documents, the same as the runtime when it detects the type.
112
- const type = mediaType.toLowerCase().split(";")[0].trim();
106
+ const type = baseMediaType(mediaType);
113
107
  return type === "application/xml" || type.endsWith("+xml") ? "text" : "blob";
114
108
  }
115
109
  /**
@@ -222,10 +216,13 @@ ${docComment({ description: "You can pass arbitrary values through the `meta` ob
222
216
  };`;
223
217
  return `${HEADER}\n${imports.join("\n")}\n\n${optionsType}\n\n${blocks.join("\n\n")}\n`;
224
218
  }
219
+ /** The option that holds the base URL, spelled the way each client does. */
220
+ export function baseUrlKey(kind) {
221
+ return kind === "axios" ? "baseURL" : "baseUrl";
222
+ }
225
223
  export function emitClientFile(options) {
226
- const baseUrlKey = options.kind === "axios" ? "baseURL" : "baseUrl";
227
224
  const config = options.baseUrl
228
- ? `{ ${baseUrlKey}: ${q(options.baseUrl)} }`
225
+ ? `{ ${baseUrlKey(options.kind)}: ${q(options.baseUrl)} }`
229
226
  : "";
230
227
  return `${HEADER}
231
228
  import {
@@ -1,69 +1,14 @@
1
1
  import { HEADER } from "./emitSdk.mjs";
2
2
  import { isValidIdentifier, uniqueName } from "./naming.mjs";
3
3
  import { classifyResponses } from "./operations.mjs";
4
- import { componentSchemaKey, discriminatorValues, isDateString, } from "./schema.mjs";
5
- import { getByPointer, refSiblingSchema } from "./spec.mjs";
6
- const ALL_KINDS = ["string", "object", "array", "other"];
4
+ import { componentSchemaKey, discriminatorValues, hasObjectKeywords, isDateString, schemaKinds, } from "./schema.mjs";
5
+ import { COMPONENT_SCHEMA_PREFIX, getByPointer, refSiblingSchema, } from "./spec.mjs";
7
6
  const ACTED_KINDS = ["string", "object", "array"];
8
- function kindOfType(type) {
9
- return type === "string" || type === "object" || type === "array"
10
- ? type
11
- : "other";
12
- }
13
- function kindOfValue(value) {
14
- if (typeof value === "string")
15
- return "string";
16
- if (Array.isArray(value))
17
- return "array";
18
- return typeof value === "object" && value !== null ? "object" : "other";
19
- }
20
7
  /** The shapes a value of the schema can have. Unknown means any of them. */
21
- function kindsOf(ctx, schema, depth = 0) {
22
- if (schema === false)
23
- return new Set();
24
- if (!schema || typeof schema !== "object" || depth > 16) {
25
- return new Set(ALL_KINDS);
26
- }
27
- if (typeof schema.$ref === "string") {
28
- return kindsOf(ctx, getByPointer(ctx.doc, schema.$ref), depth + 1);
29
- }
30
- if (schema.const !== undefined)
31
- return new Set([kindOfValue(schema.const)]);
32
- if (Array.isArray(schema.enum)) {
33
- return new Set(schema.enum.map(kindOfValue));
34
- }
35
- let kinds;
36
- if (Array.isArray(schema.type)) {
37
- kinds = new Set(schema.type.map(kindOfType));
38
- }
39
- else if (typeof schema.type === "string") {
40
- kinds = new Set([kindOfType(schema.type)]);
41
- }
42
- else if (schema.properties ||
43
- schema.patternProperties ||
44
- schema.additionalProperties !== undefined) {
45
- kinds = new Set(["object"]);
46
- }
47
- else if (schema.items || schema.prefixItems) {
48
- kinds = new Set(["array"]);
49
- }
50
- else {
51
- kinds = new Set(ALL_KINDS);
52
- }
53
- const narrow = (other) => {
54
- kinds = new Set([...kinds].filter((kind) => other.has(kind)));
55
- };
56
- for (const member of Array.isArray(schema.allOf) ? schema.allOf : []) {
57
- narrow(kindsOf(ctx, member, depth + 1));
58
- }
59
- for (const key of ["oneOf", "anyOf"]) {
60
- if (!Array.isArray(schema[key]) || schema[key].length === 0)
61
- continue;
62
- narrow(new Set(schema[key].flatMap((member) => [
63
- ...kindsOf(ctx, member, depth + 1),
64
- ])));
65
- }
66
- return kinds;
8
+ function kindsOf(ctx, schema) {
9
+ return new Set([...schemaKinds(ctx.doc, schema)].map((kind) => kind === "string" || kind === "object" || kind === "array"
10
+ ? kind
11
+ : "other"));
67
12
  }
68
13
  function all(steps) {
69
14
  const present = steps.filter((step) => step !== undefined);
@@ -96,16 +41,14 @@ function buildPlan(schema, ctx, where, seen = new Set()) {
96
41
  if (schema.const !== undefined || Array.isArray(schema.enum)) {
97
42
  return undefined;
98
43
  }
99
- const hasObjectKeywords = schema.properties ||
100
- schema.patternProperties ||
101
- schema.additionalProperties;
44
+ const hasObjectPart = hasObjectKeywords(schema);
102
45
  const allOf = Array.isArray(schema.allOf) && schema.allOf.length > 0 ? schema.allOf : [];
103
46
  const unionKeys = ["oneOf", "anyOf"].filter((key) => Array.isArray(schema[key]) && schema[key].length > 0);
104
47
  if (allOf.length > 0 || unionKeys.length > 0) {
105
48
  return all([
106
49
  ...allOf.map((member, index) => buildPlan(member, ctx, `${where}/allOf/${index}`, seen)),
107
50
  ...unionKeys.map((key) => buildUnion(schema[key], schema.discriminator, ctx, `${where}/${key}`, seen)),
108
- hasObjectKeywords ? buildObject(schema, ctx, where, seen) : undefined,
51
+ hasObjectPart ? buildObject(schema, ctx, where, seen) : undefined,
109
52
  ]);
110
53
  }
111
54
  if (Array.isArray(schema.type)) {
@@ -121,7 +64,7 @@ function buildPlan(schema, ctx, where, seen = new Set()) {
121
64
  case "object":
122
65
  return buildObject(schema, ctx, where, seen);
123
66
  case undefined:
124
- if (hasObjectKeywords)
67
+ if (hasObjectPart)
125
68
  return buildObject(schema, ctx, where, seen);
126
69
  return schema.items || schema.prefixItems
127
70
  ? buildArray(schema, ctx, where, seen)
@@ -475,6 +418,10 @@ function emitPlan(plan, target, indent, depth, functionNames) {
475
418
  return [];
476
419
  }
477
420
  }
421
+ /** A map with the same keys and every value passed through `change`. */
422
+ function mapValues(map, change) {
423
+ return new Map([...map].map(([key, value]) => [key, change(value)]));
424
+ }
478
425
  function lowerFirst(name) {
479
426
  return name.charAt(0).toLowerCase() + name.slice(1);
480
427
  }
@@ -487,7 +434,7 @@ export function emitTransformers(operations, ctx) {
487
434
  const schemas = (ctx.doc.components?.schemas ?? {});
488
435
  let components = new Map(Object.entries(schemas).map(([key, schema]) => [
489
436
  key,
490
- buildPlan(schema, ctx, `#/components/schemas/${key}`),
437
+ buildPlan(schema, ctx, `${COMPONENT_SCHEMA_PREFIX}${key}`),
491
438
  ]));
492
439
  let responses = new Map();
493
440
  for (const operation of operations) {
@@ -502,22 +449,24 @@ export function emitTransformers(operations, ctx) {
502
449
  const prune = () => {
503
450
  const live = liveKeys(components);
504
451
  const keep = (plan) => dropDead(plan, live);
505
- components = new Map([...components].map(([k, plan]) => [k, keep(plan)]));
506
- responses = new Map([...responses].map(([k, plan]) => [k, keep(plan)]));
452
+ components = mapValues(components, keep);
453
+ responses = mapValues(responses, keep);
507
454
  };
508
455
  prune();
509
456
  const byKey = actsByKey(components);
510
457
  const skipped = new Set();
511
458
  const resolve = (plan) => resolveUnions(plan, byKey, skipped);
512
- components = new Map([...components].map(([k, plan]) => [k, resolve(plan)]));
513
- responses = new Map([...responses].map(([k, plan]) => [k, resolve(plan)]));
459
+ components = mapValues(components, resolve);
460
+ responses = mapValues(responses, resolve);
514
461
  // Dropping an ambiguous union can leave a component with nothing to do.
515
462
  prune();
516
463
  const used = new Set();
464
+ // `sdk.gen.ts` imports a transformer next to the functions it declares.
465
+ const sdkFunctions = new Set(operations.map((operation) => operation.functionName));
517
466
  const byOperation = new Map();
518
467
  for (const [name, plan] of responses) {
519
468
  if (plan) {
520
- byOperation.set(name, uniqueName(`${name}ResponseTransformer`, used));
469
+ byOperation.set(name, uniqueName(`${name}ResponseTransformer`, used, sdkFunctions));
521
470
  }
522
471
  }
523
472
  if (byOperation.size === 0) {
@@ -10,7 +10,8 @@ export type EmittedTypes = {
10
10
  };
11
11
  /** First server URL with its variables replaced by their defaults. */
12
12
  export declare function getBaseUrl(doc: Doc): string | undefined;
13
- export declare function emitTypes(doc: Doc, operations: OperationIR[], ctx: SchemaCtx, options: {
13
+ export declare function emitTypes(operations: OperationIR[], ctx: SchemaCtx, options: {
14
14
  enums?: EnumsMode;
15
15
  clientKind: ClientKind;
16
+ baseUrl?: string;
16
17
  }): EmittedTypes;
@@ -1,4 +1,4 @@
1
- import { HEADER } from "./emitSdk.mjs";
1
+ import { baseUrlKey, HEADER } from "./emitSdk.mjs";
2
2
  import { propertyKey, toEnumMemberName, uniqueName } from "./naming.mjs";
3
3
  import { buildRequestBodyNames, classifyResponses, deref, pickContent, } from "./operations.mjs";
4
4
  import { docComment, renderComponentSchema, renderSchema, schemaDescription, } from "./schema.mjs";
@@ -147,14 +147,14 @@ function emitComponentSchema(schema, key, name, ctx, enumsMode) {
147
147
  }
148
148
  return `${comment}export type ${name} = ${renderComponentSchema(schema, key, ctx)};`;
149
149
  }
150
- export function emitTypes(doc, operations, ctx, options) {
150
+ export function emitTypes(operations, ctx, options) {
151
+ const { doc } = ctx;
151
152
  const readCtx = { ...ctx, mode: "read" };
152
153
  const writeCtx = { ...ctx, mode: "write" };
153
154
  const head = [];
154
155
  const exported = ["ClientOptions"];
155
- const baseUrl = getBaseUrl(doc);
156
- const baseUrlKey = options.clientKind === "axios" ? "baseURL" : "baseUrl";
157
- head.push(`export type ClientOptions = {\n ${baseUrlKey}: ${baseUrl ? `${JSON.stringify(baseUrl)} | (string & {})` : "string"};\n};`);
156
+ const { baseUrl } = options;
157
+ head.push(`export type ClientOptions = {\n ${baseUrlKey(options.clientKind)}: ${baseUrl ? `${JSON.stringify(baseUrl)} | (string & {})` : "string"};\n};`);
158
158
  const schemas = (doc.components?.schemas ?? {});
159
159
  for (const [key, schema] of Object.entries(schemas)) {
160
160
  const name = ctx.names.get(key);