@7nohe/openapi-react-query-codegen 4.0.0-beta.2 → 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.
@@ -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>;