nuxt-openapi-hyperfetch 0.1.0-alpha.1
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/.editorconfig +26 -0
- package/.prettierignore +17 -0
- package/.prettierrc.json +12 -0
- package/CONTRIBUTING.md +292 -0
- package/INSTRUCTIONS.md +327 -0
- package/LICENSE +202 -0
- package/README.md +202 -0
- package/dist/cli/config.d.ts +57 -0
- package/dist/cli/config.js +85 -0
- package/dist/cli/logger.d.ts +44 -0
- package/dist/cli/logger.js +58 -0
- package/dist/cli/logo.d.ts +6 -0
- package/dist/cli/logo.js +21 -0
- package/dist/cli/messages.d.ts +65 -0
- package/dist/cli/messages.js +86 -0
- package/dist/cli/prompts.d.ts +30 -0
- package/dist/cli/prompts.js +118 -0
- package/dist/cli/types.d.ts +43 -0
- package/dist/cli/types.js +4 -0
- package/dist/cli/utils.d.ts +26 -0
- package/dist/cli/utils.js +45 -0
- package/dist/generate.d.ts +6 -0
- package/dist/generate.js +48 -0
- package/dist/generators/nuxt-server/bff-templates.d.ts +25 -0
- package/dist/generators/nuxt-server/bff-templates.js +737 -0
- package/dist/generators/nuxt-server/generator.d.ts +7 -0
- package/dist/generators/nuxt-server/generator.js +206 -0
- package/dist/generators/nuxt-server/parser.d.ts +5 -0
- package/dist/generators/nuxt-server/parser.js +5 -0
- package/dist/generators/nuxt-server/templates.d.ts +35 -0
- package/dist/generators/nuxt-server/templates.js +412 -0
- package/dist/generators/nuxt-server/types.d.ts +5 -0
- package/dist/generators/nuxt-server/types.js +5 -0
- package/dist/generators/shared/parsers/heyapi-parser.d.ts +11 -0
- package/dist/generators/shared/parsers/heyapi-parser.js +248 -0
- package/dist/generators/shared/parsers/official-parser.d.ts +5 -0
- package/dist/generators/shared/parsers/official-parser.js +5 -0
- package/dist/generators/shared/runtime/apiHelpers.d.ts +183 -0
- package/dist/generators/shared/runtime/apiHelpers.js +268 -0
- package/dist/generators/shared/templates/api-callbacks-plugin.d.ts +178 -0
- package/dist/generators/shared/templates/api-callbacks-plugin.js +338 -0
- package/dist/generators/shared/types.d.ts +25 -0
- package/dist/generators/shared/types.js +4 -0
- package/dist/generators/tanstack-query/generator.d.ts +5 -0
- package/dist/generators/tanstack-query/generator.js +11 -0
- package/dist/generators/use-async-data/generator.d.ts +5 -0
- package/dist/generators/use-async-data/generator.js +156 -0
- package/dist/generators/use-async-data/parser.d.ts +5 -0
- package/dist/generators/use-async-data/parser.js +5 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncData.d.ts +38 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncData.js +122 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.d.ts +54 -0
- package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.js +126 -0
- package/dist/generators/use-async-data/templates.d.ts +20 -0
- package/dist/generators/use-async-data/templates.js +191 -0
- package/dist/generators/use-async-data/types.d.ts +4 -0
- package/dist/generators/use-async-data/types.js +4 -0
- package/dist/generators/use-fetch/generator.d.ts +5 -0
- package/dist/generators/use-fetch/generator.js +131 -0
- package/dist/generators/use-fetch/parser.d.ts +9 -0
- package/dist/generators/use-fetch/parser.js +282 -0
- package/dist/generators/use-fetch/runtime/useApiRequest.d.ts +46 -0
- package/dist/generators/use-fetch/runtime/useApiRequest.js +158 -0
- package/dist/generators/use-fetch/templates.d.ts +16 -0
- package/dist/generators/use-fetch/templates.js +169 -0
- package/dist/generators/use-fetch/types.d.ts +5 -0
- package/dist/generators/use-fetch/types.js +5 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +213 -0
- package/docs/API-REFERENCE.md +887 -0
- package/docs/ARCHITECTURE.md +649 -0
- package/docs/DEVELOPMENT.md +918 -0
- package/docs/QUICK-START.md +323 -0
- package/docs/README.md +155 -0
- package/docs/TROUBLESHOOTING.md +881 -0
- package/eslint.config.js +72 -0
- package/package.json +65 -0
- package/src/cli/config.ts +140 -0
- package/src/cli/logger.ts +66 -0
- package/src/cli/logo.ts +25 -0
- package/src/cli/messages.ts +97 -0
- package/src/cli/prompts.ts +143 -0
- package/src/cli/types.ts +50 -0
- package/src/cli/utils.ts +49 -0
- package/src/generate.ts +57 -0
- package/src/generators/nuxt-server/bff-templates.ts +754 -0
- package/src/generators/nuxt-server/generator.ts +270 -0
- package/src/generators/nuxt-server/parser.ts +5 -0
- package/src/generators/nuxt-server/templates.ts +483 -0
- package/src/generators/nuxt-server/types.ts +5 -0
- package/src/generators/shared/parsers/heyapi-parser.ts +307 -0
- package/src/generators/shared/parsers/official-parser.ts +5 -0
- package/src/generators/shared/runtime/apiHelpers.ts +466 -0
- package/src/generators/shared/templates/api-callbacks-plugin.ts +352 -0
- package/src/generators/shared/types.ts +27 -0
- package/src/generators/tanstack-query/generator.ts +11 -0
- package/src/generators/use-async-data/generator.ts +204 -0
- package/src/generators/use-async-data/parser.ts +5 -0
- package/src/generators/use-async-data/runtime/useApiAsyncData.ts +220 -0
- package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +236 -0
- package/src/generators/use-async-data/templates.ts +250 -0
- package/src/generators/use-async-data/types.ts +4 -0
- package/src/generators/use-fetch/generator.ts +169 -0
- package/src/generators/use-fetch/parser.ts +341 -0
- package/src/generators/use-fetch/runtime/useApiRequest.ts +223 -0
- package/src/generators/use-fetch/templates.ts +214 -0
- package/src/generators/use-fetch/types.ts +5 -0
- package/src/index.ts +265 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Nuxt Runtime Helper - This file is copied to the generated output
|
|
4
|
+
* It requires Nuxt 3 to be installed in the target project
|
|
5
|
+
*/
|
|
6
|
+
import { watch } from 'vue';
|
|
7
|
+
import {
|
|
8
|
+
getGlobalHeaders,
|
|
9
|
+
applyPick,
|
|
10
|
+
applyRequestModifications,
|
|
11
|
+
mergeCallbacks,
|
|
12
|
+
type RequestContext,
|
|
13
|
+
type ModifiedRequestContext,
|
|
14
|
+
type FinishContext,
|
|
15
|
+
type ApiRequestOptions as BaseApiRequestOptions,
|
|
16
|
+
} from '../../shared/runtime/apiHelpers.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Helper type to infer transformed data type
|
|
20
|
+
* If transform is provided, infer its return type
|
|
21
|
+
* If pick is provided, return partial object (type inference for nested paths is complex)
|
|
22
|
+
* Otherwise, return original type
|
|
23
|
+
*/
|
|
24
|
+
type MaybeTransformed<T, Options> = Options extends { transform: (...args: any) => infer R }
|
|
25
|
+
? R
|
|
26
|
+
: Options extends { pick: ReadonlyArray<any> }
|
|
27
|
+
? any // With nested paths, type inference is complex, so we use any
|
|
28
|
+
: T;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Options for useFetch API requests with lifecycle callbacks
|
|
32
|
+
* Extends base options with useFetch-specific options
|
|
33
|
+
*/
|
|
34
|
+
export interface ApiRequestOptions<T = any> extends BaseApiRequestOptions<T> {
|
|
35
|
+
/** All standard useFetch options */
|
|
36
|
+
[key: string]: any;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Enhanced useFetch wrapper with lifecycle callbacks and request interception
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* // Basic usage
|
|
45
|
+
* const { data, error } = useApiRequest<Pet>('/api/pets', {
|
|
46
|
+
* method: 'POST',
|
|
47
|
+
* body: { name: 'Max' },
|
|
48
|
+
* });
|
|
49
|
+
*
|
|
50
|
+
* // With transform (type is inferred!)
|
|
51
|
+
* const { data } = useApiRequest<Pet>('/api/pets/1', {
|
|
52
|
+
* transform: (pet) => ({ displayName: pet.name, available: pet.status === 'available' })
|
|
53
|
+
* });
|
|
54
|
+
* // data is Ref<{ displayName: string, available: boolean }>
|
|
55
|
+
*
|
|
56
|
+
* // With pick (simple fields)
|
|
57
|
+
* const { data } = useApiRequest<Pet>('/api/pets/1', {
|
|
58
|
+
* pick: ['id', 'name'] as const
|
|
59
|
+
* });
|
|
60
|
+
*
|
|
61
|
+
* // With pick (nested dot notation)
|
|
62
|
+
* const { data } = useApiRequest('/api/user', {
|
|
63
|
+
* pick: ['person.name', 'person.email', 'status']
|
|
64
|
+
* });
|
|
65
|
+
* // Result: { person: { name: '...', email: '...' }, status: '...' }
|
|
66
|
+
*
|
|
67
|
+
* // With callbacks
|
|
68
|
+
* const { data } = useApiRequest<Pet>('/api/pets', {
|
|
69
|
+
* onRequest: (ctx) => ({ headers: { 'Authorization': `Bearer ${token}` } }),
|
|
70
|
+
* onSuccess: (pet) => console.log('Got pet:', pet),
|
|
71
|
+
* onError: (err) => console.error('Failed:', err),
|
|
72
|
+
* });
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export function useApiRequest<T = any, Options extends ApiRequestOptions<T> = ApiRequestOptions<T>>(
|
|
76
|
+
url: string | (() => string),
|
|
77
|
+
options?: Options
|
|
78
|
+
) {
|
|
79
|
+
const {
|
|
80
|
+
onRequest,
|
|
81
|
+
onSuccess,
|
|
82
|
+
onError,
|
|
83
|
+
onFinish,
|
|
84
|
+
skipGlobalCallbacks,
|
|
85
|
+
transform,
|
|
86
|
+
pick,
|
|
87
|
+
...fetchOptions
|
|
88
|
+
} = options || {};
|
|
89
|
+
|
|
90
|
+
// Prepare request context for onRequest interceptor
|
|
91
|
+
const urlValue = typeof url === 'function' ? url() : url;
|
|
92
|
+
const requestContext: RequestContext = {
|
|
93
|
+
url: urlValue,
|
|
94
|
+
method: fetchOptions.method || 'GET',
|
|
95
|
+
body: fetchOptions.body,
|
|
96
|
+
headers: fetchOptions.headers,
|
|
97
|
+
query: fetchOptions.query,
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// Merge local and global callbacks
|
|
101
|
+
const mergedCallbacks = mergeCallbacks(
|
|
102
|
+
urlValue,
|
|
103
|
+
{ onRequest, onSuccess, onError, onFinish },
|
|
104
|
+
skipGlobalCallbacks
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
// Apply global headers configuration (from composable or plugin)
|
|
108
|
+
const modifiedOptions = { ...fetchOptions };
|
|
109
|
+
const globalHeaders = getGlobalHeaders();
|
|
110
|
+
if (Object.keys(globalHeaders).length > 0) {
|
|
111
|
+
modifiedOptions.headers = {
|
|
112
|
+
...globalHeaders,
|
|
113
|
+
...modifiedOptions.headers, // User headers override global headers
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Execute merged onRequest interceptor and apply modifications
|
|
118
|
+
if (mergedCallbacks.onRequest) {
|
|
119
|
+
try {
|
|
120
|
+
const result = mergedCallbacks.onRequest(requestContext);
|
|
121
|
+
|
|
122
|
+
// Handle async onRequest
|
|
123
|
+
if (result && typeof result === 'object' && 'then' in result) {
|
|
124
|
+
result
|
|
125
|
+
.then((modifications) => {
|
|
126
|
+
if (modifications) {
|
|
127
|
+
applyRequestModifications(modifiedOptions, modifications);
|
|
128
|
+
}
|
|
129
|
+
})
|
|
130
|
+
.catch((error) => {
|
|
131
|
+
console.error('Error in merged onRequest callback:', error);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// Handle sync onRequest with return value
|
|
135
|
+
else if (result && typeof result === 'object') {
|
|
136
|
+
applyRequestModifications(modifiedOptions, result);
|
|
137
|
+
}
|
|
138
|
+
} catch (error) {
|
|
139
|
+
console.error('Error in merged onRequest callback:', error);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Make the actual request using Nuxt's useFetch
|
|
144
|
+
const result = useFetch<T>(url, modifiedOptions);
|
|
145
|
+
|
|
146
|
+
// Create a ref for transformed data
|
|
147
|
+
type TransformedType = MaybeTransformed<T, Options>;
|
|
148
|
+
const transformedData = ref<TransformedType | null>(null);
|
|
149
|
+
|
|
150
|
+
// Track if callbacks have been executed to avoid duplicates
|
|
151
|
+
let successExecuted = false;
|
|
152
|
+
let errorExecuted = false;
|
|
153
|
+
|
|
154
|
+
// Watch for changes in data, error, and pending states
|
|
155
|
+
watch(
|
|
156
|
+
() => [result.data.value, result.error.value, result.pending.value] as const,
|
|
157
|
+
async ([data, error, pending], [prevData, prevError, prevPending]) => {
|
|
158
|
+
// Apply transformations when data arrives
|
|
159
|
+
if (data && data !== prevData) {
|
|
160
|
+
let processedData: any = data;
|
|
161
|
+
|
|
162
|
+
// Step 1: Apply pick if specified
|
|
163
|
+
if (pick) {
|
|
164
|
+
processedData = applyPick(processedData, pick);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Step 2: Apply transform if specified
|
|
168
|
+
if (transform) {
|
|
169
|
+
try {
|
|
170
|
+
processedData = transform(processedData);
|
|
171
|
+
} catch (err) {
|
|
172
|
+
console.error('Error in transform function:', err);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Update transformed data ref
|
|
177
|
+
transformedData.value = processedData as TransformedType;
|
|
178
|
+
|
|
179
|
+
// onSuccess - when data arrives and no error (using merged callback)
|
|
180
|
+
if (!error && !successExecuted && mergedCallbacks.onSuccess) {
|
|
181
|
+
successExecuted = true;
|
|
182
|
+
try {
|
|
183
|
+
await mergedCallbacks.onSuccess(processedData);
|
|
184
|
+
} catch (err) {
|
|
185
|
+
console.error('Error in merged onSuccess callback:', err);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// onError - when an error occurs (using merged callback)
|
|
191
|
+
if (error && error !== prevError && !errorExecuted && mergedCallbacks.onError) {
|
|
192
|
+
errorExecuted = true;
|
|
193
|
+
try {
|
|
194
|
+
await mergedCallbacks.onError(error);
|
|
195
|
+
} catch (err) {
|
|
196
|
+
console.error('Error in merged onError callback:', err);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// onFinish - when request completes (was pending, now not) (using merged callback)
|
|
201
|
+
if (prevPending && !pending && mergedCallbacks.onFinish) {
|
|
202
|
+
const finishContext: FinishContext<TransformedType> = {
|
|
203
|
+
data: transformedData.value || undefined,
|
|
204
|
+
error: error || undefined,
|
|
205
|
+
success: !!transformedData.value && !error,
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
await mergedCallbacks.onFinish(finishContext);
|
|
210
|
+
} catch (err) {
|
|
211
|
+
console.error('Error in merged onFinish callback:', err);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
{ immediate: true }
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
// Return result with transformed data
|
|
219
|
+
return {
|
|
220
|
+
...result,
|
|
221
|
+
data: transformedData as Ref<TransformedType | null>,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import type { MethodInfo } from './types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Generate file header with auto-generation warning
|
|
5
|
+
*/
|
|
6
|
+
function generateFileHeader(): string {
|
|
7
|
+
return `/**
|
|
8
|
+
* ⚠️ AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
|
|
9
|
+
*
|
|
10
|
+
* This file was automatically generated by nuxt-openapi-generator.
|
|
11
|
+
* Any manual changes will be overwritten on the next generation.
|
|
12
|
+
*
|
|
13
|
+
* @generated by nuxt-openapi-generator
|
|
14
|
+
* @see https://github.com/dmartindiaz/nuxt-openapi-hyperfetch
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/* eslint-disable */
|
|
18
|
+
// @ts-nocheck
|
|
19
|
+
`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Options for code generation
|
|
24
|
+
*/
|
|
25
|
+
export interface GenerateOptions {
|
|
26
|
+
baseUrl?: string;
|
|
27
|
+
backend?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Generate a useFetch composable function
|
|
32
|
+
*/
|
|
33
|
+
export function generateComposableFile(
|
|
34
|
+
method: MethodInfo,
|
|
35
|
+
apiImportPath: string,
|
|
36
|
+
options?: GenerateOptions
|
|
37
|
+
): string {
|
|
38
|
+
const header = generateFileHeader();
|
|
39
|
+
const imports = generateImports(method, apiImportPath);
|
|
40
|
+
const functionBody = generateFunctionBody(method, options);
|
|
41
|
+
|
|
42
|
+
return `${header}${imports}\n\n${functionBody}\n`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Extract base type names from a type string
|
|
47
|
+
* Examples:
|
|
48
|
+
* Pet[] -> Pet
|
|
49
|
+
* Array<Pet> -> Pet
|
|
50
|
+
* Pet -> Pet
|
|
51
|
+
* { [key: string]: Pet } -> (empty, it's anonymous)
|
|
52
|
+
*/
|
|
53
|
+
function extractBaseTypes(type: string): string[] {
|
|
54
|
+
if (!type) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Handle array syntax: Pet[]
|
|
59
|
+
const arrayMatch = type.match(/^(\w+)\[\]$/);
|
|
60
|
+
if (arrayMatch) {
|
|
61
|
+
return [arrayMatch[1]];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Handle Array generic: Array<Pet>
|
|
65
|
+
const arrayGenericMatch = type.match(/^Array<(\w+)>$/);
|
|
66
|
+
if (arrayGenericMatch) {
|
|
67
|
+
return [arrayGenericMatch[1]];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// If it's a simple named type (single word, PascalCase), include it
|
|
71
|
+
if (/^[A-Z][a-zA-Z0-9]*$/.test(type)) {
|
|
72
|
+
return [type];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// For complex types, don't extract anything
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Generate import statements
|
|
81
|
+
*/
|
|
82
|
+
function generateImports(method: MethodInfo, apiImportPath: string): string {
|
|
83
|
+
const typeNames = new Set<string>();
|
|
84
|
+
|
|
85
|
+
// Extract base types from request type
|
|
86
|
+
if (method.requestType) {
|
|
87
|
+
const extracted = extractBaseTypes(method.requestType);
|
|
88
|
+
extracted.forEach((t) => typeNames.add(t));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Extract base types from response type
|
|
92
|
+
if (method.responseType && method.responseType !== 'void') {
|
|
93
|
+
const extracted = extractBaseTypes(method.responseType);
|
|
94
|
+
extracted.forEach((t) => typeNames.add(t));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let imports = '';
|
|
98
|
+
|
|
99
|
+
// Import types from API (only if we have named types to import)
|
|
100
|
+
if (typeNames.size > 0) {
|
|
101
|
+
imports += `import type { ${Array.from(typeNames).join(', ')} } from '${apiImportPath}';\n`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Import runtime helper
|
|
105
|
+
imports += `import { useApiRequest, type ApiRequestOptions } from '../runtime/useApiRequest';`;
|
|
106
|
+
|
|
107
|
+
return imports;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Generate the composable function body
|
|
115
|
+
*/
|
|
116
|
+
function generateFunctionBody(method: MethodInfo, options?: GenerateOptions): string {
|
|
117
|
+
const hasParams = !!method.requestType;
|
|
118
|
+
const paramsArg = hasParams ? `params: MaybeRef<${method.requestType}>` : '';
|
|
119
|
+
const optionsType = `ApiRequestOptions<${method.responseType}>`;
|
|
120
|
+
const optionsArg = `options?: ${optionsType}`;
|
|
121
|
+
const args = hasParams ? `${paramsArg}, ${optionsArg}` : optionsArg;
|
|
122
|
+
|
|
123
|
+
const responseTypeGeneric = method.responseType !== 'void' ? `<${method.responseType}>` : '';
|
|
124
|
+
|
|
125
|
+
const url = generateUrl(method);
|
|
126
|
+
const fetchOptions = generateFetchOptions(method, options);
|
|
127
|
+
|
|
128
|
+
const description = method.description ? `/**\n * ${method.description}\n */\n` : '';
|
|
129
|
+
|
|
130
|
+
const pInit = hasParams ? `\n const p = isRef(params) ? params : shallowRef(params)` : '';
|
|
131
|
+
|
|
132
|
+
return `${description}export const ${method.composableName} = (${args}) => {${pInit}
|
|
133
|
+
return useApiRequest${responseTypeGeneric}(${url}, ${fetchOptions})
|
|
134
|
+
}`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Generate URL (with path params if needed)
|
|
139
|
+
*/
|
|
140
|
+
function generateUrl(method: MethodInfo): string {
|
|
141
|
+
if (method.pathParams.length === 0) {
|
|
142
|
+
return `'${method.path}'`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let url = method.path;
|
|
146
|
+
for (const param of method.pathParams) {
|
|
147
|
+
const accessor = method.paramsShape === 'nested' ? `p.value.path.${param}` : `p.value.${param}`;
|
|
148
|
+
url = url.replace(`{${param}}`, `\${${accessor}}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return `() => \`${url}\``;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Generate fetch options object
|
|
156
|
+
*/
|
|
157
|
+
function generateFetchOptions(method: MethodInfo, generateOptions?: GenerateOptions): string {
|
|
158
|
+
const options: string[] = [];
|
|
159
|
+
|
|
160
|
+
// Method
|
|
161
|
+
options.push(`method: '${method.httpMethod}'`);
|
|
162
|
+
|
|
163
|
+
// Base URL (if provided in config)
|
|
164
|
+
if (generateOptions?.baseUrl) {
|
|
165
|
+
options.push(`baseURL: '${generateOptions.baseUrl}'`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Body
|
|
169
|
+
if (method.hasBody) {
|
|
170
|
+
if (method.paramsShape === 'nested') {
|
|
171
|
+
options.push(`body: computed(() => p.value.body)`);
|
|
172
|
+
} else if (method.bodyField) {
|
|
173
|
+
options.push(`body: computed(() => p.value.${method.bodyField})`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Query params
|
|
178
|
+
if (method.hasQueryParams) {
|
|
179
|
+
if (method.paramsShape === 'nested') {
|
|
180
|
+
options.push(`query: computed(() => p.value.query)`);
|
|
181
|
+
} else if (method.queryParams.length > 0) {
|
|
182
|
+
const queryObj = method.queryParams
|
|
183
|
+
.map((param) => `${param}: p.value.${param}`)
|
|
184
|
+
.join(',\n ');
|
|
185
|
+
options.push(`query: computed(() => ({\n ${queryObj}\n }))`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Headers
|
|
190
|
+
if (Object.keys(method.headers).length > 0) {
|
|
191
|
+
const headersEntries = Object.entries(method.headers)
|
|
192
|
+
.map(([key, value]) => `'${key}': '${value}'`)
|
|
193
|
+
.join(',\n ');
|
|
194
|
+
options.push(`headers: {\n ${headersEntries},\n ...options?.headers\n }`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Spread options
|
|
198
|
+
options.push('...options');
|
|
199
|
+
|
|
200
|
+
const optionsStr = options.join(',\n ');
|
|
201
|
+
return `{\n ${optionsStr}\n }`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Generate index.ts that exports all composables
|
|
206
|
+
*/
|
|
207
|
+
export function generateIndexFile(composableNames: string[]): string {
|
|
208
|
+
const header = generateFileHeader();
|
|
209
|
+
const exports = composableNames
|
|
210
|
+
.map((name) => `export { ${name} } from './composables/${name}'`)
|
|
211
|
+
.join('\n');
|
|
212
|
+
|
|
213
|
+
return `${header}${exports}\n`;
|
|
214
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import * as p from '@clack/prompts';
|
|
4
|
+
import { generateOpenApiFiles, generateHeyApiFiles, checkJavaInstalled } from './generate.js';
|
|
5
|
+
import { generateUseFetchComposables } from './generators/use-fetch/generator.js';
|
|
6
|
+
import { generateUseAsyncDataComposables } from './generators/use-async-data/generator.js';
|
|
7
|
+
import { generateNuxtServerRoutes } from './generators/nuxt-server/generator.js';
|
|
8
|
+
import {
|
|
9
|
+
promptInitialInputs,
|
|
10
|
+
promptInputPath,
|
|
11
|
+
promptComposablesSelection,
|
|
12
|
+
promptServerRoutePath,
|
|
13
|
+
promptBffConfig,
|
|
14
|
+
promptGeneratorBackend,
|
|
15
|
+
} from './cli/prompts.js';
|
|
16
|
+
import { MESSAGES } from './cli/messages.js';
|
|
17
|
+
import { displayLogo } from './cli/logo.js';
|
|
18
|
+
import { loadConfig, mergeConfig, parseTags, parseGenerators } from './cli/config.js';
|
|
19
|
+
|
|
20
|
+
const program = new Command();
|
|
21
|
+
|
|
22
|
+
program.name('nxh').description('Nuxt OpenAPI Hyperfetch generator').version('1.0.0');
|
|
23
|
+
|
|
24
|
+
interface GenerateOptions {
|
|
25
|
+
input?: string;
|
|
26
|
+
output?: string;
|
|
27
|
+
baseUrl?: string;
|
|
28
|
+
mode?: 'client' | 'server';
|
|
29
|
+
tags?: string;
|
|
30
|
+
excludeTags?: string;
|
|
31
|
+
overwrite?: boolean;
|
|
32
|
+
dryRun?: boolean;
|
|
33
|
+
verbose?: boolean;
|
|
34
|
+
watch?: boolean;
|
|
35
|
+
generators?: string;
|
|
36
|
+
serverRoutePath?: string;
|
|
37
|
+
enableBff?: boolean;
|
|
38
|
+
backend?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
program
|
|
42
|
+
.command('generate')
|
|
43
|
+
.description('Generate all nuxt files and composables from OpenAPI spec')
|
|
44
|
+
.option('-i, --input <path>', 'OpenAPI file path or URL')
|
|
45
|
+
.option('-o, --output <path>', 'Output directory')
|
|
46
|
+
.option('--base-url <url>', 'Base URL for API requests')
|
|
47
|
+
.option('--mode <mode>', 'Generation mode: client or server', 'client')
|
|
48
|
+
.option('--tags <tags>', 'Generate only specific tags (comma-separated)')
|
|
49
|
+
.option('--exclude-tags <tags>', 'Exclude specific tags (comma-separated)')
|
|
50
|
+
.option('--overwrite', 'Overwrite existing files without prompting', false)
|
|
51
|
+
.option('--dry-run', 'Preview changes without writing files', false)
|
|
52
|
+
.option('-v, --verbose', 'Enable verbose logging', false)
|
|
53
|
+
.option('--watch', 'Watch mode - regenerate on file changes', false)
|
|
54
|
+
.option('--generators <types>', 'Generators to use: useFetch,useAsyncData,nuxtServer')
|
|
55
|
+
.option('--server-route-path <path>', 'Server route path (for nuxtServer mode)')
|
|
56
|
+
.option('--enable-bff', 'Enable BFF pattern (for nuxtServer mode)', false)
|
|
57
|
+
.option('--backend <type>', 'Generator backend: official (Java) or heyapi (Node.js)')
|
|
58
|
+
.action(async (options: GenerateOptions) => {
|
|
59
|
+
try {
|
|
60
|
+
// Load config file
|
|
61
|
+
const fileConfig = await loadConfig();
|
|
62
|
+
|
|
63
|
+
if (options.verbose && fileConfig) {
|
|
64
|
+
p.log.info('Loaded configuration from file');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Parse and merge configuration
|
|
68
|
+
const config = mergeConfig(fileConfig, {
|
|
69
|
+
input: options.input,
|
|
70
|
+
output: options.output,
|
|
71
|
+
baseUrl: options.baseUrl,
|
|
72
|
+
mode: options.mode,
|
|
73
|
+
tags: parseTags(options.tags),
|
|
74
|
+
excludeTags: parseTags(options.excludeTags),
|
|
75
|
+
overwrite: options.overwrite,
|
|
76
|
+
dryRun: options.dryRun,
|
|
77
|
+
verbose: options.verbose,
|
|
78
|
+
watch: options.watch,
|
|
79
|
+
generators: parseGenerators(options.generators),
|
|
80
|
+
serverRoutePath: options.serverRoutePath,
|
|
81
|
+
enableBff: options.enableBff,
|
|
82
|
+
backend:
|
|
83
|
+
options.backend === 'official' || options.backend === 'heyapi'
|
|
84
|
+
? options.backend
|
|
85
|
+
: undefined,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (config.verbose) {
|
|
89
|
+
console.log('Configuration:', config);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Show logo and intro
|
|
93
|
+
displayLogo();
|
|
94
|
+
p.intro(MESSAGES.intro);
|
|
95
|
+
|
|
96
|
+
if (config.dryRun) {
|
|
97
|
+
p.log.warn('🔍 DRY RUN MODE - No files will be written');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// 0. Select generator engine (first question)
|
|
101
|
+
// Resolve engine from config.generator (user-facing) or config.backend (CLI flag)
|
|
102
|
+
// config.generator: 'openapi' | 'heyapi' → map 'openapi' to internal 'official'
|
|
103
|
+
const resolvedBackend =
|
|
104
|
+
config.generator === 'openapi'
|
|
105
|
+
? 'official'
|
|
106
|
+
: config.generator === 'heyapi'
|
|
107
|
+
? 'heyapi'
|
|
108
|
+
: config.backend;
|
|
109
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
110
|
+
const backend = await promptGeneratorBackend(resolvedBackend);
|
|
111
|
+
|
|
112
|
+
// Check Java availability when official backend is selected
|
|
113
|
+
if (backend === 'official' && !checkJavaInstalled()) {
|
|
114
|
+
p.log.error(
|
|
115
|
+
'Java not found. The OpenAPI Generator requires Java 11 or higher.\n' +
|
|
116
|
+
'Install it from: https://adoptium.net\n' +
|
|
117
|
+
'Or switch to @hey-api/openapi-ts which requires no Java.'
|
|
118
|
+
);
|
|
119
|
+
p.outro('Aborted.');
|
|
120
|
+
process.exit(1);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 1. Determine composables to generate FIRST
|
|
124
|
+
let composables: ('useFetch' | 'useAsyncData' | 'nuxtServer')[];
|
|
125
|
+
|
|
126
|
+
if (config.generators) {
|
|
127
|
+
composables = config.generators;
|
|
128
|
+
if (config.verbose) {
|
|
129
|
+
console.log(`Using generators from config: ${composables.join(', ')}`);
|
|
130
|
+
}
|
|
131
|
+
} else {
|
|
132
|
+
const result = await promptComposablesSelection();
|
|
133
|
+
composables = result.composables;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (composables.length === 0) {
|
|
137
|
+
p.outro(MESSAGES.outro.noComposables);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 2. Ask for paths based on which generators were selected
|
|
142
|
+
const needsComposables = composables.some((c) => c === 'useFetch' || c === 'useAsyncData');
|
|
143
|
+
const needsNuxtServer = composables.includes('nuxtServer');
|
|
144
|
+
|
|
145
|
+
let inputPath: string;
|
|
146
|
+
let outputPath: string;
|
|
147
|
+
|
|
148
|
+
if (needsComposables) {
|
|
149
|
+
// useFetch/useAsyncData: ask for both input (OpenAPI spec) and output (composables dir)
|
|
150
|
+
const inputs = await promptInitialInputs(config.input, config.output);
|
|
151
|
+
inputPath = inputs.inputPath;
|
|
152
|
+
outputPath = inputs.outputPath;
|
|
153
|
+
} else {
|
|
154
|
+
// nuxtServer only: ask just for the OpenAPI spec, use default/config for output
|
|
155
|
+
inputPath = await promptInputPath(config.input);
|
|
156
|
+
outputPath = config.output ?? './swagger';
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 3. Ask for server route path if nuxtServer is selected
|
|
160
|
+
let serverRoutePath = config.serverRoutePath || '';
|
|
161
|
+
let enableBff = config.enableBff || false;
|
|
162
|
+
|
|
163
|
+
if (needsNuxtServer && !config.serverRoutePath) {
|
|
164
|
+
serverRoutePath = await promptServerRoutePath();
|
|
165
|
+
const bffConfig = await promptBffConfig();
|
|
166
|
+
enableBff = bffConfig.enableBff;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Generate OpenAPI files
|
|
170
|
+
const s = p.spinner();
|
|
171
|
+
s.start(MESSAGES.steps.generatingOpenApi);
|
|
172
|
+
|
|
173
|
+
if (!config.dryRun) {
|
|
174
|
+
if (backend === 'heyapi') {
|
|
175
|
+
await generateHeyApiFiles(inputPath, outputPath);
|
|
176
|
+
} else {
|
|
177
|
+
generateOpenApiFiles(inputPath, outputPath);
|
|
178
|
+
}
|
|
179
|
+
s.stop('OpenAPI files generated');
|
|
180
|
+
} else {
|
|
181
|
+
s.stop('Would generate OpenAPI files (skipped in dry-run)');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Generate selected composables
|
|
185
|
+
const composablesOutputDir = `${outputPath}/composables`;
|
|
186
|
+
|
|
187
|
+
for (const composable of composables) {
|
|
188
|
+
const spinner = p.spinner();
|
|
189
|
+
spinner.start(`Generating ${composable}...`);
|
|
190
|
+
|
|
191
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
192
|
+
const generateOptions = { baseUrl: config.baseUrl, backend };
|
|
193
|
+
|
|
194
|
+
try {
|
|
195
|
+
switch (composable) {
|
|
196
|
+
case 'useFetch':
|
|
197
|
+
if (!config.dryRun) {
|
|
198
|
+
await generateUseFetchComposables(
|
|
199
|
+
outputPath,
|
|
200
|
+
`${composablesOutputDir}/use-fetch`,
|
|
201
|
+
generateOptions
|
|
202
|
+
);
|
|
203
|
+
spinner.stop(`✓ Generated useFetch composables`);
|
|
204
|
+
} else {
|
|
205
|
+
spinner.stop(`Would generate useFetch composables (dry-run)`);
|
|
206
|
+
}
|
|
207
|
+
break;
|
|
208
|
+
case 'useAsyncData':
|
|
209
|
+
if (!config.dryRun) {
|
|
210
|
+
await generateUseAsyncDataComposables(
|
|
211
|
+
outputPath,
|
|
212
|
+
`${composablesOutputDir}/use-async-data`,
|
|
213
|
+
generateOptions
|
|
214
|
+
);
|
|
215
|
+
spinner.stop(`✓ Generated useAsyncData composables`);
|
|
216
|
+
} else {
|
|
217
|
+
spinner.stop(`Would generate useAsyncData composables (dry-run)`);
|
|
218
|
+
}
|
|
219
|
+
break;
|
|
220
|
+
case 'nuxtServer':
|
|
221
|
+
if (!config.dryRun) {
|
|
222
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
223
|
+
await generateNuxtServerRoutes(outputPath, serverRoutePath, { enableBff, backend });
|
|
224
|
+
spinner.stop(`✓ Generated Nuxt server routes`);
|
|
225
|
+
} else {
|
|
226
|
+
spinner.stop(`Would generate Nuxt server routes (dry-run)`);
|
|
227
|
+
}
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
} catch (error) {
|
|
231
|
+
spinner.stop(`✗ Failed to generate ${composable}`);
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (config.dryRun) {
|
|
237
|
+
p.outro('🔍 Dry run complete - no files were modified');
|
|
238
|
+
} else {
|
|
239
|
+
p.outro(MESSAGES.outro.success);
|
|
240
|
+
}
|
|
241
|
+
} catch (error) {
|
|
242
|
+
p.log.error(`Error: ${String(error)}`);
|
|
243
|
+
process.exit(1);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
program
|
|
248
|
+
.command('use-fetch')
|
|
249
|
+
.description('Generate Nuxt useFetch composables from OpenAPI generated files')
|
|
250
|
+
.option('-i, --input <path>', 'OpenAPI generated files directory')
|
|
251
|
+
.option('-o, --output <path>', 'Output directory for composables')
|
|
252
|
+
.action(async (options: { input?: string; output?: string }) => {
|
|
253
|
+
if (!options.input || !options.output) {
|
|
254
|
+
p.log.error('Error: You must provide both --input and --output');
|
|
255
|
+
process.exit(1);
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
await generateUseFetchComposables(options.input, options.output);
|
|
259
|
+
} catch (error) {
|
|
260
|
+
p.log.error(`Error: ${String(error)}`);
|
|
261
|
+
process.exit(1);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
program.parse();
|