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.
Files changed (109) hide show
  1. package/.editorconfig +26 -0
  2. package/.prettierignore +17 -0
  3. package/.prettierrc.json +12 -0
  4. package/CONTRIBUTING.md +292 -0
  5. package/INSTRUCTIONS.md +327 -0
  6. package/LICENSE +202 -0
  7. package/README.md +202 -0
  8. package/dist/cli/config.d.ts +57 -0
  9. package/dist/cli/config.js +85 -0
  10. package/dist/cli/logger.d.ts +44 -0
  11. package/dist/cli/logger.js +58 -0
  12. package/dist/cli/logo.d.ts +6 -0
  13. package/dist/cli/logo.js +21 -0
  14. package/dist/cli/messages.d.ts +65 -0
  15. package/dist/cli/messages.js +86 -0
  16. package/dist/cli/prompts.d.ts +30 -0
  17. package/dist/cli/prompts.js +118 -0
  18. package/dist/cli/types.d.ts +43 -0
  19. package/dist/cli/types.js +4 -0
  20. package/dist/cli/utils.d.ts +26 -0
  21. package/dist/cli/utils.js +45 -0
  22. package/dist/generate.d.ts +6 -0
  23. package/dist/generate.js +48 -0
  24. package/dist/generators/nuxt-server/bff-templates.d.ts +25 -0
  25. package/dist/generators/nuxt-server/bff-templates.js +737 -0
  26. package/dist/generators/nuxt-server/generator.d.ts +7 -0
  27. package/dist/generators/nuxt-server/generator.js +206 -0
  28. package/dist/generators/nuxt-server/parser.d.ts +5 -0
  29. package/dist/generators/nuxt-server/parser.js +5 -0
  30. package/dist/generators/nuxt-server/templates.d.ts +35 -0
  31. package/dist/generators/nuxt-server/templates.js +412 -0
  32. package/dist/generators/nuxt-server/types.d.ts +5 -0
  33. package/dist/generators/nuxt-server/types.js +5 -0
  34. package/dist/generators/shared/parsers/heyapi-parser.d.ts +11 -0
  35. package/dist/generators/shared/parsers/heyapi-parser.js +248 -0
  36. package/dist/generators/shared/parsers/official-parser.d.ts +5 -0
  37. package/dist/generators/shared/parsers/official-parser.js +5 -0
  38. package/dist/generators/shared/runtime/apiHelpers.d.ts +183 -0
  39. package/dist/generators/shared/runtime/apiHelpers.js +268 -0
  40. package/dist/generators/shared/templates/api-callbacks-plugin.d.ts +178 -0
  41. package/dist/generators/shared/templates/api-callbacks-plugin.js +338 -0
  42. package/dist/generators/shared/types.d.ts +25 -0
  43. package/dist/generators/shared/types.js +4 -0
  44. package/dist/generators/tanstack-query/generator.d.ts +5 -0
  45. package/dist/generators/tanstack-query/generator.js +11 -0
  46. package/dist/generators/use-async-data/generator.d.ts +5 -0
  47. package/dist/generators/use-async-data/generator.js +156 -0
  48. package/dist/generators/use-async-data/parser.d.ts +5 -0
  49. package/dist/generators/use-async-data/parser.js +5 -0
  50. package/dist/generators/use-async-data/runtime/useApiAsyncData.d.ts +38 -0
  51. package/dist/generators/use-async-data/runtime/useApiAsyncData.js +122 -0
  52. package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.d.ts +54 -0
  53. package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.js +126 -0
  54. package/dist/generators/use-async-data/templates.d.ts +20 -0
  55. package/dist/generators/use-async-data/templates.js +191 -0
  56. package/dist/generators/use-async-data/types.d.ts +4 -0
  57. package/dist/generators/use-async-data/types.js +4 -0
  58. package/dist/generators/use-fetch/generator.d.ts +5 -0
  59. package/dist/generators/use-fetch/generator.js +131 -0
  60. package/dist/generators/use-fetch/parser.d.ts +9 -0
  61. package/dist/generators/use-fetch/parser.js +282 -0
  62. package/dist/generators/use-fetch/runtime/useApiRequest.d.ts +46 -0
  63. package/dist/generators/use-fetch/runtime/useApiRequest.js +158 -0
  64. package/dist/generators/use-fetch/templates.d.ts +16 -0
  65. package/dist/generators/use-fetch/templates.js +169 -0
  66. package/dist/generators/use-fetch/types.d.ts +5 -0
  67. package/dist/generators/use-fetch/types.js +5 -0
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.js +213 -0
  70. package/docs/API-REFERENCE.md +887 -0
  71. package/docs/ARCHITECTURE.md +649 -0
  72. package/docs/DEVELOPMENT.md +918 -0
  73. package/docs/QUICK-START.md +323 -0
  74. package/docs/README.md +155 -0
  75. package/docs/TROUBLESHOOTING.md +881 -0
  76. package/eslint.config.js +72 -0
  77. package/package.json +65 -0
  78. package/src/cli/config.ts +140 -0
  79. package/src/cli/logger.ts +66 -0
  80. package/src/cli/logo.ts +25 -0
  81. package/src/cli/messages.ts +97 -0
  82. package/src/cli/prompts.ts +143 -0
  83. package/src/cli/types.ts +50 -0
  84. package/src/cli/utils.ts +49 -0
  85. package/src/generate.ts +57 -0
  86. package/src/generators/nuxt-server/bff-templates.ts +754 -0
  87. package/src/generators/nuxt-server/generator.ts +270 -0
  88. package/src/generators/nuxt-server/parser.ts +5 -0
  89. package/src/generators/nuxt-server/templates.ts +483 -0
  90. package/src/generators/nuxt-server/types.ts +5 -0
  91. package/src/generators/shared/parsers/heyapi-parser.ts +307 -0
  92. package/src/generators/shared/parsers/official-parser.ts +5 -0
  93. package/src/generators/shared/runtime/apiHelpers.ts +466 -0
  94. package/src/generators/shared/templates/api-callbacks-plugin.ts +352 -0
  95. package/src/generators/shared/types.ts +27 -0
  96. package/src/generators/tanstack-query/generator.ts +11 -0
  97. package/src/generators/use-async-data/generator.ts +204 -0
  98. package/src/generators/use-async-data/parser.ts +5 -0
  99. package/src/generators/use-async-data/runtime/useApiAsyncData.ts +220 -0
  100. package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +236 -0
  101. package/src/generators/use-async-data/templates.ts +250 -0
  102. package/src/generators/use-async-data/types.ts +4 -0
  103. package/src/generators/use-fetch/generator.ts +169 -0
  104. package/src/generators/use-fetch/parser.ts +341 -0
  105. package/src/generators/use-fetch/runtime/useApiRequest.ts +223 -0
  106. package/src/generators/use-fetch/templates.ts +214 -0
  107. package/src/generators/use-fetch/types.ts +5 -0
  108. package/src/index.ts +265 -0
  109. package/tsconfig.json +15 -0
@@ -0,0 +1,282 @@
1
+ import { Project, SyntaxKind } from 'ts-morph';
2
+ import * as path from 'path';
3
+ import { existsSync, readdirSync } from 'node:fs';
4
+ import { pascalCase } from 'change-case';
5
+ import { p } from '../../cli/logger.js';
6
+ /**
7
+ * Get all API files from the input directory
8
+ */
9
+ export function getApiFiles(inputDir) {
10
+ const apisDir = path.join(inputDir, 'apis');
11
+ if (!existsSync(apisDir)) {
12
+ throw new Error(`APIs directory not found: ${apisDir}`);
13
+ }
14
+ const files = readdirSync(apisDir);
15
+ return files
16
+ .filter((file) => file.endsWith('.ts') && file !== 'index.ts')
17
+ .map((file) => path.join(apisDir, file));
18
+ }
19
+ /**
20
+ * Parse an API file and extract all methods
21
+ */
22
+ export function parseApiFile(filePath) {
23
+ const project = new Project();
24
+ const sourceFile = project.addSourceFileAtPath(filePath);
25
+ // Find the API class (e.g., PetApi, StoreApi)
26
+ const classes = sourceFile.getClasses();
27
+ if (classes.length === 0) {
28
+ throw new Error(`No class found in ${filePath}`);
29
+ }
30
+ const apiClass = classes[0];
31
+ const className = apiClass.getName() || '';
32
+ // Get all public methods (excluding Raw and RequestOpts)
33
+ const methods = getPublicMethods(apiClass.getMethods());
34
+ const methodInfos = [];
35
+ for (const method of methods) {
36
+ try {
37
+ const methodInfo = extractMethodInfo(method, sourceFile);
38
+ if (methodInfo) {
39
+ methodInfos.push(methodInfo);
40
+ }
41
+ }
42
+ catch (error) {
43
+ p.log.warn(`Could not parse method ${method.getName()}: ${String(error)}`);
44
+ }
45
+ }
46
+ return {
47
+ className,
48
+ methods: methodInfos,
49
+ };
50
+ }
51
+ /**
52
+ * Filter to get only public methods (not Raw, not RequestOpts)
53
+ */
54
+ function getPublicMethods(methods) {
55
+ return methods.filter((method) => {
56
+ const name = method.getName();
57
+ const isAsync = method.isAsync();
58
+ const isPublic = !method.hasModifier(SyntaxKind.PrivateKeyword) &&
59
+ !method.hasModifier(SyntaxKind.ProtectedKeyword);
60
+ return isPublic && isAsync && !name.endsWith('Raw') && !name.endsWith('RequestOpts');
61
+ });
62
+ }
63
+ /**
64
+ * Extract method information
65
+ */
66
+ function extractMethodInfo(method, sourceFile) {
67
+ const methodName = method.getName();
68
+ const composableName = `useFetch${pascalCase(methodName)}`;
69
+ // Get parameters
70
+ const params = method.getParameters();
71
+ let requestType = params.length > 0 ? params[0].getType().getText() : undefined;
72
+ // Clean up type text: remove import() expressions and fix formatting
73
+ if (requestType) {
74
+ // Remove all import("path") expressions
75
+ requestType = requestType.replace(/import\([^)]+\)\./g, '');
76
+ // If it's the default RequestInit | InitOverrideFunction, treat as no params
77
+ if (requestType === 'RequestInit | InitOverrideFunction') {
78
+ requestType = undefined;
79
+ }
80
+ }
81
+ // Get return type
82
+ const returnType = method.getReturnType();
83
+ const responseType = extractResponseType(returnType.getText());
84
+ // Find corresponding RequestOpts method
85
+ const requestOptsMethodName = `${methodName}RequestOpts`;
86
+ const requestOptsMethod = sourceFile.getClasses()[0].getMethod(requestOptsMethodName);
87
+ if (!requestOptsMethod) {
88
+ p.log.warn(`Could not find ${requestOptsMethodName} method`);
89
+ return null;
90
+ }
91
+ // Parse request options
92
+ const requestOpts = parseRequestOptions(requestOptsMethod);
93
+ // Get description from JSDoc
94
+ const jsDocs = method.getJsDocs();
95
+ const description = jsDocs.length > 0 ? jsDocs[0].getDescription().trim() : undefined;
96
+ // Detect if Raw method exists
97
+ const rawMethodName = `${methodName}Raw`;
98
+ const classDeclaration = sourceFile.getClasses()[0];
99
+ const hasRawMethod = classDeclaration.getMethod(rawMethodName) !== undefined;
100
+ return {
101
+ name: methodName,
102
+ composableName,
103
+ requestType,
104
+ responseType,
105
+ httpMethod: requestOpts.method,
106
+ path: requestOpts.path,
107
+ hasBody: requestOpts.hasBody,
108
+ bodyField: requestOpts.bodyField,
109
+ hasQueryParams: requestOpts.queryParams.length > 0,
110
+ queryParams: requestOpts.queryParams,
111
+ pathParams: extractPathParams(requestOpts.path),
112
+ headers: requestOpts.headers,
113
+ description,
114
+ hasRawMethod,
115
+ rawMethodName: hasRawMethod ? rawMethodName : undefined,
116
+ };
117
+ }
118
+ /**
119
+ * Extract response type from Promise<Type>
120
+ */
121
+ function extractResponseType(returnTypeText) {
122
+ // Match Promise<Type>
123
+ const match = returnTypeText.match(/Promise<(.+)>$/);
124
+ if (match) {
125
+ // Remove all import("path") expressions
126
+ return match[1].replace(/import\([^)]+\)\./g, '');
127
+ }
128
+ return 'void';
129
+ }
130
+ /**
131
+ * Parse the RequestOpts method to extract request details
132
+ */
133
+ function parseRequestOptions(method) {
134
+ const result = {
135
+ path: '',
136
+ method: 'GET',
137
+ headers: {},
138
+ hasBody: false,
139
+ bodyField: undefined,
140
+ queryParams: [],
141
+ };
142
+ // Find the return statement
143
+ const returnStatements = method.getDescendantsOfKind(SyntaxKind.ReturnStatement);
144
+ if (returnStatements.length === 0) {
145
+ return result;
146
+ }
147
+ const returnStmt = returnStatements[0];
148
+ const objectLiteral = returnStmt.getFirstDescendantByKind(SyntaxKind.ObjectLiteralExpression);
149
+ if (!objectLiteral) {
150
+ return result;
151
+ }
152
+ // Parse each property
153
+ for (const prop of objectLiteral.getProperties()) {
154
+ if (prop.getKind() !== SyntaxKind.PropertyAssignment) {
155
+ continue;
156
+ }
157
+ const propAssignment = prop.asKind(SyntaxKind.PropertyAssignment);
158
+ if (!propAssignment) {
159
+ continue;
160
+ }
161
+ const propName = propAssignment.getName();
162
+ const initializer = propAssignment.getInitializer();
163
+ if (!initializer) {
164
+ continue;
165
+ }
166
+ switch (propName) {
167
+ case 'path': {
168
+ // Extract path from variable assignment
169
+ const pathValue = extractStringValue(initializer, method);
170
+ if (pathValue) {
171
+ result.path = pathValue;
172
+ }
173
+ break;
174
+ }
175
+ case 'method': {
176
+ const methodValue = extractStringValue(initializer, method);
177
+ if (methodValue) {
178
+ result.method = methodValue;
179
+ }
180
+ break;
181
+ }
182
+ case 'body': {
183
+ result.hasBody = true;
184
+ // Try to extract body field (e.g., params['pet'] or params.pet)
185
+ const bodyText = initializer.getText();
186
+ const bodyMatch = bodyText.match(/requestParameters(?:\['(\w+)'\]|\.(\w+))/);
187
+ if (bodyMatch) {
188
+ result.bodyField = bodyMatch[1] || bodyMatch[2];
189
+ }
190
+ break;
191
+ }
192
+ case 'headers': {
193
+ // Extract headers if it's an object literal
194
+ if (initializer.getKind() === SyntaxKind.ObjectLiteralExpression) {
195
+ const headersObj = initializer.asKind(SyntaxKind.ObjectLiteralExpression);
196
+ if (headersObj) {
197
+ for (const headerProp of headersObj.getProperties()) {
198
+ if (headerProp.getKind() === SyntaxKind.PropertyAssignment) {
199
+ const headerAssignment = headerProp.asKind(SyntaxKind.PropertyAssignment);
200
+ if (headerAssignment) {
201
+ const headerName = headerAssignment.getName();
202
+ const headerValue = headerAssignment.getInitializer();
203
+ if (headerValue && headerValue.getKind() === SyntaxKind.StringLiteral) {
204
+ result.headers[headerName] = headerValue.getText().slice(1, -1);
205
+ }
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ break;
212
+ }
213
+ }
214
+ }
215
+ // Extract query parameters from the method body
216
+ result.queryParams = extractQueryParams(method);
217
+ return result;
218
+ }
219
+ /**
220
+ * Extract string value from expression
221
+ */
222
+ function extractStringValue(node, method) {
223
+ // Direct string literal
224
+ if (node.getKind() === SyntaxKind.StringLiteral) {
225
+ return node.getText().slice(1, -1); // Remove quotes
226
+ }
227
+ // Template literal
228
+ if (node.getKind() === SyntaxKind.TemplateExpression ||
229
+ node.getKind() === SyntaxKind.NoSubstitutionTemplateLiteral) {
230
+ return node.getText().slice(1, -1); // Remove backticks
231
+ }
232
+ // Variable reference - try to find its value
233
+ if (node.getKind() === SyntaxKind.Identifier) {
234
+ const varName = node.getText();
235
+ // Find variable declarations in the method body
236
+ const varDeclarations = method.getDescendantsOfKind(SyntaxKind.VariableDeclaration);
237
+ for (const varDecl of varDeclarations) {
238
+ if (varDecl.getName() === varName) {
239
+ const initializer = varDecl.getInitializer();
240
+ if (initializer) {
241
+ if (initializer.getKind() === SyntaxKind.StringLiteral) {
242
+ return initializer.getText().slice(1, -1);
243
+ }
244
+ if (initializer.getKind() === SyntaxKind.TemplateExpression ||
245
+ initializer.getKind() === SyntaxKind.NoSubstitutionTemplateLiteral) {
246
+ return initializer.getText().slice(1, -1);
247
+ }
248
+ }
249
+ }
250
+ }
251
+ }
252
+ return null;
253
+ }
254
+ /**
255
+ * Extract query parameters from method body
256
+ */
257
+ function extractQueryParams(method) {
258
+ const params = [];
259
+ const methodText = method.getText();
260
+ // Look for queryParameters['paramName'] or queryParameters.paramName
261
+ const regex = /queryParameters(?:\['(\w+)'\]|\.(\w+))/g;
262
+ let match;
263
+ while ((match = regex.exec(methodText)) !== null) {
264
+ const paramName = match[1] || match[2];
265
+ if (paramName && !params.includes(paramName)) {
266
+ params.push(paramName);
267
+ }
268
+ }
269
+ return params;
270
+ }
271
+ /**
272
+ * Extract path parameters from path string (e.g., /pet/{petId} -> ['petId'])
273
+ */
274
+ function extractPathParams(path) {
275
+ const regex = /\{(\w+)\}/g;
276
+ const params = [];
277
+ let match;
278
+ while ((match = regex.exec(path)) !== null) {
279
+ params.push(match[1]);
280
+ }
281
+ return params;
282
+ }
@@ -0,0 +1,46 @@
1
+ import { type ApiRequestOptions as BaseApiRequestOptions } from '../../shared/runtime/apiHelpers.js';
2
+ /**
3
+ * Options for useFetch API requests with lifecycle callbacks
4
+ * Extends base options with useFetch-specific options
5
+ */
6
+ export interface ApiRequestOptions<T = any> extends BaseApiRequestOptions<T> {
7
+ /** All standard useFetch options */
8
+ [key: string]: any;
9
+ }
10
+ /**
11
+ * Enhanced useFetch wrapper with lifecycle callbacks and request interception
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * // Basic usage
16
+ * const { data, error } = useApiRequest<Pet>('/api/pets', {
17
+ * method: 'POST',
18
+ * body: { name: 'Max' },
19
+ * });
20
+ *
21
+ * // With transform (type is inferred!)
22
+ * const { data } = useApiRequest<Pet>('/api/pets/1', {
23
+ * transform: (pet) => ({ displayName: pet.name, available: pet.status === 'available' })
24
+ * });
25
+ * // data is Ref<{ displayName: string, available: boolean }>
26
+ *
27
+ * // With pick (simple fields)
28
+ * const { data } = useApiRequest<Pet>('/api/pets/1', {
29
+ * pick: ['id', 'name'] as const
30
+ * });
31
+ *
32
+ * // With pick (nested dot notation)
33
+ * const { data } = useApiRequest('/api/user', {
34
+ * pick: ['person.name', 'person.email', 'status']
35
+ * });
36
+ * // Result: { person: { name: '...', email: '...' }, status: '...' }
37
+ *
38
+ * // With callbacks
39
+ * const { data } = useApiRequest<Pet>('/api/pets', {
40
+ * onRequest: (ctx) => ({ headers: { 'Authorization': `Bearer ${token}` } }),
41
+ * onSuccess: (pet) => console.log('Got pet:', pet),
42
+ * onError: (err) => console.error('Failed:', err),
43
+ * });
44
+ * ```
45
+ */
46
+ export declare function useApiRequest<T = any, Options extends ApiRequestOptions<T> = ApiRequestOptions<T>>(url: string | (() => string), options?: Options): any;
@@ -0,0 +1,158 @@
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 { getGlobalHeaders, applyPick, applyRequestModifications, mergeCallbacks, } from '../../shared/runtime/apiHelpers.js';
8
+ /**
9
+ * Enhanced useFetch wrapper with lifecycle callbacks and request interception
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * // Basic usage
14
+ * const { data, error } = useApiRequest<Pet>('/api/pets', {
15
+ * method: 'POST',
16
+ * body: { name: 'Max' },
17
+ * });
18
+ *
19
+ * // With transform (type is inferred!)
20
+ * const { data } = useApiRequest<Pet>('/api/pets/1', {
21
+ * transform: (pet) => ({ displayName: pet.name, available: pet.status === 'available' })
22
+ * });
23
+ * // data is Ref<{ displayName: string, available: boolean }>
24
+ *
25
+ * // With pick (simple fields)
26
+ * const { data } = useApiRequest<Pet>('/api/pets/1', {
27
+ * pick: ['id', 'name'] as const
28
+ * });
29
+ *
30
+ * // With pick (nested dot notation)
31
+ * const { data } = useApiRequest('/api/user', {
32
+ * pick: ['person.name', 'person.email', 'status']
33
+ * });
34
+ * // Result: { person: { name: '...', email: '...' }, status: '...' }
35
+ *
36
+ * // With callbacks
37
+ * const { data } = useApiRequest<Pet>('/api/pets', {
38
+ * onRequest: (ctx) => ({ headers: { 'Authorization': `Bearer ${token}` } }),
39
+ * onSuccess: (pet) => console.log('Got pet:', pet),
40
+ * onError: (err) => console.error('Failed:', err),
41
+ * });
42
+ * ```
43
+ */
44
+ export function useApiRequest(url, options) {
45
+ const { onRequest, onSuccess, onError, onFinish, skipGlobalCallbacks, transform, pick, ...fetchOptions } = options || {};
46
+ // Prepare request context for onRequest interceptor
47
+ const urlValue = typeof url === 'function' ? url() : url;
48
+ const requestContext = {
49
+ url: urlValue,
50
+ method: fetchOptions.method || 'GET',
51
+ body: fetchOptions.body,
52
+ headers: fetchOptions.headers,
53
+ query: fetchOptions.query,
54
+ };
55
+ // Merge local and global callbacks
56
+ const mergedCallbacks = mergeCallbacks(urlValue, { onRequest, onSuccess, onError, onFinish }, skipGlobalCallbacks);
57
+ // Apply global headers configuration (from composable or plugin)
58
+ const modifiedOptions = { ...fetchOptions };
59
+ const globalHeaders = getGlobalHeaders();
60
+ if (Object.keys(globalHeaders).length > 0) {
61
+ modifiedOptions.headers = {
62
+ ...globalHeaders,
63
+ ...modifiedOptions.headers, // User headers override global headers
64
+ };
65
+ }
66
+ // Execute merged onRequest interceptor and apply modifications
67
+ if (mergedCallbacks.onRequest) {
68
+ try {
69
+ const result = mergedCallbacks.onRequest(requestContext);
70
+ // Handle async onRequest
71
+ if (result && typeof result === 'object' && 'then' in result) {
72
+ result
73
+ .then((modifications) => {
74
+ if (modifications) {
75
+ applyRequestModifications(modifiedOptions, modifications);
76
+ }
77
+ })
78
+ .catch((error) => {
79
+ console.error('Error in merged onRequest callback:', error);
80
+ });
81
+ }
82
+ // Handle sync onRequest with return value
83
+ else if (result && typeof result === 'object') {
84
+ applyRequestModifications(modifiedOptions, result);
85
+ }
86
+ }
87
+ catch (error) {
88
+ console.error('Error in merged onRequest callback:', error);
89
+ }
90
+ }
91
+ // Make the actual request using Nuxt's useFetch
92
+ const result = useFetch(url, modifiedOptions);
93
+ const transformedData = ref(null);
94
+ // Track if callbacks have been executed to avoid duplicates
95
+ let successExecuted = false;
96
+ let errorExecuted = false;
97
+ // Watch for changes in data, error, and pending states
98
+ watch(() => [result.data.value, result.error.value, result.pending.value], async ([data, error, pending], [prevData, prevError, prevPending]) => {
99
+ // Apply transformations when data arrives
100
+ if (data && data !== prevData) {
101
+ let processedData = data;
102
+ // Step 1: Apply pick if specified
103
+ if (pick) {
104
+ processedData = applyPick(processedData, pick);
105
+ }
106
+ // Step 2: Apply transform if specified
107
+ if (transform) {
108
+ try {
109
+ processedData = transform(processedData);
110
+ }
111
+ catch (err) {
112
+ console.error('Error in transform function:', err);
113
+ }
114
+ }
115
+ // Update transformed data ref
116
+ transformedData.value = processedData;
117
+ // onSuccess - when data arrives and no error (using merged callback)
118
+ if (!error && !successExecuted && mergedCallbacks.onSuccess) {
119
+ successExecuted = true;
120
+ try {
121
+ await mergedCallbacks.onSuccess(processedData);
122
+ }
123
+ catch (err) {
124
+ console.error('Error in merged onSuccess callback:', err);
125
+ }
126
+ }
127
+ }
128
+ // onError - when an error occurs (using merged callback)
129
+ if (error && error !== prevError && !errorExecuted && mergedCallbacks.onError) {
130
+ errorExecuted = true;
131
+ try {
132
+ await mergedCallbacks.onError(error);
133
+ }
134
+ catch (err) {
135
+ console.error('Error in merged onError callback:', err);
136
+ }
137
+ }
138
+ // onFinish - when request completes (was pending, now not) (using merged callback)
139
+ if (prevPending && !pending && mergedCallbacks.onFinish) {
140
+ const finishContext = {
141
+ data: transformedData.value || undefined,
142
+ error: error || undefined,
143
+ success: !!transformedData.value && !error,
144
+ };
145
+ try {
146
+ await mergedCallbacks.onFinish(finishContext);
147
+ }
148
+ catch (err) {
149
+ console.error('Error in merged onFinish callback:', err);
150
+ }
151
+ }
152
+ }, { immediate: true });
153
+ // Return result with transformed data
154
+ return {
155
+ ...result,
156
+ data: transformedData,
157
+ };
158
+ }
@@ -0,0 +1,16 @@
1
+ import type { MethodInfo } from './types.js';
2
+ /**
3
+ * Options for code generation
4
+ */
5
+ export interface GenerateOptions {
6
+ baseUrl?: string;
7
+ backend?: string;
8
+ }
9
+ /**
10
+ * Generate a useFetch composable function
11
+ */
12
+ export declare function generateComposableFile(method: MethodInfo, apiImportPath: string, options?: GenerateOptions): string;
13
+ /**
14
+ * Generate index.ts that exports all composables
15
+ */
16
+ export declare function generateIndexFile(composableNames: string[]): string;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Generate file header with auto-generation warning
3
+ */
4
+ function generateFileHeader() {
5
+ return `/**
6
+ * ⚠️ AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
7
+ *
8
+ * This file was automatically generated by nuxt-openapi-generator.
9
+ * Any manual changes will be overwritten on the next generation.
10
+ *
11
+ * @generated by nuxt-openapi-generator
12
+ * @see https://github.com/dmartindiaz/nuxt-openapi-hyperfetch
13
+ */
14
+
15
+ /* eslint-disable */
16
+ // @ts-nocheck
17
+ `;
18
+ }
19
+ /**
20
+ * Generate a useFetch composable function
21
+ */
22
+ export function generateComposableFile(method, apiImportPath, options) {
23
+ const header = generateFileHeader();
24
+ const imports = generateImports(method, apiImportPath);
25
+ const functionBody = generateFunctionBody(method, options);
26
+ return `${header}${imports}\n\n${functionBody}\n`;
27
+ }
28
+ /**
29
+ * Extract base type names from a type string
30
+ * Examples:
31
+ * Pet[] -> Pet
32
+ * Array<Pet> -> Pet
33
+ * Pet -> Pet
34
+ * { [key: string]: Pet } -> (empty, it's anonymous)
35
+ */
36
+ function extractBaseTypes(type) {
37
+ if (!type) {
38
+ return [];
39
+ }
40
+ // Handle array syntax: Pet[]
41
+ const arrayMatch = type.match(/^(\w+)\[\]$/);
42
+ if (arrayMatch) {
43
+ return [arrayMatch[1]];
44
+ }
45
+ // Handle Array generic: Array<Pet>
46
+ const arrayGenericMatch = type.match(/^Array<(\w+)>$/);
47
+ if (arrayGenericMatch) {
48
+ return [arrayGenericMatch[1]];
49
+ }
50
+ // If it's a simple named type (single word, PascalCase), include it
51
+ if (/^[A-Z][a-zA-Z0-9]*$/.test(type)) {
52
+ return [type];
53
+ }
54
+ // For complex types, don't extract anything
55
+ return [];
56
+ }
57
+ /**
58
+ * Generate import statements
59
+ */
60
+ function generateImports(method, apiImportPath) {
61
+ const typeNames = new Set();
62
+ // Extract base types from request type
63
+ if (method.requestType) {
64
+ const extracted = extractBaseTypes(method.requestType);
65
+ extracted.forEach((t) => typeNames.add(t));
66
+ }
67
+ // Extract base types from response type
68
+ if (method.responseType && method.responseType !== 'void') {
69
+ const extracted = extractBaseTypes(method.responseType);
70
+ extracted.forEach((t) => typeNames.add(t));
71
+ }
72
+ let imports = '';
73
+ // Import types from API (only if we have named types to import)
74
+ if (typeNames.size > 0) {
75
+ imports += `import type { ${Array.from(typeNames).join(', ')} } from '${apiImportPath}';\n`;
76
+ }
77
+ // Import runtime helper
78
+ imports += `import { useApiRequest, type ApiRequestOptions } from '../runtime/useApiRequest';`;
79
+ return imports;
80
+ }
81
+ /**
82
+ }
83
+
84
+ /**
85
+ * Generate the composable function body
86
+ */
87
+ function generateFunctionBody(method, options) {
88
+ const hasParams = !!method.requestType;
89
+ const paramsArg = hasParams ? `params: MaybeRef<${method.requestType}>` : '';
90
+ const optionsType = `ApiRequestOptions<${method.responseType}>`;
91
+ const optionsArg = `options?: ${optionsType}`;
92
+ const args = hasParams ? `${paramsArg}, ${optionsArg}` : optionsArg;
93
+ const responseTypeGeneric = method.responseType !== 'void' ? `<${method.responseType}>` : '';
94
+ const url = generateUrl(method);
95
+ const fetchOptions = generateFetchOptions(method, options);
96
+ const description = method.description ? `/**\n * ${method.description}\n */\n` : '';
97
+ const pInit = hasParams ? `\n const p = isRef(params) ? params : shallowRef(params)` : '';
98
+ return `${description}export const ${method.composableName} = (${args}) => {${pInit}
99
+ return useApiRequest${responseTypeGeneric}(${url}, ${fetchOptions})
100
+ }`;
101
+ }
102
+ /**
103
+ * Generate URL (with path params if needed)
104
+ */
105
+ function generateUrl(method) {
106
+ if (method.pathParams.length === 0) {
107
+ return `'${method.path}'`;
108
+ }
109
+ let url = method.path;
110
+ for (const param of method.pathParams) {
111
+ const accessor = method.paramsShape === 'nested' ? `p.value.path.${param}` : `p.value.${param}`;
112
+ url = url.replace(`{${param}}`, `\${${accessor}}`);
113
+ }
114
+ return `() => \`${url}\``;
115
+ }
116
+ /**
117
+ * Generate fetch options object
118
+ */
119
+ function generateFetchOptions(method, generateOptions) {
120
+ const options = [];
121
+ // Method
122
+ options.push(`method: '${method.httpMethod}'`);
123
+ // Base URL (if provided in config)
124
+ if (generateOptions?.baseUrl) {
125
+ options.push(`baseURL: '${generateOptions.baseUrl}'`);
126
+ }
127
+ // Body
128
+ if (method.hasBody) {
129
+ if (method.paramsShape === 'nested') {
130
+ options.push(`body: computed(() => p.value.body)`);
131
+ }
132
+ else if (method.bodyField) {
133
+ options.push(`body: computed(() => p.value.${method.bodyField})`);
134
+ }
135
+ }
136
+ // Query params
137
+ if (method.hasQueryParams) {
138
+ if (method.paramsShape === 'nested') {
139
+ options.push(`query: computed(() => p.value.query)`);
140
+ }
141
+ else if (method.queryParams.length > 0) {
142
+ const queryObj = method.queryParams
143
+ .map((param) => `${param}: p.value.${param}`)
144
+ .join(',\n ');
145
+ options.push(`query: computed(() => ({\n ${queryObj}\n }))`);
146
+ }
147
+ }
148
+ // Headers
149
+ if (Object.keys(method.headers).length > 0) {
150
+ const headersEntries = Object.entries(method.headers)
151
+ .map(([key, value]) => `'${key}': '${value}'`)
152
+ .join(',\n ');
153
+ options.push(`headers: {\n ${headersEntries},\n ...options?.headers\n }`);
154
+ }
155
+ // Spread options
156
+ options.push('...options');
157
+ const optionsStr = options.join(',\n ');
158
+ return `{\n ${optionsStr}\n }`;
159
+ }
160
+ /**
161
+ * Generate index.ts that exports all composables
162
+ */
163
+ export function generateIndexFile(composableNames) {
164
+ const header = generateFileHeader();
165
+ const exports = composableNames
166
+ .map((name) => `export { ${name} } from './composables/${name}'`)
167
+ .join('\n');
168
+ return `${header}${exports}\n`;
169
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Re-export shared types
3
+ * This allows use-fetch generator to use the same types as other generators
4
+ */
5
+ export * from '../shared/types.js';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Re-export shared types
3
+ * This allows use-fetch generator to use the same types as other generators
4
+ */
5
+ export * from '../shared/types.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};