@7nohe/openapi-react-query-codegen 4.0.0-beta.4 → 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 (45) hide show
  1. package/AGENTS.md +4 -0
  2. package/dist/client/emitSchemas.mjs +12 -9
  3. package/dist/client/emitSdk.d.mts +2 -0
  4. package/dist/client/emitSdk.mjs +24 -27
  5. package/dist/client/emitTransformers.mjs +21 -72
  6. package/dist/client/emitTypes.d.mts +2 -1
  7. package/dist/client/emitTypes.mjs +5 -5
  8. package/dist/client/index.mjs +13 -5
  9. package/dist/client/naming.d.mts +5 -2
  10. package/dist/client/naming.mjs +7 -3
  11. package/dist/client/operations.d.mts +3 -2
  12. package/dist/client/operations.mjs +10 -47
  13. package/dist/client/runtime/axios.runtime.ts +15 -10
  14. package/dist/client/schema.d.mts +24 -2
  15. package/dist/client/schema.mjs +135 -33
  16. package/dist/client/spec.d.mts +6 -0
  17. package/dist/client/spec.mjs +15 -5
  18. package/dist/common.d.mts +0 -2
  19. package/dist/common.mjs +0 -10
  20. package/dist/createSource.d.mts +1 -1
  21. package/dist/createSource.mjs +1 -3
  22. package/dist/generate.mjs +1 -2
  23. package/dist/hooks/buildCommon.d.mts +12 -16
  24. package/dist/hooks/buildCommon.mjs +25 -35
  25. package/dist/hooks/buildMutationHooks.d.mts +3 -2
  26. package/dist/hooks/buildMutationHooks.mjs +6 -11
  27. package/dist/hooks/buildQueryHooks.d.mts +21 -15
  28. package/dist/hooks/buildQueryHooks.mjs +35 -69
  29. package/dist/hooks/buildQueryOptions.d.mts +4 -3
  30. package/dist/hooks/buildQueryOptions.mjs +9 -22
  31. package/dist/hooks/generateFiles.mjs +54 -81
  32. package/dist/hooks/hookNames.d.mts +69 -0
  33. package/dist/hooks/hookNames.mjs +82 -0
  34. package/dist/hooks/imports.d.mts +27 -52
  35. package/dist/hooks/imports.mjs +82 -164
  36. package/dist/hooks/operationNames.d.mts +10 -0
  37. package/dist/hooks/operationNames.mjs +22 -0
  38. package/dist/hooks/statement.d.mts +15 -6
  39. package/dist/hooks/statement.mjs +19 -14
  40. package/dist/types.d.mts +5 -7
  41. package/package.json +1 -1
  42. package/dist/hooks/index.d.mts +0 -4
  43. package/dist/hooks/index.mjs +0 -4
  44. package/dist/print.d.mts +0 -5
  45. package/dist/print.mjs +0 -22
@@ -0,0 +1,82 @@
1
+ import { uniqueName } from "../client/naming.mjs";
2
+ import { OpenApiRqFiles } from "../constants.mjs";
3
+ import { FIXED_IMPORT_NAMES } from "./imports.mjs";
4
+ /** The names as they are spelled from the name of the operation. */
5
+ function defaultHookNames(op) {
6
+ const name = op.methodName;
7
+ const Name = op.capitalizedMethodName;
8
+ return {
9
+ defaultResponse: `${Name}DefaultResponse`,
10
+ queryResult: `${Name}QueryResult`,
11
+ mutationResult: `${Name}MutationResult`,
12
+ key: `use${Name}Key`,
13
+ keyFn: `Use${Name}KeyFn`,
14
+ infiniteClientOptions: `${Name}InfiniteClientOptions`,
15
+ infiniteKey: `use${Name}InfiniteKey`,
16
+ infiniteKeyFn: `Use${Name}InfiniteKeyFn`,
17
+ hook: `use${Name}`,
18
+ suspenseHook: `use${Name}Suspense`,
19
+ infiniteHook: `use${Name}Infinite`,
20
+ suspenseInfiniteHook: `use${Name}SuspenseInfinite`,
21
+ options: `${name}Options`,
22
+ infiniteOptions: `${name}InfiniteOptions`,
23
+ prefetch: `prefetchUse${Name}`,
24
+ prefetchInfinite: `prefetchUse${Name}Infinite`,
25
+ ensureData: `ensureUse${Name}Data`,
26
+ };
27
+ }
28
+ /** The names the hook files declare for an operation. */
29
+ export function hookNames(op) {
30
+ return op.names ?? defaultHookNames(op);
31
+ }
32
+ /** The files `index.ts` re-exports, which therefore share their names. */
33
+ const INDEX_FILES = [
34
+ OpenApiRqFiles.common,
35
+ OpenApiRqFiles.queries,
36
+ OpenApiRqFiles.queryOptions,
37
+ ];
38
+ /**
39
+ * Find the names that cannot stay as they are spelled, given the files built
40
+ * with those names, and give each a number.
41
+ *
42
+ * A name has to differ from what its file imports (an SDK function, a model, a
43
+ * fixed name such as `useQuery`) and from the other names declared in the
44
+ * file, or in any file `index.ts` re-exports next to it. The specification's
45
+ * names always stay: `getUserOptions` is the operation of that name, and the
46
+ * options of `getUser` become `getUserOptions2`. Between two derived names the
47
+ * later one gives way, and `common.ts` comes last, so that a hook keeps its
48
+ * name before a key does (`useGetApiKey` is the hook of `getApiKey`, not the
49
+ * key of `getApi`).
50
+ *
51
+ * Returns nothing when every name can stay, which is the usual case.
52
+ */
53
+ export function settleHookNames(files) {
54
+ const settled = new Map();
55
+ const exported = new Set();
56
+ const inOrder = [
57
+ ...files.filter(([name]) => name !== OpenApiRqFiles.common),
58
+ ...files.filter(([name]) => name === OpenApiRqFiles.common),
59
+ ];
60
+ for (const [file, declared] of inOrder) {
61
+ const imported = new Set(FIXED_IMPORT_NAMES);
62
+ for (const { statement } of declared) {
63
+ if (statement.service)
64
+ imported.add(statement.service);
65
+ for (const model of statement.models ?? [])
66
+ imported.add(model);
67
+ }
68
+ const local = INDEX_FILES.includes(file) ? exported : new Set();
69
+ for (const { op, statement } of declared) {
70
+ const name = uniqueName(statement.name, local, imported);
71
+ if (name === statement.name)
72
+ continue;
73
+ const names = settled.get(op) ?? { ...hookNames(op) };
74
+ for (const key of Object.keys(names)) {
75
+ if (names[key] === statement.name)
76
+ names[key] = name;
77
+ }
78
+ settled.set(op, names);
79
+ }
80
+ }
81
+ return settled.size > 0 ? settled : undefined;
82
+ }
@@ -1,71 +1,46 @@
1
1
  import type { GenerationContext } from "../types.mjs";
2
- /** One import declaration of a generated file, before unused names are dropped. */
2
+ type NamedImport = {
3
+ name: string;
4
+ isTypeOnly?: boolean;
5
+ };
6
+ /** One import declaration of a generated file. */
3
7
  export type ImportDeclaration = {
4
8
  moduleSpecifier: string;
5
9
  /** `import type { … }` */
6
10
  isTypeOnly?: boolean;
7
11
  /** `import * as Name` */
8
12
  namespaceImport?: string;
9
- namedImports?: Array<{
10
- name: string;
11
- isTypeOnly?: boolean;
12
- }>;
13
+ namedImports?: NamedImport[];
13
14
  };
14
15
  /**
15
16
  * A relative module specifier, with the extension the consuming project's
16
17
  * module resolution asks for.
17
18
  */
18
19
  export declare function relativeModule(path: string, ctx?: Pick<GenerationContext, "importExtension">): string;
20
+ /** What the builders use from TanStack Query. */
21
+ export declare const TANSTACK_IMPORTS: NamedImport[];
19
22
  /**
20
- * Build import structure for the Options type.
21
- * sdk.gen re-exports Options extended with `client` and `meta`, which the
22
- * base client Options lacks; hooks must accept those properties.
23
- */
24
- export declare function buildClientImport(ctx: GenerationContext): ImportDeclaration;
25
- /**
26
- * Build import structure for TanStack Query.
27
- */
28
- export declare function buildQueryImport(): ImportDeclaration;
29
- /**
30
- * Build import structure for the queryOptions/infiniteQueryOptions helpers.
31
- */
32
- export declare function buildQueryOptionsImport(): ImportDeclaration;
33
- /**
34
- * Build import structure for services.
35
- */
36
- export declare function buildServiceImport(ctx: GenerationContext): ImportDeclaration;
37
- /**
38
- * Build import structure for models.
39
- * Emitted as a type-only import so generated code compiles under
40
- * `verbatimModuleSyntax` (enabled by default in recent Vite templates).
41
- */
42
- export declare function buildModelImport(ctx: GenerationContext): ImportDeclaration | null;
43
- /**
44
- * Build import structure for axios error type.
45
- */
46
- export declare function buildAxiosErrorImport(): ImportDeclaration;
47
- /**
48
- * Build import for Common namespace.
49
- */
50
- export declare function buildCommonImport(ctx?: Pick<GenerationContext, "importExtension">): ImportDeclaration;
51
- /**
52
- * Build all imports needed for the common file.
53
- */
54
- export declare function buildCommonFileImports(ctx: GenerationContext): ImportDeclaration[];
55
- /**
56
- * Build all imports needed for hook files (queries, suspense, infinite).
23
+ * Every fixed name a generated file can import. A name the hooks derive from
24
+ * an operation gives way to these, as the names of the client do.
57
25
  */
58
- export declare function buildHookFileImports(ctx: GenerationContext): ImportDeclaration[];
26
+ export declare const FIXED_IMPORT_NAMES: readonly string[];
59
27
  /**
60
- * Build all imports needed for the queryOptions file.
61
- * Narrower than the hook file imports: queryOptions only needs the
62
- * queryOptions/infiniteQueryOptions helpers, not the TanStack hooks.
28
+ * The imports of a generated file.
29
+ *
30
+ * `services` and `models` are what the file's statements declare. Everything
31
+ * else is a fixed name the builders write themselves, kept when `mentioned`
32
+ * holds it: the client generator reserves these names, so no model, service or
33
+ * local of the generated code can be called the same.
63
34
  */
64
- export declare function buildQueryOptionsFileImports(ctx: GenerationContext): ImportDeclaration[];
35
+ export declare function buildFileImports(ctx: Pick<GenerationContext, "importExtension">, { services, models, mentioned, }: {
36
+ services: string[];
37
+ models: string[];
38
+ mentioned: ReadonlySet<string>;
39
+ }): ImportDeclaration[];
65
40
  /**
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.
41
+ * Print an import block: packages before relative modules, and both the
42
+ * modules and the names within a declaration in alphabetical order regardless
43
+ * of case. A declaration without names is left out.
70
44
  */
71
- export declare function printImports(declarations: ImportDeclaration[], used: ReadonlySet<string>): string;
45
+ export declare function printImports(declarations: ImportDeclaration[]): string;
46
+ export {};
@@ -5,141 +5,80 @@
5
5
  export function relativeModule(path, ctx) {
6
6
  return `${path}${ctx?.importExtension ?? ""}`;
7
7
  }
8
+ /** What the builders use from TanStack Query. */
9
+ export const TANSTACK_IMPORTS = [
10
+ { name: "useQuery" },
11
+ { name: "useSuspenseQuery" },
12
+ { name: "useInfiniteQuery" },
13
+ { name: "useSuspenseInfiniteQuery" },
14
+ { name: "useMutation" },
15
+ { name: "queryOptions" },
16
+ { name: "infiniteQueryOptions" },
17
+ { name: "QueryClient", isTypeOnly: true },
18
+ { name: "UseQueryResult", isTypeOnly: true },
19
+ { name: "UseQueryOptions", isTypeOnly: true },
20
+ { name: "UseInfiniteQueryOptions", isTypeOnly: true },
21
+ { name: "UseSuspenseInfiniteQueryOptions", isTypeOnly: true },
22
+ { name: "UseMutationOptions", isTypeOnly: true },
23
+ { name: "UseSuspenseQueryOptions", isTypeOnly: true },
24
+ { name: "InfiniteData", isTypeOnly: true },
25
+ { name: "FetchQueryOptions", isTypeOnly: true },
26
+ { name: "FetchInfiniteQueryOptions", isTypeOnly: true },
27
+ { name: "GetNextPageParamFunction", isTypeOnly: true },
28
+ { name: "EnsureQueryDataOptions", isTypeOnly: true },
29
+ ];
8
30
  /**
9
- * Build import structure for the Options type.
10
- * sdk.gen re-exports Options extended with `client` and `meta`, which the
11
- * base client Options lacks; hooks must accept those properties.
31
+ * Every fixed name a generated file can import. A name the hooks derive from
32
+ * an operation gives way to these, as the names of the client do.
12
33
  */
13
- export function buildClientImport(ctx) {
14
- return {
15
- moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
16
- namedImports: [{ name: "Options", isTypeOnly: true }],
17
- };
18
- }
19
- /**
20
- * Build import structure for TanStack Query.
21
- */
22
- export function buildQueryImport() {
23
- return {
24
- moduleSpecifier: "@tanstack/react-query",
25
- namedImports: [
26
- { name: "QueryClient", isTypeOnly: true },
27
- { name: "useQuery" },
28
- { name: "useSuspenseQuery" },
29
- { name: "useInfiniteQuery" },
30
- { name: "useSuspenseInfiniteQuery" },
31
- { name: "useMutation" },
32
- { name: "UseQueryResult", isTypeOnly: true },
33
- { name: "UseQueryOptions", isTypeOnly: true },
34
- { name: "UseInfiniteQueryOptions", isTypeOnly: true },
35
- { name: "UseSuspenseInfiniteQueryOptions", isTypeOnly: true },
36
- { name: "UseMutationOptions", isTypeOnly: true },
37
- { name: "UseMutationResult", isTypeOnly: true },
38
- { name: "UseSuspenseQueryOptions", isTypeOnly: true },
39
- { name: "InfiniteData", isTypeOnly: true },
40
- { name: "FetchQueryOptions", isTypeOnly: true },
41
- { name: "FetchInfiniteQueryOptions", isTypeOnly: true },
42
- { name: "GetNextPageParamFunction", isTypeOnly: true },
43
- { name: "EnsureQueryDataOptions", isTypeOnly: true },
44
- ],
45
- };
46
- }
47
- /**
48
- * Build import structure for the queryOptions/infiniteQueryOptions helpers.
49
- */
50
- export function buildQueryOptionsImport() {
51
- return {
52
- moduleSpecifier: "@tanstack/react-query",
53
- namedImports: [
54
- { name: "queryOptions" },
55
- { name: "infiniteQueryOptions" },
56
- { name: "UseInfiniteQueryOptions", isTypeOnly: true },
57
- ],
58
- };
59
- }
60
- /**
61
- * Build import structure for services.
62
- */
63
- export function buildServiceImport(ctx) {
64
- return {
65
- moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
66
- namedImports: ctx.serviceNames.map((name) => ({ name })),
67
- };
68
- }
69
- /**
70
- * Build import structure for models.
71
- * Emitted as a type-only import so generated code compiles under
72
- * `verbatimModuleSyntax` (enabled by default in recent Vite templates).
73
- */
74
- export function buildModelImport(ctx) {
75
- if (ctx.modelNames.length === 0) {
76
- return null;
77
- }
78
- return {
79
- moduleSpecifier: relativeModule("../requests/types.gen", ctx),
80
- isTypeOnly: true,
81
- namedImports: ctx.modelNames.map((name) => ({ name })),
82
- };
83
- }
84
- /**
85
- * Build import structure for axios error type.
86
- */
87
- export function buildAxiosErrorImport() {
88
- return {
89
- moduleSpecifier: "axios",
90
- namedImports: [{ name: "AxiosError" }],
91
- };
92
- }
93
- /**
94
- * Build import for Common namespace.
95
- */
96
- export function buildCommonImport(ctx) {
97
- return {
98
- moduleSpecifier: relativeModule("./common", ctx),
99
- namespaceImport: "Common",
100
- };
101
- }
34
+ export const FIXED_IMPORT_NAMES = [
35
+ ...TANSTACK_IMPORTS.map(({ name }) => name),
36
+ "AxiosError",
37
+ "Options",
38
+ "Common",
39
+ ];
102
40
  /**
103
- * Build all imports needed for the common file.
41
+ * The imports of a generated file.
42
+ *
43
+ * `services` and `models` are what the file's statements declare. Everything
44
+ * else is a fixed name the builders write themselves, kept when `mentioned`
45
+ * holds it: the client generator reserves these names, so no model, service or
46
+ * local of the generated code can be called the same.
104
47
  */
105
- export function buildCommonFileImports(ctx) {
106
- const imports = [
107
- buildClientImport(ctx),
108
- buildQueryImport(),
109
- buildServiceImport(ctx),
48
+ export function buildFileImports(ctx, { services, models, mentioned, }) {
49
+ const isMentioned = ({ name }) => mentioned.has(name);
50
+ const declarations = [
51
+ {
52
+ moduleSpecifier: "@tanstack/react-query",
53
+ namedImports: TANSTACK_IMPORTS.filter(isMentioned),
54
+ },
55
+ {
56
+ moduleSpecifier: "axios",
57
+ namedImports: [{ name: "AxiosError" }].filter(isMentioned),
58
+ },
59
+ {
60
+ // `Options` is the one sdk.gen re-exports: it adds `client` and `meta`
61
+ // to the Options of the runtime, and the hooks accept both.
62
+ moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
63
+ namedImports: [
64
+ ...[{ name: "Options", isTypeOnly: true }].filter(isMentioned),
65
+ ...services.map((name) => ({ name })),
66
+ ],
67
+ },
68
+ {
69
+ // Type-only, so the output compiles under `verbatimModuleSyntax`.
70
+ moduleSpecifier: relativeModule("../requests/types.gen", ctx),
71
+ isTypeOnly: true,
72
+ namedImports: models.map((name) => ({ name })),
73
+ },
110
74
  ];
111
- const modelImport = buildModelImport(ctx);
112
- if (modelImport) {
113
- imports.push(modelImport);
114
- }
115
- if (ctx.client === "axios") {
116
- imports.push(buildAxiosErrorImport());
75
+ if (mentioned.has("Common")) {
76
+ declarations.push({
77
+ moduleSpecifier: relativeModule("./common", ctx),
78
+ namespaceImport: "Common",
79
+ });
117
80
  }
118
- return imports;
119
- }
120
- /**
121
- * Build all imports needed for hook files (queries, suspense, infinite).
122
- */
123
- export function buildHookFileImports(ctx) {
124
- return [buildCommonImport(ctx), ...buildCommonFileImports(ctx)];
125
- }
126
- /**
127
- * Build all imports needed for the queryOptions file.
128
- * Narrower than the hook file imports: queryOptions only needs the
129
- * queryOptions/infiniteQueryOptions helpers, not the TanStack hooks.
130
- */
131
- export function buildQueryOptionsFileImports(ctx) {
132
- const imports = [
133
- buildCommonImport(ctx),
134
- buildQueryOptionsImport(),
135
- buildClientImport(ctx),
136
- buildServiceImport(ctx),
137
- ];
138
- const modelImport = buildModelImport(ctx);
139
- if (modelImport) {
140
- imports.push(modelImport);
141
- }
142
- return imports;
81
+ return declarations;
143
82
  }
144
83
  function compareCaseInsensitive(a, b) {
145
84
  const lowerA = a.toLowerCase();
@@ -149,49 +88,28 @@ function compareCaseInsensitive(a, b) {
149
88
  function isRelative(moduleSpecifier) {
150
89
  return moduleSpecifier.startsWith(".");
151
90
  }
152
- function printImport(declaration, names) {
91
+ function printImport(declaration) {
153
92
  const from = `from "${declaration.moduleSpecifier}";\n`;
154
93
  if (declaration.namespaceImport) {
155
94
  return `import * as ${declaration.namespaceImport} ${from}`;
156
95
  }
157
- const list = names
158
- .sort((a, b) => compareCaseInsensitive(a.name, b.name))
96
+ const names = (declaration.namedImports ?? [])
97
+ .toSorted((a, b) => compareCaseInsensitive(a.name, b.name))
159
98
  .map(({ name, isTypeOnly }) => (isTypeOnly ? `type ${name}` : name))
160
99
  .join(", ");
161
- return `import ${declaration.isTypeOnly ? "type " : ""}{ ${list} } ${from}`;
100
+ return `import ${declaration.isTypeOnly ? "type " : ""}{ ${names} } ${from}`;
162
101
  }
163
102
  /**
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.
103
+ * Print an import block: packages before relative modules, and both the
104
+ * modules and the names within a declaration in alphabetical order regardless
105
+ * of case. A declaration without names is left out.
168
106
  */
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()]))
107
+ export function printImports(declarations) {
108
+ return declarations
109
+ .filter((declaration) => declaration.namespaceImport || declaration.namedImports?.length)
110
+ .toSorted((a, b) => Number(isRelative(a.moduleSpecifier)) -
111
+ Number(isRelative(b.moduleSpecifier)) ||
112
+ compareCaseInsensitive(a.moduleSpecifier, b.moduleSpecifier))
113
+ .map(printImport)
196
114
  .join("");
197
115
  }
@@ -1,5 +1,15 @@
1
1
  import type { GenerationContext, OperationInfo } from "../types.mjs";
2
+ import type { ConstStatement } from "./statement.mjs";
2
3
  /** The generated Data type name, or unknown when there is none. */
3
4
  export declare function getDataTypeName(op: OperationInfo): string;
4
5
  /** The error type of an operation's hooks, wrapped for axios. */
5
6
  export declare function getErrorType(op: OperationInfo, ctx: GenerationContext): string;
7
+ /** The model `getDataTypeName` names, for a statement's `models`. */
8
+ export declare function dataModels(op: OperationInfo): string[];
9
+ /** The model `getErrorType` names, for a statement's `models`. */
10
+ export declare function errorModels(op: OperationInfo): string[];
11
+ /**
12
+ * A `const` that calls the operation's SDK function. It carries the JSDoc
13
+ * (description and `@deprecated`) the SDK function has.
14
+ */
15
+ export declare function operationConst(op: OperationInfo, name: string, initializer: string, models: string[]): ConstStatement;
@@ -7,3 +7,25 @@ export function getErrorType(op, ctx) {
7
7
  const errorType = op.errorTypeName ?? "unknown";
8
8
  return ctx.client === "axios" ? `AxiosError<${errorType}>` : errorType;
9
9
  }
10
+ /** The model `getDataTypeName` names, for a statement's `models`. */
11
+ export function dataModels(op) {
12
+ return op.dataTypeName ? [op.dataTypeName] : [];
13
+ }
14
+ /** The model `getErrorType` names, for a statement's `models`. */
15
+ export function errorModels(op) {
16
+ return op.errorTypeName ? [op.errorTypeName] : [];
17
+ }
18
+ /**
19
+ * A `const` that calls the operation's SDK function. It carries the JSDoc
20
+ * (description and `@deprecated`) the SDK function has.
21
+ */
22
+ export function operationConst(op, name, initializer, models) {
23
+ return {
24
+ kind: "const",
25
+ jsDoc: op.jsDoc,
26
+ name,
27
+ initializer,
28
+ service: op.methodName,
29
+ models,
30
+ };
31
+ }
@@ -1,5 +1,12 @@
1
+ /** What a statement's code needs imported from the generated client. */
2
+ type References = {
3
+ /** The SDK function the code calls or takes the type of. */
4
+ service?: string;
5
+ /** The types from `types.gen` the code names. */
6
+ models?: string[];
7
+ };
1
8
  /** An exported `const` of a generated file. */
2
- export type ConstStatement = {
9
+ export type ConstStatement = References & {
3
10
  kind: "const";
4
11
  name: string;
5
12
  /** The expression after `=`. */
@@ -8,7 +15,7 @@ export type ConstStatement = {
8
15
  jsDoc?: string;
9
16
  };
10
17
  /** An exported type alias of a generated file. */
11
- export type TypeStatement = {
18
+ export type TypeStatement = References & {
12
19
  kind: "type";
13
20
  name: string;
14
21
  typeParameters?: Array<{
@@ -26,9 +33,11 @@ export declare function statementCode(statement: Statement): string;
26
33
  */
27
34
  export declare function printStatements(statements: Statement[]): string;
28
35
  /**
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)`).
36
+ * The identifiers a piece of generated code mentions. Some places hold a name
37
+ * without referring to anything a file could import, and are left out: a
38
+ * comment, a string literal, the name after the dot of a member access, and
39
+ * the key of a property or the name of a parameter (`{ page: 1 }`,
40
+ * `(options?: T)`).
33
41
  */
34
42
  export declare function referencedNames(code: string): Set<string>;
43
+ export {};
@@ -27,29 +27,34 @@ export function printStatements(statements) {
27
27
  });
28
28
  return text;
29
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. */
30
+ // A comment, a string literal, a spread, a member access, an identifier (the
31
+ // one group), or any other character. The last only matters as what precedes
32
+ // an identifier.
33
+ const TOKEN = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`|\.\.\.|\.\s*[\p{ID_Start}_$][\p{ID_Continue}$]*|([\p{ID_Start}_$][\p{ID_Continue}$]*)|\S/gu;
34
+ /** What precedes the key of a property or the name of a parameter. */
35
+ const KEY_START = new Set(["{", ",", "(", ";"]);
36
+ /** What follows one. */
35
37
  const KEY_END = /\s*\??:/y;
36
38
  /**
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)`).
39
+ * The identifiers a piece of generated code mentions. Some places hold a name
40
+ * without referring to anything a file could import, and are left out: a
41
+ * comment, a string literal, the name after the dot of a member access, and
42
+ * the key of a property or the name of a parameter (`{ page: 1 }`,
43
+ * `(options?: T)`).
41
44
  */
42
45
  export function referencedNames(code) {
43
46
  const names = new Set();
44
47
  let previous = "";
45
48
  for (const match of code.matchAll(TOKEN)) {
46
- const [token] = match;
47
- if (IDENTIFIER_START.test(token)) {
49
+ const [token, identifier] = match;
50
+ if (token.startsWith("/*") || token.startsWith("//")) {
51
+ continue;
52
+ }
53
+ if (identifier !== undefined) {
48
54
  KEY_END.lastIndex = match.index + token.length;
49
- const isKey = (previous === "{" || previous === "," || previous === "(") &&
50
- KEY_END.test(code);
55
+ const isKey = KEY_START.has(previous) && KEY_END.test(code);
51
56
  if (!isKey) {
52
- names.add(token);
57
+ names.add(identifier);
53
58
  }
54
59
  }
55
60
  previous = token;
package/dist/types.d.mts CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Normalized operation information extracted from the OpenAPI service.
3
- * This is a pure JSON-serializable structure that can be consumed by generators.
2
+ * What the hook generators know about an operation. The client generator
3
+ * (`src/client/`) fills it in; it is plain JSON-serializable data.
4
4
  */
5
5
  export interface OperationInfo {
6
- /** Method/function name as defined in service (e.g., "findPets") */
6
+ /** Name of the operation's function in `sdk.gen.ts` (e.g., "findPets") */
7
7
  methodName: string;
8
8
  /** Capitalized method name (e.g., "FindPets") */
9
9
  capitalizedMethodName: string;
@@ -26,6 +26,8 @@ export interface OperationInfo {
26
26
  isPaginatable: boolean;
27
27
  /** Type of the configured page query parameter */
28
28
  pageParamType?: string;
29
+ /** Models `pageParamType` names, which the hooks have to import */
30
+ pageParamModels?: string[];
29
31
  /** Resolved primitive kind of the configured page query parameter */
30
32
  pageParamTypeKind?: PageParamTypeKind;
31
33
  }
@@ -37,10 +39,6 @@ export type PageParamTypeKind = "string" | "number" | "other";
37
39
  export interface GenerationContext {
38
40
  /** Client type: "fetch" or "axios" */
39
41
  client: "fetch" | "axios";
40
- /** Model type names exported from the models file */
41
- modelNames: string[];
42
- /** Service function names exported from the service file */
43
- serviceNames: string[];
44
42
  /** Page param name for infinite queries (e.g., "page") */
45
43
  pageParam: string;
46
44
  /** Next page param name for infinite queries (e.g., "nextPage") */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@7nohe/openapi-react-query-codegen",
3
- "version": "4.0.0-beta.4",
3
+ "version": "4.0.0-beta.5",
4
4
  "description": "OpenAPI React Query Codegen",
5
5
  "bin": {
6
6
  "openapi-rq": "dist/cli.mjs"
@@ -1,4 +0,0 @@
1
- export * from "./buildCommon.mjs";
2
- export * from "./buildMutationHooks.mjs";
3
- export * from "./buildQueryHooks.mjs";
4
- export { generateAllFiles } from "./generateFiles.mjs";
@@ -1,4 +0,0 @@
1
- export * from "./buildCommon.mjs";
2
- export * from "./buildMutationHooks.mjs";
3
- export * from "./buildQueryHooks.mjs";
4
- export { generateAllFiles } from "./generateFiles.mjs";
package/dist/print.d.mts DELETED
@@ -1,5 +0,0 @@
1
- import type { LimitedUserConfig } from "./cli.mjs";
2
- export declare function print(results: {
3
- name: string;
4
- content: string;
5
- }[], options: Pick<LimitedUserConfig, "output">): Promise<void>;