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

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 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
 
@@ -189,13 +189,13 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
189
189
  - After generator changes, run tests and consider regenerating example outputs to manually diff.
190
190
 
191
191
  ### 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.
192
+ - Commits: clear, descriptive messages (e.g., `fix: align imports for generated queries`, `chore: update biome config`). Avoid bundling unrelated changes.
193
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.
194
194
 
195
195
  ### Architecture: IR Boundary
196
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
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.
198
+ - 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.
199
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
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.
201
201
 
@@ -203,5 +203,5 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
203
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.
204
204
 
205
205
  ### Agent-Specific Notes
206
- - Use AST-aware paths (ts-morph/TypeScript factory) when editing generators to keep output structurally valid.
206
+ - 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
207
  - 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
@@ -5,7 +5,8 @@ import { getByPointer, resolveRef } from "./spec.mjs";
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",
@@ -1,4 +1,4 @@
1
- import { generateAllFiles } from "./tsmorph/index.mjs";
1
+ import { generateAllFiles } from "./hooks/index.mjs";
2
2
  /**
3
3
  * Create the React Query source files for a generated client.
4
4
  */
package/dist/format.d.mts CHANGED
@@ -1,4 +1,3 @@
1
- export declare const formatOutput: (outputPath: string) => Promise<void>;
2
1
  export declare const processOutput: ({ output, format, lint, }: {
3
2
  output: string;
4
3
  format?: "prettier" | "biome";
package/dist/format.mjs CHANGED
@@ -1,24 +1,4 @@
1
1
  import { sync } from "cross-spawn";
2
- import { IndentationText, NewLineKind, Project, QuoteKind } from "ts-morph";
3
- export const formatOutput = async (outputPath) => {
4
- const project = new Project({
5
- skipAddingFilesFromTsConfig: true,
6
- manipulationSettings: {
7
- indentationText: IndentationText.TwoSpaces,
8
- newLineKind: NewLineKind.LineFeed,
9
- quoteKind: QuoteKind.Double,
10
- usePrefixAndSuffixTextForRename: false,
11
- useTrailingCommas: true,
12
- },
13
- });
14
- const sourceFiles = project.addSourceFilesAtPaths(`${outputPath}/**/*`);
15
- const tasks = sourceFiles.map((sourceFile) => {
16
- sourceFile.formatText();
17
- sourceFile.organizeImports();
18
- return sourceFile.save();
19
- });
20
- await Promise.all(tasks);
21
- };
22
2
  const formatters = {
23
3
  biome: {
24
4
  args: (path) => ["format", "--write", path],
package/dist/generate.mjs CHANGED
@@ -2,7 +2,7 @@ import { detectImportExtension, findNearestTsConfigPath, generateClient, SpecErr
2
2
  import { buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, } from "./common.mjs";
3
3
  import { createSource } from "./createSource.mjs";
4
4
  import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
5
- import { formatOutput, processOutput } from "./format.mjs";
5
+ import { processOutput } from "./format.mjs";
6
6
  import { print } from "./print.mjs";
7
7
  export { findNearestTsConfigPath };
8
8
  /** Map a `--client` value (including the v3 `@hey-api/*` aliases) to a kind. */
@@ -84,7 +84,6 @@ async function runGenerate(options, version, runtime) {
84
84
  });
85
85
  await print(source, formattedOptions);
86
86
  const queriesOutputPath = buildQueriesOutputPath(options.output);
87
- await formatOutput(queriesOutputPath);
88
87
  await processOutput({
89
88
  output: queriesOutputPath,
90
89
  format: formattedOptions.format,
@@ -1,42 +1,42 @@
1
- import { type TypeAliasDeclarationStructure, type VariableStatementStructure } from "ts-morph";
2
1
  import type { GenerationContext, OperationInfo } from "../types.mjs";
2
+ import type { ConstStatement, TypeStatement } from "./statement.mjs";
3
3
  /**
4
4
  * Build the default response type alias.
5
5
  * Example: export type FindPetsDefaultResponse = Awaited<ReturnType<typeof findPets>>["data"];
6
6
  */
7
- export declare function buildDefaultResponseType(op: OperationInfo): TypeAliasDeclarationStructure;
7
+ export declare function buildDefaultResponseType(op: OperationInfo): TypeStatement;
8
8
  /**
9
9
  * Build the query result type alias.
10
10
  * Example: export type FindPetsQueryResult<TData = FindPetsDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>;
11
11
  */
12
- export declare function buildQueryResultType(op: OperationInfo): TypeAliasDeclarationStructure;
12
+ export declare function buildQueryResultType(op: OperationInfo): TypeStatement;
13
13
  /**
14
14
  * Build the mutation result type alias.
15
15
  * Example: export type AddPetMutationResult = Awaited<ReturnType<typeof addPet>>;
16
16
  */
17
- export declare function buildMutationResultType(op: OperationInfo): TypeAliasDeclarationStructure;
17
+ export declare function buildMutationResultType(op: OperationInfo): TypeStatement;
18
18
  /**
19
19
  * Build query key constant.
20
20
  * Example: export const useFindPetsKey = "FindPets";
21
21
  */
22
- export declare function buildQueryKeyConst(op: OperationInfo): VariableStatementStructure;
22
+ export declare function buildQueryKeyConst(op: OperationInfo): ConstStatement;
23
23
  /**
24
24
  * Build mutation key constant.
25
25
  * Example: export const useAddPetKey = "AddPet";
26
26
  */
27
- export declare function buildMutationKeyConst(op: OperationInfo): VariableStatementStructure;
27
+ export declare function buildMutationKeyConst(op: OperationInfo): ConstStatement;
28
28
  /**
29
29
  * Build query key function.
30
30
  * Example: export const UseFindPetsKeyFn = (clientOptions: Options<FindPetsData, true> = {}, queryKey?: Array<unknown>) =>
31
31
  * [useFindPetsKey, ...(queryKey ?? [clientOptions])];
32
32
  */
33
- export declare function buildQueryKeyFn(op: OperationInfo): VariableStatementStructure;
33
+ export declare function buildQueryKeyFn(op: OperationInfo): ConstStatement;
34
34
  /**
35
35
  * Build mutation key function.
36
36
  * Example: export const UseAddPetKeyFn = (mutationKey?: Array<unknown>) =>
37
37
  * [useAddPetKey, ...(mutationKey ?? [])];
38
38
  */
39
- export declare function buildMutationKeyFn(op: OperationInfo): VariableStatementStructure;
39
+ export declare function buildMutationKeyFn(op: OperationInfo): ConstStatement;
40
40
  /**
41
41
  * Build the client options type for infinite queries.
42
42
  * The page parameter is excluded because TanStack Query supplies it via the
@@ -45,7 +45,7 @@ export declare function buildMutationKeyFn(op: OperationInfo): VariableStatement
45
45
  * export type FindPaginatedPetsInfiniteClientOptions = Omit<Options<FindPaginatedPetsData, true>, "query"> &
46
46
  * { query?: Omit<NonNullable<FindPaginatedPetsData["query"]>, "page"> };
47
47
  */
48
- export declare function buildInfiniteClientOptionsType(op: OperationInfo, ctx: GenerationContext): TypeAliasDeclarationStructure;
48
+ export declare function buildInfiniteClientOptionsType(op: OperationInfo, ctx: GenerationContext): TypeStatement;
49
49
  /**
50
50
  * Build the infinite query key constant.
51
51
  * Shares the plain query key as its first segment so a single
@@ -54,7 +54,7 @@ export declare function buildInfiniteClientOptionsType(op: OperationInfo, ctx: G
54
54
  * segment keeps cached InfiniteData from colliding with plain query data (#140).
55
55
  * Example: export const useFindPaginatedPetsInfiniteKey = [useFindPaginatedPetsKey, "infinite"] as const;
56
56
  */
57
- export declare function buildInfiniteQueryKeyConst(op: OperationInfo): VariableStatementStructure;
57
+ export declare function buildInfiniteQueryKeyConst(op: OperationInfo): ConstStatement;
58
58
  /**
59
59
  * Build the infinite query key function.
60
60
  * The custom queryKey argument only replaces the params segment — the
@@ -63,4 +63,4 @@ export declare function buildInfiniteQueryKeyConst(op: OperationInfo): VariableS
63
63
  * Example: export const UseFindPaginatedPetsInfiniteKeyFn = (clientOptions: FindPaginatedPetsInfiniteClientOptions = {}, queryKey?: Array<unknown>) =>
64
64
  * [...useFindPaginatedPetsInfiniteKey, ...(queryKey ?? [clientOptions])];
65
65
  */
66
- export declare function buildInfiniteQueryKeyFn(op: OperationInfo): VariableStatementStructure;
66
+ export declare function buildInfiniteQueryKeyFn(op: OperationInfo): ConstStatement;
@@ -1,4 +1,3 @@
1
- import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
1
  import { getDataTypeName } from "./operationNames.mjs";
3
2
  /**
4
3
  * Build the default response type alias.
@@ -6,8 +5,7 @@ import { getDataTypeName } from "./operationNames.mjs";
6
5
  */
7
6
  export function buildDefaultResponseType(op) {
8
7
  return {
9
- kind: StructureKind.TypeAlias,
10
- isExported: true,
8
+ kind: "type",
11
9
  name: `${op.capitalizedMethodName}DefaultResponse`,
12
10
  type: `Awaited<ReturnType<typeof ${op.methodName}>>["data"]`,
13
11
  };
@@ -18,8 +16,7 @@ export function buildDefaultResponseType(op) {
18
16
  */
19
17
  export function buildQueryResultType(op) {
20
18
  return {
21
- kind: StructureKind.TypeAlias,
22
- isExported: true,
19
+ kind: "type",
23
20
  name: `${op.capitalizedMethodName}QueryResult`,
24
21
  typeParameters: [
25
22
  { name: "TData", default: `${op.capitalizedMethodName}DefaultResponse` },
@@ -34,8 +31,7 @@ export function buildQueryResultType(op) {
34
31
  */
35
32
  export function buildMutationResultType(op) {
36
33
  return {
37
- kind: StructureKind.TypeAlias,
38
- isExported: true,
34
+ kind: "type",
39
35
  name: `${op.capitalizedMethodName}MutationResult`,
40
36
  type: `Awaited<ReturnType<typeof ${op.methodName}>>`,
41
37
  };
@@ -46,15 +42,9 @@ export function buildMutationResultType(op) {
46
42
  */
47
43
  export function buildQueryKeyConst(op) {
48
44
  return {
49
- kind: StructureKind.VariableStatement,
50
- isExported: true,
51
- declarationKind: VariableDeclarationKind.Const,
52
- declarations: [
53
- {
54
- name: `use${op.capitalizedMethodName}Key`,
55
- initializer: `"${op.capitalizedMethodName}"`,
56
- },
57
- ],
45
+ kind: "const",
46
+ name: `use${op.capitalizedMethodName}Key`,
47
+ initializer: `"${op.capitalizedMethodName}"`,
58
48
  };
59
49
  }
60
50
  /**
@@ -63,15 +53,9 @@ export function buildQueryKeyConst(op) {
63
53
  */
64
54
  export function buildMutationKeyConst(op) {
65
55
  return {
66
- kind: StructureKind.VariableStatement,
67
- isExported: true,
68
- declarationKind: VariableDeclarationKind.Const,
69
- declarations: [
70
- {
71
- name: `use${op.capitalizedMethodName}Key`,
72
- initializer: `"${op.capitalizedMethodName}"`,
73
- },
74
- ],
56
+ kind: "const",
57
+ name: `use${op.capitalizedMethodName}Key`,
58
+ initializer: `"${op.capitalizedMethodName}"`,
75
59
  };
76
60
  }
77
61
  /**
@@ -87,15 +71,9 @@ export function buildQueryKeyFn(op) {
87
71
  params.push("queryKey?: Array<unknown>");
88
72
  const fallbackArray = "[clientOptions]";
89
73
  return {
90
- kind: StructureKind.VariableStatement,
91
- isExported: true,
92
- declarationKind: VariableDeclarationKind.Const,
93
- declarations: [
94
- {
95
- name: `Use${op.capitalizedMethodName}KeyFn`,
96
- initializer: `(${params.join(", ")}) => [use${op.capitalizedMethodName}Key, ...(queryKey ?? ${fallbackArray})]`,
97
- },
98
- ],
74
+ kind: "const",
75
+ name: `Use${op.capitalizedMethodName}KeyFn`,
76
+ initializer: `(${params.join(", ")}) => [use${op.capitalizedMethodName}Key, ...(queryKey ?? ${fallbackArray})]`,
99
77
  };
100
78
  }
101
79
  /**
@@ -105,15 +83,9 @@ export function buildQueryKeyFn(op) {
105
83
  */
106
84
  export function buildMutationKeyFn(op) {
107
85
  return {
108
- kind: StructureKind.VariableStatement,
109
- isExported: true,
110
- declarationKind: VariableDeclarationKind.Const,
111
- declarations: [
112
- {
113
- name: `Use${op.capitalizedMethodName}KeyFn`,
114
- initializer: `(mutationKey?: Array<unknown>) => [use${op.capitalizedMethodName}Key, ...(mutationKey ?? [])]`,
115
- },
116
- ],
86
+ kind: "const",
87
+ name: `Use${op.capitalizedMethodName}KeyFn`,
88
+ initializer: `(mutationKey?: Array<unknown>) => [use${op.capitalizedMethodName}Key, ...(mutationKey ?? [])]`,
117
89
  };
118
90
  }
119
91
  /**
@@ -128,8 +100,7 @@ export function buildInfiniteClientOptionsType(op, ctx) {
128
100
  const dataTypeName = getDataTypeName(op);
129
101
  const type = `Omit<Options<${dataTypeName}, true>, "query"> & { query?: Omit<NonNullable<${dataTypeName}["query"]>, "${ctx.pageParam}"> }`;
130
102
  return {
131
- kind: StructureKind.TypeAlias,
132
- isExported: true,
103
+ kind: "type",
133
104
  name: `${op.capitalizedMethodName}InfiniteClientOptions`,
134
105
  type,
135
106
  };
@@ -144,15 +115,9 @@ export function buildInfiniteClientOptionsType(op, ctx) {
144
115
  */
145
116
  export function buildInfiniteQueryKeyConst(op) {
146
117
  return {
147
- kind: StructureKind.VariableStatement,
148
- isExported: true,
149
- declarationKind: VariableDeclarationKind.Const,
150
- declarations: [
151
- {
152
- name: `use${op.capitalizedMethodName}InfiniteKey`,
153
- initializer: `[use${op.capitalizedMethodName}Key, "infinite"] as const`,
154
- },
155
- ],
118
+ kind: "const",
119
+ name: `use${op.capitalizedMethodName}InfiniteKey`,
120
+ initializer: `[use${op.capitalizedMethodName}Key, "infinite"] as const`,
156
121
  };
157
122
  }
158
123
  /**
@@ -170,14 +135,8 @@ export function buildInfiniteQueryKeyFn(op) {
170
135
  "queryKey?: Array<unknown>",
171
136
  ];
172
137
  return {
173
- kind: StructureKind.VariableStatement,
174
- isExported: true,
175
- declarationKind: VariableDeclarationKind.Const,
176
- declarations: [
177
- {
178
- name: `Use${op.capitalizedMethodName}InfiniteKeyFn`,
179
- initializer: `(${params.join(", ")}) => [...use${op.capitalizedMethodName}InfiniteKey, ...(queryKey ?? [clientOptions])]`,
180
- },
181
- ],
138
+ kind: "const",
139
+ name: `Use${op.capitalizedMethodName}InfiniteKeyFn`,
140
+ initializer: `(${params.join(", ")}) => [...use${op.capitalizedMethodName}InfiniteKey, ...(queryKey ?? [clientOptions])]`,
182
141
  };
183
142
  }
@@ -1,5 +1,5 @@
1
- import { type VariableStatementStructure } from "ts-morph";
2
1
  import type { GenerationContext, OperationInfo } from "../types.mjs";
2
+ import type { ConstStatement } from "./statement.mjs";
3
3
  /**
4
4
  * Build useMutation hook.
5
5
  * Example:
@@ -12,4 +12,4 @@ import type { GenerationContext, OperationInfo } from "../types.mjs";
12
12
  * ...options
13
13
  * });
14
14
  */
15
- export declare function buildUseMutationHook(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure;
15
+ export declare function buildUseMutationHook(op: OperationInfo, ctx: GenerationContext): ConstStatement;
@@ -1,4 +1,3 @@
1
- import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
1
  import { SDK_CALL_ARGS } from "./buildQueryHooks.mjs";
3
2
  import { getDataTypeName, getErrorType } from "./operationNames.mjs";
4
3
  /**
@@ -21,16 +20,10 @@ export function buildUseMutationHook(op, ctx) {
21
20
  const mutationFn = `clientOptions => ${op.methodName}(${SDK_CALL_ARGS}) as unknown as Promise<TData>`;
22
21
  const body = `useMutation<TData, TError, ${optionsType}, TContext>({ mutationKey: Common.Use${op.capitalizedMethodName}KeyFn(mutationKey), mutationFn: ${mutationFn}, ...options })`;
23
22
  return {
24
- kind: StructureKind.VariableStatement,
25
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
26
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
27
- isExported: true,
28
- declarationKind: VariableDeclarationKind.Const,
29
- declarations: [
30
- {
31
- name: hookName,
32
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[], TContext = unknown>(mutationKey?: TQueryKey, options?: Omit<UseMutationOptions<TData, TError, ${optionsType}, TContext>, "mutationKey" | "mutationFn">) => ${body}`,
33
- },
34
- ],
23
+ kind: "const",
24
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
25
+ jsDoc: op.jsDoc,
26
+ name: hookName,
27
+ initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[], TContext = unknown>(mutationKey?: TQueryKey, options?: Omit<UseMutationOptions<TData, TError, ${optionsType}, TContext>, "mutationKey" | "mutationFn">) => ${body}`,
35
28
  };
36
29
  }
@@ -1,5 +1,5 @@
1
- import { type VariableStatementStructure } from "ts-morph";
2
1
  import type { GenerationContext, OperationInfo } from "../types.mjs";
2
+ import type { ConstStatement } from "./statement.mjs";
3
3
  /**
4
4
  * SDK call arguments shared by every generated queryFn/mutationFn.
5
5
  * throwOnError: true forces the SDK call to reject on error responses; the
@@ -79,19 +79,19 @@ export declare function buildOverridableInfiniteOptionsType(optionsTypeName: str
79
79
  * ...options
80
80
  * });
81
81
  */
82
- export declare function buildUseQueryHook(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure;
82
+ export declare function buildUseQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement;
83
83
  /**
84
84
  * Build useSuspenseQuery hook.
85
85
  */
86
- export declare function buildUseSuspenseQueryHook(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure;
86
+ export declare function buildUseSuspenseQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement;
87
87
  /**
88
88
  * Build useInfiniteQuery hook.
89
89
  */
90
- export declare function buildUseInfiniteQueryHook(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure | null;
90
+ export declare function buildUseInfiniteQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
91
91
  /**
92
92
  * Build useSuspenseInfiniteQuery hook.
93
93
  */
94
- export declare function buildUseSuspenseInfiniteQueryHook(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure | null;
94
+ export declare function buildUseSuspenseInfiniteQueryHook(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
95
95
  /**
96
96
  * Build prefetch function.
97
97
  * Example:
@@ -102,7 +102,7 @@ export declare function buildUseSuspenseInfiniteQueryHook(op: OperationInfo, ctx
102
102
  * ...options
103
103
  * });
104
104
  */
105
- export declare function buildPrefetchFn(op: OperationInfo): VariableStatementStructure;
105
+ export declare function buildPrefetchFn(op: OperationInfo): ConstStatement;
106
106
  /**
107
107
  * Build prefetchInfiniteQuery function for a paginatable operation.
108
108
  * Example:
@@ -115,7 +115,7 @@ export declare function buildPrefetchFn(op: OperationInfo): VariableStatementStr
115
115
  * ...options
116
116
  * });
117
117
  */
118
- export declare function buildPrefetchInfiniteQueryFn(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure | null;
118
+ export declare function buildPrefetchInfiniteQueryFn(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
119
119
  /**
120
120
  * Build ensureQueryData function.
121
121
  * Example:
@@ -126,4 +126,4 @@ export declare function buildPrefetchInfiniteQueryFn(op: OperationInfo, ctx: Gen
126
126
  * ...options
127
127
  * });
128
128
  */
129
- export declare function buildEnsureQueryDataFn(op: OperationInfo): VariableStatementStructure;
129
+ export declare function buildEnsureQueryDataFn(op: OperationInfo): ConstStatement;
@@ -1,4 +1,3 @@
1
- import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
1
  import { isValidIdentifier, propertyKey } from "../client/naming.mjs";
3
2
  import { getDataTypeName, getErrorType } from "./operationNames.mjs";
4
3
  /**
@@ -146,17 +145,11 @@ export function buildUseQueryHook(op, ctx) {
146
145
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data as TData) as TData`;
147
146
  const body = `useQuery<TData, TError>({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ...options })`;
148
147
  return {
149
- kind: StructureKind.VariableStatement,
150
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
151
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
152
- isExported: true,
153
- declarationKind: VariableDeclarationKind.Const,
154
- declarations: [
155
- {
156
- name: hookName,
157
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`,
158
- },
159
- ],
148
+ kind: "const",
149
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
150
+ jsDoc: op.jsDoc,
151
+ name: hookName,
152
+ initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`,
160
153
  };
161
154
  }
162
155
  /**
@@ -170,17 +163,11 @@ export function buildUseSuspenseQueryHook(op, ctx) {
170
163
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data as TData) as TData`;
171
164
  const body = `useSuspenseQuery<TData, TError>({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ...options })`;
172
165
  return {
173
- kind: StructureKind.VariableStatement,
174
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
175
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
176
- isExported: true,
177
- declarationKind: VariableDeclarationKind.Const,
178
- declarations: [
179
- {
180
- name: hookName,
181
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseSuspenseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`,
182
- },
183
- ],
166
+ kind: "const",
167
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
168
+ jsDoc: op.jsDoc,
169
+ name: hookName,
170
+ initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${clientOptionsParam}, queryKey?: TQueryKey, options?: Omit<UseSuspenseQueryOptions<TData, TError>, "queryKey" | "queryFn">) => ${body}`,
184
171
  };
185
172
  }
186
173
  /**
@@ -209,17 +196,11 @@ function buildInfiniteHook(op, ctx, suspense) {
209
196
  const infiniteOptions = `initialPageParam: ${formatInitialPageParam(ctx, op)}, getNextPageParam: ${buildGetNextPageParamExpr(ctx, op)}`;
210
197
  const body = `${hookCall}({ queryKey: Common.Use${op.capitalizedMethodName}InfiniteKeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
211
198
  return {
212
- kind: StructureKind.VariableStatement,
213
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
214
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
215
- isExported: true,
216
- declarationKind: VariableDeclarationKind.Const,
217
- declarations: [
218
- {
219
- name: hookName,
220
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${buildInfiniteClientOptionsParam(op)}, queryKey?: TQueryKey, options?: ${buildOverridableInfiniteOptionsType(optionsTypeName, getPageType(op))}) => ${body}`,
221
- },
222
- ],
199
+ kind: "const",
200
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
201
+ jsDoc: op.jsDoc,
202
+ name: hookName,
203
+ initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[]>(${buildInfiniteClientOptionsParam(op)}, queryKey?: TQueryKey, options?: ${buildOverridableInfiniteOptionsType(optionsTypeName, getPageType(op))}) => ${body}`,
223
204
  };
224
205
  }
225
206
  /**
@@ -250,17 +231,11 @@ export function buildPrefetchFn(op) {
250
231
  const optionsParam = `options?: Omit<FetchQueryOptions<Common.${op.capitalizedMethodName}DefaultResponse>, "queryKey" | "queryFn">`;
251
232
  const body = `queryClient.prefetchQuery({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions), queryFn: ${queryFn}, ...options })`;
252
233
  return {
253
- kind: StructureKind.VariableStatement,
254
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
255
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
256
- isExported: true,
257
- declarationKind: VariableDeclarationKind.Const,
258
- declarations: [
259
- {
260
- name: fnName,
261
- initializer: `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
262
- },
263
- ],
234
+ kind: "const",
235
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
236
+ jsDoc: op.jsDoc,
237
+ name: fnName,
238
+ initializer: `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
264
239
  };
265
240
  }
266
241
  /**
@@ -293,17 +268,11 @@ export function buildPrefetchInfiniteQueryFn(op, ctx) {
293
268
  const optionsParam = `options?: Omit<${instantiated}, "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam"> & ${overrides}`;
294
269
  const body = `queryClient.prefetchInfiniteQuery({ queryKey: Common.Use${op.capitalizedMethodName}InfiniteKeyFn(clientOptions), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
295
270
  return {
296
- kind: StructureKind.VariableStatement,
297
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
298
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
299
- isExported: true,
300
- declarationKind: VariableDeclarationKind.Const,
301
- declarations: [
302
- {
303
- name: fnName,
304
- initializer: `(queryClient: QueryClient, ${buildInfiniteClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
305
- },
306
- ],
271
+ kind: "const",
272
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
273
+ jsDoc: op.jsDoc,
274
+ name: fnName,
275
+ initializer: `(queryClient: QueryClient, ${buildInfiniteClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
307
276
  };
308
277
  }
309
278
  /**
@@ -322,16 +291,10 @@ export function buildEnsureQueryDataFn(op) {
322
291
  const optionsParam = `options?: Omit<EnsureQueryDataOptions<Common.${op.capitalizedMethodName}DefaultResponse>, "queryKey" | "queryFn">`;
323
292
  const body = `queryClient.ensureQueryData({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions), queryFn: ${queryFn}, ...options })`;
324
293
  return {
325
- kind: StructureKind.VariableStatement,
326
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
327
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
328
- isExported: true,
329
- declarationKind: VariableDeclarationKind.Const,
330
- declarations: [
331
- {
332
- name: fnName,
333
- initializer: `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
334
- },
335
- ],
294
+ kind: "const",
295
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
296
+ jsDoc: op.jsDoc,
297
+ name: fnName,
298
+ initializer: `(queryClient: QueryClient, ${buildClientOptionsParam(op)}, ${optionsParam}) => ${body}`,
336
299
  };
337
300
  }
@@ -1,5 +1,5 @@
1
- import { type VariableStatementStructure } from "ts-morph";
2
1
  import type { GenerationContext, OperationInfo } from "../types.mjs";
2
+ import type { ConstStatement } from "./statement.mjs";
3
3
  /**
4
4
  * Build a queryOptions factory for a GET operation.
5
5
  * The factory centralizes queryKey and queryFn so they can be reused with
@@ -12,7 +12,7 @@ import type { GenerationContext, OperationInfo } from "../types.mjs";
12
12
  * queryFn: () => findPets({ ...clientOptions, throwOnError: true }).then(response => response.data),
13
13
  * });
14
14
  */
15
- export declare function buildQueryOptionsFn(op: OperationInfo): VariableStatementStructure;
15
+ export declare function buildQueryOptionsFn(op: OperationInfo): ConstStatement;
16
16
  /**
17
17
  * Build an infiniteQueryOptions factory for a paginatable GET operation.
18
18
  * Uses the dedicated infinite query key and page-less options type.
@@ -26,4 +26,4 @@ export declare function buildQueryOptionsFn(op: OperationInfo): VariableStatemen
26
26
  * ...options,
27
27
  * });
28
28
  */
29
- export declare function buildInfiniteQueryOptionsFn(op: OperationInfo, ctx: GenerationContext): VariableStatementStructure | null;
29
+ export declare function buildInfiniteQueryOptionsFn(op: OperationInfo, ctx: GenerationContext): ConstStatement | null;
@@ -1,4 +1,3 @@
1
- import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
1
  import { buildClientOptionsParam, buildGetNextPageParamExpr, buildInfiniteClientOptionsParam, buildPagedQueryFn, formatInitialPageParam, getPageType, QUERY_SDK_CALL_ARGS, } from "./buildQueryHooks.mjs";
3
2
  /**
4
3
  * Build a queryOptions factory for a GET operation.
@@ -18,17 +17,11 @@ export function buildQueryOptionsFn(op) {
18
17
  const queryFn = `({ signal }) => ${op.methodName}(${QUERY_SDK_CALL_ARGS}).then(response => response.data)`;
19
18
  const body = `queryOptions({ queryKey: Common.Use${op.capitalizedMethodName}KeyFn(clientOptions, queryKey), queryFn: ${queryFn} })`;
20
19
  return {
21
- kind: StructureKind.VariableStatement,
22
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
23
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
24
- isExported: true,
25
- declarationKind: VariableDeclarationKind.Const,
26
- declarations: [
27
- {
28
- name: fnName,
29
- initializer: `(${clientOptionsParam}, queryKey?: Array<unknown>) => ${body}`,
30
- },
31
- ],
20
+ kind: "const",
21
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
22
+ jsDoc: op.jsDoc,
23
+ name: fnName,
24
+ initializer: `(${clientOptionsParam}, queryKey?: Array<unknown>) => ${body}`,
32
25
  };
33
26
  }
34
27
  /**
@@ -57,16 +50,10 @@ export function buildInfiniteQueryOptionsFn(op, ctx) {
57
50
  const optionsParam = `options?: Partial<Pick<UseInfiniteQueryOptions<${getPageType(op)}>, "initialPageParam" | "getNextPageParam">>`;
58
51
  const body = `infiniteQueryOptions({ queryKey: Common.Use${op.capitalizedMethodName}InfiniteKeyFn(clientOptions, queryKey), queryFn: ${queryFn}, ${infiniteOptions}, ...options })`;
59
52
  return {
60
- kind: StructureKind.VariableStatement,
61
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
62
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
63
- isExported: true,
64
- declarationKind: VariableDeclarationKind.Const,
65
- declarations: [
66
- {
67
- name: fnName,
68
- initializer: `(${buildInfiniteClientOptionsParam(op)}, queryKey?: Array<unknown>, ${optionsParam}) => ${body}`,
69
- },
70
- ],
53
+ kind: "const",
54
+ // The operation's JSDoc (description and @deprecated), as on the SDK function
55
+ jsDoc: op.jsDoc,
56
+ name: fnName,
57
+ initializer: `(${buildInfiniteClientOptionsParam(op)}, queryKey?: Array<unknown>, ${optionsParam}) => ${body}`,
71
58
  };
72
59
  }
@@ -1,5 +1,5 @@
1
1
  import type { GeneratedFile, GenerationContext, OperationInfo } from "../types.mjs";
2
2
  /**
3
- * Generate all files using ts-morph.
3
+ * Generate the React Query files for the operations of a specification.
4
4
  */
5
5
  export declare function generateAllFiles(operations: OperationInfo[], ctx: GenerationContext): GeneratedFile[];
@@ -3,7 +3,8 @@ import { buildDefaultResponseType, buildInfiniteClientOptionsType, buildInfinite
3
3
  import { buildUseMutationHook } from "./buildMutationHooks.mjs";
4
4
  import { buildEnsureQueryDataFn, buildPrefetchFn, buildPrefetchInfiniteQueryFn, buildUseInfiniteQueryHook, buildUseQueryHook, buildUseSuspenseInfiniteQueryHook, buildUseSuspenseQueryHook, } from "./buildQueryHooks.mjs";
5
5
  import { buildInfiniteQueryOptionsFn, buildQueryOptionsFn, } from "./buildQueryOptions.mjs";
6
- import { buildCommonFileImports, buildHookFileImports, buildQueryOptionsFileImports, createGenerationProject, relativeModule, } from "./projectFactory.mjs";
6
+ import { buildCommonFileImports, buildHookFileImports, buildQueryOptionsFileImports, printImports, relativeModule, } from "./imports.mjs";
7
+ import { printStatements, referencedNames, statementCode, } from "./statement.mjs";
7
8
  /**
8
9
  * Build one variable statement per operation, skipping the ones the builder
9
10
  * declines. A builder returns null when the operation is out of its scope —
@@ -21,39 +22,25 @@ function collectStatements(operations, build) {
21
22
  return statements;
22
23
  }
23
24
  /**
24
- * ts-morph separates statements of different kinds with a blank line when
25
- * they are added one at a time but not when they are added as a batch, so
26
- * restore the separator where the kind changes.
25
+ * The content of a generated file: the imports its statements need, then the
26
+ * statements. Only the services of the operations the file covers and the
27
+ * models its code mentions are imported.
27
28
  */
28
- function separateKinds(statements) {
29
- return statements.map((statement, index) => index > 0 && statements[index - 1].kind !== statement.kind
30
- ? { ...statement, leadingTrivia: `\n${statement.leadingTrivia ?? ""}` }
31
- : statement);
32
- }
33
- const IDENTIFIER_RE = /[\p{ID_Start}_$][\p{ID_Continue}$]*/gu;
34
- /**
35
- * Create a generated file. Statements go in as one batch so ts-morph reparses
36
- * the file once, and only the model and service names the body actually
37
- * mentions are imported: importing thousands of unused names forced every
38
- * edit to rescan a huge import list and made the later import organising pass
39
- * slow on large specifications.
40
- */
41
- function createFile(name, ctx, buildImports, statements) {
42
- const project = createGenerationProject();
43
- const sourceFile = project.createSourceFile(`${name}.ts`, undefined, {
44
- overwrite: true,
45
- });
46
- sourceFile.addStatements(statements);
47
- const used = new Set(sourceFile.getFullText().match(IDENTIFIER_RE));
48
- sourceFile.insertImportDeclarations(0, buildImports({
29
+ function createFile(ctx, buildImports, operations, statements) {
30
+ if (statements.length === 0) {
31
+ // Nothing to export. The bare import keeps the file a module.
32
+ return `import "${relativeModule("../requests/sdk.gen", ctx)}";\n`;
33
+ }
34
+ const used = referencedNames(statements.map(statementCode).join("\n"));
35
+ const imports = buildImports({
49
36
  ...ctx,
50
37
  modelNames: ctx.modelNames.filter((model) => used.has(model)),
51
- serviceNames: ctx.serviceNames.filter((service) => used.has(service)),
52
- }));
53
- return sourceFile.getFullText();
38
+ serviceNames: operations.map((op) => op.methodName),
39
+ });
40
+ return `${printImports(imports, used)}\n${printStatements(statements)}`;
54
41
  }
55
42
  /**
56
- * The content of index.ts, which needs no ts-morph project.
43
+ * The content of index.ts.
57
44
  */
58
45
  function indexFile(ctx) {
59
46
  return [
@@ -76,7 +63,7 @@ function commonStatements(queries, mutations, ctx) {
76
63
  for (const op of mutations) {
77
64
  statements.push(buildMutationResultType(op), buildMutationKeyConst(op), buildMutationKeyFn(op));
78
65
  }
79
- return separateKinds(statements);
66
+ return statements;
80
67
  }
81
68
  /**
82
69
  * Add the generated header comment to file content.
@@ -86,20 +73,24 @@ function addHeaderComment(content, version) {
86
73
  return comment + content;
87
74
  }
88
75
  /**
89
- * Generate all files using ts-morph.
76
+ * Generate the React Query files for the operations of a specification.
90
77
  */
91
78
  export function generateAllFiles(operations, ctx) {
92
79
  const queries = operations.filter((op) => op.httpMethod === "GET");
93
80
  const mutations = operations.filter((op) => ["POST", "PUT", "PATCH", "DELETE"].includes(op.httpMethod));
81
+ const paginated = queries.filter((op) => op.isPaginatable);
82
+ const all = [...queries, ...mutations];
94
83
  const files = [
95
84
  [
96
85
  OpenApiRqFiles.common,
97
86
  buildCommonFileImports,
87
+ all,
98
88
  commonStatements(queries, mutations, ctx),
99
89
  ],
100
90
  [
101
91
  OpenApiRqFiles.queries,
102
92
  buildHookFileImports,
93
+ all,
103
94
  [
104
95
  ...queries.map((op) => buildUseQueryHook(op, ctx)),
105
96
  ...mutations.map((op) => buildUseMutationHook(op, ctx)),
@@ -108,6 +99,7 @@ export function generateAllFiles(operations, ctx) {
108
99
  [
109
100
  OpenApiRqFiles.queryOptions,
110
101
  buildQueryOptionsFileImports,
102
+ queries,
111
103
  [
112
104
  ...queries.map((op) => buildQueryOptionsFn(op)),
113
105
  ...collectStatements(queries, (op) => buildInfiniteQueryOptionsFn(op, ctx)),
@@ -116,6 +108,7 @@ export function generateAllFiles(operations, ctx) {
116
108
  [
117
109
  OpenApiRqFiles.suspense,
118
110
  buildHookFileImports,
111
+ queries,
119
112
  [
120
113
  ...queries.map((op) => buildUseSuspenseQueryHook(op, ctx)),
121
114
  ...collectStatements(queries, (op) => buildUseSuspenseInfiniteQueryHook(op, ctx)),
@@ -124,11 +117,13 @@ export function generateAllFiles(operations, ctx) {
124
117
  [
125
118
  OpenApiRqFiles.infiniteQueries,
126
119
  buildHookFileImports,
120
+ paginated,
127
121
  collectStatements(queries, (op) => buildUseInfiniteQueryHook(op, ctx)),
128
122
  ],
129
123
  [
130
124
  OpenApiRqFiles.prefetch,
131
125
  buildHookFileImports,
126
+ queries,
132
127
  [
133
128
  ...queries.map((op) => buildPrefetchFn(op)),
134
129
  ...collectStatements(queries, (op) => buildPrefetchInfiniteQueryFn(op, ctx)),
@@ -137,6 +132,7 @@ export function generateAllFiles(operations, ctx) {
137
132
  [
138
133
  OpenApiRqFiles.ensureQueryData,
139
134
  buildHookFileImports,
135
+ queries,
140
136
  queries.map((op) => buildEnsureQueryDataFn(op)),
141
137
  ],
142
138
  ];
@@ -145,9 +141,9 @@ export function generateAllFiles(operations, ctx) {
145
141
  name: `${OpenApiRqFiles.index}.ts`,
146
142
  content: addHeaderComment(indexFile(ctx), ctx.version),
147
143
  },
148
- ...files.map(([name, imports, statements]) => ({
144
+ ...files.map(([name, imports, operations, statements]) => ({
149
145
  name: `${name}.ts`,
150
- content: addHeaderComment(createFile(name, ctx, imports, statements), ctx.version),
146
+ content: addHeaderComment(createFile(ctx, imports, operations, statements), ctx.version),
151
147
  })),
152
148
  ];
153
149
  }
@@ -1,10 +1,16 @@
1
- import { type ImportDeclarationStructure, Project } from "ts-morph";
2
1
  import type { GenerationContext } from "../types.mjs";
3
- /**
4
- * Create a shared ts-morph Project for code generation.
5
- * Uses consistent formatting settings to match existing output.
6
- */
7
- export declare function createGenerationProject(): Project;
2
+ /** One import declaration of a generated file, before unused names are dropped. */
3
+ export type ImportDeclaration = {
4
+ moduleSpecifier: string;
5
+ /** `import type { … }` */
6
+ isTypeOnly?: boolean;
7
+ /** `import * as Name` */
8
+ namespaceImport?: string;
9
+ namedImports?: Array<{
10
+ name: string;
11
+ isTypeOnly?: boolean;
12
+ }>;
13
+ };
8
14
  /**
9
15
  * A relative module specifier, with the extension the consuming project's
10
16
  * module resolution asks for.
@@ -15,44 +21,51 @@ export declare function relativeModule(path: string, ctx?: Pick<GenerationContex
15
21
  * sdk.gen re-exports Options extended with `client` and `meta`, which the
16
22
  * base client Options lacks; hooks must accept those properties.
17
23
  */
18
- export declare function buildClientImport(ctx: GenerationContext): ImportDeclarationStructure;
24
+ export declare function buildClientImport(ctx: GenerationContext): ImportDeclaration;
19
25
  /**
20
26
  * Build import structure for TanStack Query.
21
27
  */
22
- export declare function buildQueryImport(): ImportDeclarationStructure;
28
+ export declare function buildQueryImport(): ImportDeclaration;
23
29
  /**
24
30
  * Build import structure for the queryOptions/infiniteQueryOptions helpers.
25
31
  */
26
- export declare function buildQueryOptionsImport(): ImportDeclarationStructure;
32
+ export declare function buildQueryOptionsImport(): ImportDeclaration;
27
33
  /**
28
34
  * Build import structure for services.
29
35
  */
30
- export declare function buildServiceImport(ctx: GenerationContext): ImportDeclarationStructure;
36
+ export declare function buildServiceImport(ctx: GenerationContext): ImportDeclaration;
31
37
  /**
32
38
  * Build import structure for models.
33
39
  * Emitted as a type-only import so generated code compiles under
34
40
  * `verbatimModuleSyntax` (enabled by default in recent Vite templates).
35
41
  */
36
- export declare function buildModelImport(ctx: GenerationContext): ImportDeclarationStructure | null;
42
+ export declare function buildModelImport(ctx: GenerationContext): ImportDeclaration | null;
37
43
  /**
38
44
  * Build import structure for axios error type.
39
45
  */
40
- export declare function buildAxiosErrorImport(): ImportDeclarationStructure;
46
+ export declare function buildAxiosErrorImport(): ImportDeclaration;
41
47
  /**
42
48
  * Build import for Common namespace.
43
49
  */
44
- export declare function buildCommonImport(ctx?: Pick<GenerationContext, "importExtension">): ImportDeclarationStructure;
50
+ export declare function buildCommonImport(ctx?: Pick<GenerationContext, "importExtension">): ImportDeclaration;
45
51
  /**
46
52
  * Build all imports needed for the common file.
47
53
  */
48
- export declare function buildCommonFileImports(ctx: GenerationContext): ImportDeclarationStructure[];
54
+ export declare function buildCommonFileImports(ctx: GenerationContext): ImportDeclaration[];
49
55
  /**
50
56
  * Build all imports needed for hook files (queries, suspense, infinite).
51
57
  */
52
- export declare function buildHookFileImports(ctx: GenerationContext): ImportDeclarationStructure[];
58
+ export declare function buildHookFileImports(ctx: GenerationContext): ImportDeclaration[];
53
59
  /**
54
60
  * Build all imports needed for the queryOptions file.
55
61
  * Narrower than the hook file imports: queryOptions only needs the
56
62
  * queryOptions/infiniteQueryOptions helpers, not the TanStack hooks.
57
63
  */
58
- export declare function buildQueryOptionsFileImports(ctx: GenerationContext): ImportDeclarationStructure[];
64
+ export declare function buildQueryOptionsFileImports(ctx: GenerationContext): ImportDeclaration[];
65
+ /**
66
+ * Print the import block of a generated file: only the names in `used`, one
67
+ * declaration per module and kind, packages before relative modules, and both
68
+ * the modules and the names within a declaration in alphabetical order
69
+ * regardless of case. A declaration left without names is dropped.
70
+ */
71
+ export declare function printImports(declarations: ImportDeclaration[], used: ReadonlySet<string>): string;
@@ -1,22 +1,3 @@
1
- import { IndentationText, NewLineKind, Project, QuoteKind, StructureKind, } from "ts-morph";
2
- /**
3
- * Create a shared ts-morph Project for code generation.
4
- * Uses consistent formatting settings to match existing output.
5
- */
6
- export function createGenerationProject() {
7
- return new Project({
8
- useInMemoryFileSystem: true,
9
- compilerOptions: {
10
- strict: true,
11
- },
12
- manipulationSettings: {
13
- indentationText: IndentationText.TwoSpaces,
14
- newLineKind: NewLineKind.LineFeed,
15
- quoteKind: QuoteKind.Double,
16
- useTrailingCommas: true,
17
- },
18
- });
19
- }
20
1
  /**
21
2
  * A relative module specifier, with the extension the consuming project's
22
3
  * module resolution asks for.
@@ -31,7 +12,6 @@ export function relativeModule(path, ctx) {
31
12
  */
32
13
  export function buildClientImport(ctx) {
33
14
  return {
34
- kind: StructureKind.ImportDeclaration,
35
15
  moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
36
16
  namedImports: [{ name: "Options", isTypeOnly: true }],
37
17
  };
@@ -41,7 +21,6 @@ export function buildClientImport(ctx) {
41
21
  */
42
22
  export function buildQueryImport() {
43
23
  return {
44
- kind: StructureKind.ImportDeclaration,
45
24
  moduleSpecifier: "@tanstack/react-query",
46
25
  namedImports: [
47
26
  { name: "QueryClient", isTypeOnly: true },
@@ -70,7 +49,6 @@ export function buildQueryImport() {
70
49
  */
71
50
  export function buildQueryOptionsImport() {
72
51
  return {
73
- kind: StructureKind.ImportDeclaration,
74
52
  moduleSpecifier: "@tanstack/react-query",
75
53
  namedImports: [
76
54
  { name: "queryOptions" },
@@ -84,7 +62,6 @@ export function buildQueryOptionsImport() {
84
62
  */
85
63
  export function buildServiceImport(ctx) {
86
64
  return {
87
- kind: StructureKind.ImportDeclaration,
88
65
  moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
89
66
  namedImports: ctx.serviceNames.map((name) => ({ name })),
90
67
  };
@@ -99,7 +76,6 @@ export function buildModelImport(ctx) {
99
76
  return null;
100
77
  }
101
78
  return {
102
- kind: StructureKind.ImportDeclaration,
103
79
  moduleSpecifier: relativeModule("../requests/types.gen", ctx),
104
80
  isTypeOnly: true,
105
81
  namedImports: ctx.modelNames.map((name) => ({ name })),
@@ -110,7 +86,6 @@ export function buildModelImport(ctx) {
110
86
  */
111
87
  export function buildAxiosErrorImport() {
112
88
  return {
113
- kind: StructureKind.ImportDeclaration,
114
89
  moduleSpecifier: "axios",
115
90
  namedImports: [{ name: "AxiosError" }],
116
91
  };
@@ -120,7 +95,6 @@ export function buildAxiosErrorImport() {
120
95
  */
121
96
  export function buildCommonImport(ctx) {
122
97
  return {
123
- kind: StructureKind.ImportDeclaration,
124
98
  moduleSpecifier: relativeModule("./common", ctx),
125
99
  namespaceImport: "Common",
126
100
  };
@@ -167,3 +141,57 @@ export function buildQueryOptionsFileImports(ctx) {
167
141
  }
168
142
  return imports;
169
143
  }
144
+ function compareCaseInsensitive(a, b) {
145
+ const lowerA = a.toLowerCase();
146
+ const lowerB = b.toLowerCase();
147
+ return lowerA < lowerB ? -1 : lowerA > lowerB ? 1 : 0;
148
+ }
149
+ function isRelative(moduleSpecifier) {
150
+ return moduleSpecifier.startsWith(".");
151
+ }
152
+ function printImport(declaration, names) {
153
+ const from = `from "${declaration.moduleSpecifier}";\n`;
154
+ if (declaration.namespaceImport) {
155
+ return `import * as ${declaration.namespaceImport} ${from}`;
156
+ }
157
+ const list = names
158
+ .sort((a, b) => compareCaseInsensitive(a.name, b.name))
159
+ .map(({ name, isTypeOnly }) => (isTypeOnly ? `type ${name}` : name))
160
+ .join(", ");
161
+ return `import ${declaration.isTypeOnly ? "type " : ""}{ ${list} } ${from}`;
162
+ }
163
+ /**
164
+ * Print the import block of a generated file: only the names in `used`, one
165
+ * declaration per module and kind, packages before relative modules, and both
166
+ * the modules and the names within a declaration in alphabetical order
167
+ * regardless of case. A declaration left without names is dropped.
168
+ */
169
+ export function printImports(declarations, used) {
170
+ const merged = new Map();
171
+ for (const declaration of declarations) {
172
+ const key = [
173
+ declaration.moduleSpecifier,
174
+ declaration.namespaceImport ?? "",
175
+ declaration.isTypeOnly ? "type" : "",
176
+ ].join("|");
177
+ let target = merged.get(key);
178
+ if (!target) {
179
+ target = { declaration, names: new Map() };
180
+ merged.set(key, target);
181
+ }
182
+ for (const named of declaration.namedImports ?? []) {
183
+ if (used.has(named.name)) {
184
+ target.names.set(named.name, named);
185
+ }
186
+ }
187
+ }
188
+ return [...merged.values()]
189
+ .filter(({ declaration, names }) => declaration.namespaceImport
190
+ ? used.has(declaration.namespaceImport)
191
+ : names.size > 0)
192
+ .sort((a, b) => Number(isRelative(a.declaration.moduleSpecifier)) -
193
+ Number(isRelative(b.declaration.moduleSpecifier)) ||
194
+ compareCaseInsensitive(a.declaration.moduleSpecifier, b.declaration.moduleSpecifier))
195
+ .map(({ declaration, names }) => printImport(declaration, [...names.values()]))
196
+ .join("");
197
+ }
@@ -2,4 +2,3 @@ export * from "./buildCommon.mjs";
2
2
  export * from "./buildMutationHooks.mjs";
3
3
  export * from "./buildQueryHooks.mjs";
4
4
  export { generateAllFiles } from "./generateFiles.mjs";
5
- export { createGenerationProject } from "./projectFactory.mjs";
@@ -2,4 +2,3 @@ export * from "./buildCommon.mjs";
2
2
  export * from "./buildMutationHooks.mjs";
3
3
  export * from "./buildQueryHooks.mjs";
4
4
  export { generateAllFiles } from "./generateFiles.mjs";
5
- export { createGenerationProject } from "./projectFactory.mjs";
@@ -0,0 +1,34 @@
1
+ /** An exported `const` of a generated file. */
2
+ export type ConstStatement = {
3
+ kind: "const";
4
+ name: string;
5
+ /** The expression after `=`. */
6
+ initializer: string;
7
+ /** A complete JSDoc comment to put above the declaration. */
8
+ jsDoc?: string;
9
+ };
10
+ /** An exported type alias of a generated file. */
11
+ export type TypeStatement = {
12
+ kind: "type";
13
+ name: string;
14
+ typeParameters?: Array<{
15
+ name: string;
16
+ default: string;
17
+ }>;
18
+ type: string;
19
+ };
20
+ export type Statement = ConstStatement | TypeStatement;
21
+ /** The declaration itself, without its JSDoc. */
22
+ export declare function statementCode(statement: Statement): string;
23
+ /**
24
+ * One statement per line, with a blank line wherever a `const` follows a type
25
+ * alias or the other way round.
26
+ */
27
+ export declare function printStatements(statements: Statement[]): string;
28
+ /**
29
+ * The identifiers a piece of generated code refers to. Three places hold a
30
+ * name without referring to anything a file could import, and are left out:
31
+ * a string literal, the name after the dot of a member access, and the key of
32
+ * a property or the name of a parameter (`{ page: 1 }`, `(options?: T)`).
33
+ */
34
+ export declare function referencedNames(code: string): Set<string>;
@@ -0,0 +1,58 @@
1
+ /** The declaration itself, without its JSDoc. */
2
+ export function statementCode(statement) {
3
+ if (statement.kind === "const") {
4
+ return `export const ${statement.name} = ${statement.initializer};`;
5
+ }
6
+ const typeParameters = statement.typeParameters?.length
7
+ ? `<${statement.typeParameters
8
+ .map((parameter) => `${parameter.name} = ${parameter.default}`)
9
+ .join(", ")}>`
10
+ : "";
11
+ return `export type ${statement.name}${typeParameters} = ${statement.type};`;
12
+ }
13
+ /**
14
+ * One statement per line, with a blank line wherever a `const` follows a type
15
+ * alias or the other way round.
16
+ */
17
+ export function printStatements(statements) {
18
+ let text = "";
19
+ statements.forEach((statement, index) => {
20
+ if (index > 0 && statements[index - 1].kind !== statement.kind) {
21
+ text += "\n";
22
+ }
23
+ if (statement.kind === "const" && statement.jsDoc) {
24
+ text += `${statement.jsDoc}\n`;
25
+ }
26
+ text += `${statementCode(statement)}\n`;
27
+ });
28
+ return text;
29
+ }
30
+ // A string literal, a spread, a member access, an identifier, or any other
31
+ // character. The last one only matters as what comes before an identifier.
32
+ const TOKEN = /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`|\.\.\.|\.\s*[\p{ID_Start}_$][\p{ID_Continue}$]*|[\p{ID_Start}_$][\p{ID_Continue}$]*|\S/gu;
33
+ const IDENTIFIER_START = /^[\p{ID_Start}_$]/u;
34
+ /** What follows the key of a property or the name of a parameter. */
35
+ const KEY_END = /\s*\??:/y;
36
+ /**
37
+ * The identifiers a piece of generated code refers to. Three places hold a
38
+ * name without referring to anything a file could import, and are left out:
39
+ * a string literal, the name after the dot of a member access, and the key of
40
+ * a property or the name of a parameter (`{ page: 1 }`, `(options?: T)`).
41
+ */
42
+ export function referencedNames(code) {
43
+ const names = new Set();
44
+ let previous = "";
45
+ for (const match of code.matchAll(TOKEN)) {
46
+ const [token] = match;
47
+ if (IDENTIFIER_START.test(token)) {
48
+ KEY_END.lastIndex = match.index + token.length;
49
+ const isKey = (previous === "{" || previous === "," || previous === "(") &&
50
+ KEY_END.test(code);
51
+ if (!isKey) {
52
+ names.add(token);
53
+ }
54
+ }
55
+ previous = token;
56
+ }
57
+ return names;
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@7nohe/openapi-react-query-codegen",
3
- "version": "4.0.0-beta.3",
3
+ "version": "4.0.0-beta.4",
4
4
  "description": "OpenAPI React Query Codegen",
5
5
  "bin": {
6
6
  "openapi-rq": "dist/cli.mjs"
@@ -51,18 +51,16 @@
51
51
  "axios": "1.20.0",
52
52
  "commander": "^15.0.0",
53
53
  "lefthook": "^2.1.10",
54
- "ts-morph": "^28.0.0",
55
54
  "typescript": "^6.0.3",
56
55
  "vite": "^7.3.7",
57
56
  "vitest": "^4.1.12"
58
57
  },
59
58
  "peerDependencies": {
60
59
  "@tanstack/react-query": "^5.0.0",
61
- "commander": "12.x || 13.x || 14.x || 15.x",
62
- "ts-morph": "28.x"
60
+ "commander": "12.x || 13.x || 14.x || 15.x"
63
61
  },
64
62
  "engines": {
65
- "node": ">=22.18.0",
63
+ "node": ">=24.0.0",
66
64
  "pnpm": ">=9"
67
65
  },
68
66
  "scripts": {
File without changes
File without changes