@7nohe/openapi-react-query-codegen 4.0.0-beta.3 → 4.0.0-beta.5

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 (56) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +2 -2
  3. package/dist/client/emitSchemas.mjs +12 -9
  4. package/dist/client/emitSdk.d.mts +2 -0
  5. package/dist/client/emitSdk.mjs +24 -27
  6. package/dist/client/emitTransformers.mjs +21 -72
  7. package/dist/client/emitTypes.d.mts +2 -1
  8. package/dist/client/emitTypes.mjs +5 -5
  9. package/dist/client/index.mjs +13 -5
  10. package/dist/client/naming.d.mts +5 -2
  11. package/dist/client/naming.mjs +7 -3
  12. package/dist/client/operations.d.mts +3 -2
  13. package/dist/client/operations.mjs +16 -48
  14. package/dist/client/runtime/axios.runtime.ts +15 -10
  15. package/dist/client/schema.d.mts +24 -2
  16. package/dist/client/schema.mjs +135 -33
  17. package/dist/client/spec.d.mts +6 -0
  18. package/dist/client/spec.mjs +15 -5
  19. package/dist/common.d.mts +0 -2
  20. package/dist/common.mjs +0 -10
  21. package/dist/createSource.d.mts +1 -1
  22. package/dist/createSource.mjs +1 -3
  23. package/dist/format.d.mts +0 -1
  24. package/dist/format.mjs +0 -20
  25. package/dist/generate.mjs +2 -4
  26. package/dist/{tsmorph → hooks}/buildCommon.d.mts +13 -17
  27. package/dist/hooks/buildCommon.mjs +132 -0
  28. package/dist/{tsmorph → hooks}/buildMutationHooks.d.mts +4 -3
  29. package/dist/hooks/buildMutationHooks.mjs +24 -0
  30. package/dist/{tsmorph → hooks}/buildQueryHooks.d.mts +22 -16
  31. package/dist/{tsmorph → hooks}/buildQueryHooks.mjs +35 -106
  32. package/dist/{tsmorph → hooks}/buildQueryOptions.d.mts +5 -4
  33. package/dist/{tsmorph → hooks}/buildQueryOptions.mjs +9 -35
  34. package/dist/{tsmorph → hooks}/generateFiles.d.mts +1 -1
  35. package/dist/hooks/generateFiles.mjs +122 -0
  36. package/dist/hooks/hookNames.d.mts +69 -0
  37. package/dist/hooks/hookNames.mjs +82 -0
  38. package/dist/hooks/imports.d.mts +46 -0
  39. package/dist/hooks/imports.mjs +115 -0
  40. package/dist/hooks/operationNames.d.mts +15 -0
  41. package/dist/hooks/operationNames.mjs +31 -0
  42. package/dist/hooks/statement.d.mts +43 -0
  43. package/dist/hooks/statement.mjs +63 -0
  44. package/dist/types.d.mts +5 -7
  45. package/package.json +3 -5
  46. package/dist/print.d.mts +0 -5
  47. package/dist/print.mjs +0 -22
  48. package/dist/tsmorph/buildCommon.mjs +0 -183
  49. package/dist/tsmorph/buildMutationHooks.mjs +0 -36
  50. package/dist/tsmorph/generateFiles.mjs +0 -153
  51. package/dist/tsmorph/index.d.mts +0 -5
  52. package/dist/tsmorph/index.mjs +0 -5
  53. package/dist/tsmorph/operationNames.d.mts +0 -5
  54. package/dist/tsmorph/operationNames.mjs +0 -9
  55. package/dist/tsmorph/projectFactory.d.mts +0 -58
  56. package/dist/tsmorph/projectFactory.mjs +0 -169
package/AGENTS.md CHANGED
@@ -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` and `ts-morph` are peer dependencies. If your package manager does not install peers automatically, add them as devDependencies. 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/`.
24
+ `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
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
 
@@ -93,6 +93,8 @@ Names come from the operation ID (or from the path with `--noOperationId`). For
93
93
  | `useFindPetsKey`, `UseFindPetsKeyFn(clientOptions?)` | `common.ts` | `invalidateQueries` with the same key the hook uses |
94
94
  | `useAddPet(mutationKey?, options?)` | `queries.ts` | `useMutation`; `mutate({ body, path, query })` |
95
95
 
96
+ 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`.
97
+
96
98
  `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
99
 
98
100
  ```tsx
@@ -189,13 +191,15 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
189
191
  - After generator changes, run tests and consider regenerating example outputs to manually diff.
190
192
 
191
193
  ### Commit & Pull Request Guidelines
192
- - Commits: clear, descriptive messages (e.g., `fix: align imports for generated queries`, `chore: update ts-morph config`). Avoid bundling unrelated changes.
194
+ - Commits: clear, descriptive messages (e.g., `fix: align imports for generated queries`, `chore: update biome config`). Avoid bundling unrelated changes.
193
195
  - Pull requests: include summary of changes, affected areas (e.g., codegen output, docs, examples), and test commands run. Link issues when applicable. Add before/after notes or sample generated snippets if behavior changes.
194
196
 
195
197
  ### Architecture: IR Boundary
196
198
  - `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
199
  - `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.
200
+ - 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.
201
+ - 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.
202
+ - 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
203
  - 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
204
  - 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
205
 
@@ -203,5 +207,5 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
203
207
  - Runtime dependencies are deliberately few (`cross-spawn`, `yaml`). Adding one needs a reason; the generator replaced `@hey-api/openapi-ts` to cut the supply-chain surface.
204
208
 
205
209
  ### Agent-Specific Notes
206
- - Use AST-aware paths (ts-morph/TypeScript factory) when editing generators to keep output structurally valid.
210
+ - The generators build source text as strings. After changing one, run the tests that compile the generated output (`tests/createSource.test.ts`, `tests/client/`) to confirm it is still valid TypeScript.
207
211
  - Respect ignore patterns in `biome.json` and avoid checking in `dist/` or example-generated artifacts unless explicitly intended.
package/README.md CHANGED
@@ -59,9 +59,9 @@ The client generator is part of this package, so the generated `requests/` direc
59
59
 
60
60
  ## Requirements
61
61
 
62
- - Node.js 22.18+
62
+ - Node.js 24+
63
63
  - `@tanstack/react-query` 5.x (peer dependency)
64
- - `ts-morph` 28.x, `commander` 12–15 (peer dependencies)
64
+ - `commander` 12–15 (peer dependency)
65
65
  - TypeScript 5.x, 6.x or 7.x to compile the generated code. It is not a peer dependency: the generator does not use the `typescript` package.
66
66
 
67
67
  ## License
@@ -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);
@@ -30,6 +30,13 @@ function toOperationInfo(operation, ctx, pageParam, emittedTypes) {
30
30
  const pageParameter = method === "GET"
31
31
  ? operation.parameters.find((parameter) => parameter.in === "query" && parameter.name === pageParam)
32
32
  : undefined;
33
+ const pageParamModels = new Set();
34
+ const pageParamType = pageParameter
35
+ ? renderSchema(pageParameter.schema, {
36
+ ...ctx,
37
+ onRef: (name) => pageParamModels.add(name),
38
+ })
39
+ : undefined;
33
40
  return {
34
41
  methodName: operation.functionName,
35
42
  capitalizedMethodName: capitalizeFirst(operation.functionName),
@@ -41,9 +48,8 @@ function toOperationInfo(operation, ctx, pageParam, emittedTypes) {
41
48
  jsDoc: operation.jsDoc,
42
49
  allParamsOptional: optionsAreOptional(operation),
43
50
  isPaginatable: pageParameter !== undefined,
44
- pageParamType: pageParameter
45
- ? renderSchema(pageParameter.schema, ctx)
46
- : undefined,
51
+ pageParamType,
52
+ pageParamModels: pageParameter ? [...pageParamModels] : undefined,
47
53
  pageParamTypeKind: pageParameter
48
54
  ? schemaPrimitiveKind(ctx.doc, pageParameter.schema)
49
55
  : undefined,
@@ -67,9 +73,11 @@ export async function generateClient(options) {
67
73
  reservedTypeNames: [...names.values(), ...writableNames.values()],
68
74
  });
69
75
  const ext = options.importExtension;
70
- const types = emitTypes(doc, operations, ctx, {
76
+ const baseUrl = getBaseUrl(doc);
77
+ const types = emitTypes(operations, ctx, {
71
78
  enums: options.enums,
72
79
  clientKind: options.client,
80
+ baseUrl,
73
81
  });
74
82
  const transformers = options.useDateType
75
83
  ? emitTransformers(operations, ctx)
@@ -95,7 +103,7 @@ export async function generateClient(options) {
95
103
  content: emitClientFile({
96
104
  kind: options.client,
97
105
  ext,
98
- baseUrl: getBaseUrl(doc),
106
+ baseUrl,
99
107
  }),
100
108
  },
101
109
  { name: "runtime.gen.ts", content: await readRuntime(options.client) },
@@ -27,8 +27,11 @@ export declare function toTypeName(input: string): string;
27
27
  export declare function nameFromPath(method: string, path: string): string;
28
28
  /** Object key, quoted only when it is not a valid identifier. */
29
29
  export declare function propertyKey(name: string): string;
30
- /** Make `base` unique inside `used` by appending a counter. */
31
- export declare function uniqueName(base: string, used: Set<string>): string;
30
+ /**
31
+ * Make `base` unique inside `used` by appending a counter. A name in `taken`
32
+ * is passed over as well; `taken` itself is left as it is.
33
+ */
34
+ export declare function uniqueName(base: string, used: Set<string>, taken?: ReadonlySet<string>): string;
32
35
  /**
33
36
  * Name for an enum member generated from its value, in UPPER_SNAKE_CASE
34
37
  * (`in-progress` → `IN_PROGRESS`). A number gets a `_` prefix, except when
@@ -75,6 +75,7 @@ const RESERVED_FUNCTION_NAMES = new Set([
75
75
  "queryKey",
76
76
  "queryOptions",
77
77
  "signal",
78
+ "undefined",
78
79
  "useInfiniteQuery",
79
80
  "useMutation",
80
81
  "useQuery",
@@ -146,11 +147,14 @@ export function nameFromPath(method, path) {
146
147
  export function propertyKey(name) {
147
148
  return isValidIdentifier(name) ? name : JSON.stringify(name);
148
149
  }
149
- /** Make `base` unique inside `used` by appending a counter. */
150
- export function uniqueName(base, used) {
150
+ /**
151
+ * Make `base` unique inside `used` by appending a counter. A name in `taken`
152
+ * is passed over as well; `taken` itself is left as it is.
153
+ */
154
+ export function uniqueName(base, used, taken) {
151
155
  let name = base;
152
156
  let counter = 2;
153
- while (used.has(name)) {
157
+ while (used.has(name) || taken?.has(name)) {
154
158
  name = `${base}${counter}`;
155
159
  counter += 1;
156
160
  }
@@ -1,3 +1,4 @@
1
+ import type { PageParamTypeKind } from "../types.mjs";
1
2
  import { type Doc, type Json } from "./spec.mjs";
2
3
  declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
3
4
  type HttpMethod = (typeof HTTP_METHODS)[number];
@@ -98,6 +99,6 @@ export declare function classifyResponses(operation: OperationIR): {
98
99
  responses: ResponseIR[];
99
100
  errors: ResponseIR[];
100
101
  };
101
- /** Resolve a schema (following `$ref` chains) down to its leading primitive. */
102
- export declare function schemaPrimitiveKind(doc: Doc, node: Json): "string" | "number" | "other";
102
+ /** The one primitive a schema holds, leaving `null` aside. */
103
+ export declare function schemaPrimitiveKind(doc: Doc, node: Json): PageParamTypeKind;
103
104
  export {};
@@ -1,11 +1,12 @@
1
1
  import { nameFromPath, toFunctionName, toTypeName, uniqueName, } from "./naming.mjs";
2
- import { docComment, findReadWriteOnlyKeys } from "./schema.mjs";
3
- import { getByPointer, resolveRef } from "./spec.mjs";
2
+ import { docComment, findReadWriteOnlyKeys, schemaKinds } from "./schema.mjs";
3
+ import { baseMediaType, getByPointer } from "./spec.mjs";
4
4
  /**
5
5
  * Type names a schema or an operation type cannot take: `ClientOptions` and
6
6
  * `Options` are exported next to them, and the rest are what the generated hook
7
7
  * files import or use, where an imported model of the same name would clash
8
- * with or shadow them.
8
+ * with or shadow them. The last four are the type parameters of the hooks,
9
+ * which would shadow the model instead.
9
10
  */
10
11
  const RESERVED_TYPE_NAMES = [
11
12
  "ClientOptions",
@@ -34,6 +35,10 @@ const RESERVED_TYPE_NAMES = [
34
35
  "Promise",
35
36
  "Record",
36
37
  "ReturnType",
38
+ "TContext",
39
+ "TData",
40
+ "TError",
41
+ "TQueryKey",
37
42
  ];
38
43
  const HTTP_METHODS = [
39
44
  "get",
@@ -66,7 +71,7 @@ export function deref(doc, node, depth = 0) {
66
71
  return node;
67
72
  }
68
73
  export function mediaKind(mediaType) {
69
- const type = mediaType.toLowerCase().split(";")[0].trim();
74
+ const type = baseMediaType(mediaType);
70
75
  if (type === "application/json" || type.endsWith("+json"))
71
76
  return "json";
72
77
  if (type === "multipart/form-data")
@@ -304,49 +309,12 @@ export function classifyResponses(operation) {
304
309
  (responses.length === 0 ? responses : errors).push(fallback);
305
310
  return { responses, errors };
306
311
  }
307
- /** Resolve a schema (following `$ref` chains) down to its leading primitive. */
312
+ /** The one primitive a schema holds, leaving `null` aside. */
308
313
  export function schemaPrimitiveKind(doc, node) {
309
- const schema = resolveRef(doc, node);
310
- if (!schema || typeof schema !== "object")
311
- return "other";
312
- const alternatives = schema.anyOf ?? schema.oneOf ?? schema.allOf;
313
- if (Array.isArray(alternatives)) {
314
- const kinds = new Set(alternatives
315
- .filter((member) => resolveRef(doc, member)?.type !== "null")
316
- .map((member) => schemaPrimitiveKind(doc, member)));
317
- const [only] = kinds;
318
- return kinds.size === 1 ? only : "other";
319
- }
320
- const kinds = new Set();
321
- const collect = (value) => {
322
- if (value === null)
323
- return;
324
- if (typeof value === "string")
325
- kinds.add("string");
326
- else if (typeof value === "number")
327
- kinds.add("number");
328
- else
329
- kinds.add("other");
330
- };
331
- if (Array.isArray(schema.enum)) {
332
- for (const value of schema.enum)
333
- collect(value);
334
- }
335
- else {
336
- const types = (Array.isArray(schema.type) ? schema.type : [schema.type]).filter((type) => type !== "null");
337
- for (const type of types) {
338
- if (type === "string")
339
- kinds.add("string");
340
- else if (type === "number" || type === "integer")
341
- kinds.add("number");
342
- else
343
- kinds.add("other");
344
- }
345
- }
346
- if (kinds.size === 1) {
347
- const [only] = kinds;
348
- if (only === "string" || only === "number")
349
- return only;
350
- }
351
- return "other";
314
+ const kinds = schemaKinds(doc, node);
315
+ kinds.delete("null");
316
+ const [only] = kinds;
317
+ return kinds.size === 1 && (only === "string" || only === "number")
318
+ ? only
319
+ : "other";
352
320
  }