nuxt-openapi-hyperfetch 0.1.7-alpha.1 → 0.2.7-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 (97) hide show
  1. package/CONTRIBUTING.md +291 -292
  2. package/INSTRUCTIONS.md +327 -327
  3. package/LICENSE +202 -202
  4. package/README.md +231 -227
  5. package/dist/cli/logger.d.ts +26 -0
  6. package/dist/cli/logger.js +36 -0
  7. package/dist/cli/logo.js +5 -5
  8. package/dist/generators/components/connector-generator/generator.d.ts +12 -0
  9. package/dist/generators/components/connector-generator/generator.js +116 -0
  10. package/dist/generators/components/connector-generator/templates.d.ts +18 -0
  11. package/dist/generators/components/connector-generator/templates.js +222 -0
  12. package/dist/generators/components/connector-generator/types.d.ts +32 -0
  13. package/dist/generators/components/connector-generator/types.js +7 -0
  14. package/dist/generators/components/schema-analyzer/index.d.ts +17 -0
  15. package/dist/generators/components/schema-analyzer/index.js +20 -0
  16. package/dist/generators/components/schema-analyzer/intent-detector.d.ts +17 -0
  17. package/dist/generators/components/schema-analyzer/intent-detector.js +143 -0
  18. package/dist/generators/components/schema-analyzer/openapi-reader.d.ts +11 -0
  19. package/dist/generators/components/schema-analyzer/openapi-reader.js +76 -0
  20. package/dist/generators/components/schema-analyzer/resource-grouper.d.ts +6 -0
  21. package/dist/generators/components/schema-analyzer/resource-grouper.js +132 -0
  22. package/dist/generators/components/schema-analyzer/schema-field-mapper.d.ts +35 -0
  23. package/dist/generators/components/schema-analyzer/schema-field-mapper.js +220 -0
  24. package/dist/generators/components/schema-analyzer/types.d.ts +156 -0
  25. package/dist/generators/components/schema-analyzer/types.js +7 -0
  26. package/dist/generators/nuxt-server/generator.d.ts +2 -1
  27. package/dist/generators/nuxt-server/generator.js +21 -21
  28. package/dist/generators/shared/runtime/apiHelpers.d.ts +81 -41
  29. package/dist/generators/shared/runtime/apiHelpers.js +97 -104
  30. package/dist/generators/shared/runtime/pagination.d.ts +168 -0
  31. package/dist/generators/shared/runtime/pagination.js +179 -0
  32. package/dist/generators/shared/runtime/useDeleteConnector.d.ts +16 -0
  33. package/dist/generators/shared/runtime/useDeleteConnector.js +93 -0
  34. package/dist/generators/shared/runtime/useDetailConnector.d.ts +14 -0
  35. package/dist/generators/shared/runtime/useDetailConnector.js +50 -0
  36. package/dist/generators/shared/runtime/useFormConnector.d.ts +19 -0
  37. package/dist/generators/shared/runtime/useFormConnector.js +113 -0
  38. package/dist/generators/shared/runtime/useListConnector.d.ts +25 -0
  39. package/dist/generators/shared/runtime/useListConnector.js +125 -0
  40. package/dist/generators/shared/runtime/zod-error-merger.d.ts +23 -0
  41. package/dist/generators/shared/runtime/zod-error-merger.js +106 -0
  42. package/dist/generators/shared/templates/api-callbacks-plugin.js +54 -11
  43. package/dist/generators/shared/templates/api-pagination-plugin.d.ts +51 -0
  44. package/dist/generators/shared/templates/api-pagination-plugin.js +152 -0
  45. package/dist/generators/use-async-data/generator.d.ts +2 -1
  46. package/dist/generators/use-async-data/generator.js +14 -14
  47. package/dist/generators/use-async-data/runtime/useApiAsyncData.js +114 -13
  48. package/dist/generators/use-async-data/runtime/useApiAsyncDataRaw.js +88 -10
  49. package/dist/generators/use-async-data/templates.js +17 -17
  50. package/dist/generators/use-fetch/generator.d.ts +2 -1
  51. package/dist/generators/use-fetch/generator.js +12 -12
  52. package/dist/generators/use-fetch/runtime/useApiRequest.js +149 -40
  53. package/dist/generators/use-fetch/templates.js +14 -14
  54. package/dist/index.js +25 -0
  55. package/dist/module/index.d.ts +4 -0
  56. package/dist/module/index.js +93 -0
  57. package/dist/module/types.d.ts +27 -0
  58. package/dist/module/types.js +1 -0
  59. package/docs/API-REFERENCE.md +886 -887
  60. package/docs/generated-components.md +615 -0
  61. package/docs/headless-composables-ui.md +569 -0
  62. package/eslint.config.js +13 -0
  63. package/package.json +29 -2
  64. package/src/cli/config.ts +140 -140
  65. package/src/cli/logger.ts +124 -66
  66. package/src/cli/logo.ts +25 -25
  67. package/src/cli/types.ts +50 -50
  68. package/src/generators/components/connector-generator/generator.ts +138 -0
  69. package/src/generators/components/connector-generator/templates.ts +254 -0
  70. package/src/generators/components/connector-generator/types.ts +34 -0
  71. package/src/generators/components/schema-analyzer/index.ts +44 -0
  72. package/src/generators/components/schema-analyzer/intent-detector.ts +187 -0
  73. package/src/generators/components/schema-analyzer/openapi-reader.ts +96 -0
  74. package/src/generators/components/schema-analyzer/resource-grouper.ts +166 -0
  75. package/src/generators/components/schema-analyzer/schema-field-mapper.ts +268 -0
  76. package/src/generators/components/schema-analyzer/types.ts +177 -0
  77. package/src/generators/nuxt-server/generator.ts +272 -270
  78. package/src/generators/shared/runtime/apiHelpers.ts +535 -507
  79. package/src/generators/shared/runtime/pagination.ts +323 -0
  80. package/src/generators/shared/runtime/useDeleteConnector.ts +109 -0
  81. package/src/generators/shared/runtime/useDetailConnector.ts +64 -0
  82. package/src/generators/shared/runtime/useFormConnector.ts +139 -0
  83. package/src/generators/shared/runtime/useListConnector.ts +148 -0
  84. package/src/generators/shared/runtime/zod-error-merger.ts +119 -0
  85. package/src/generators/shared/templates/api-callbacks-plugin.ts +399 -352
  86. package/src/generators/shared/templates/api-pagination-plugin.ts +158 -0
  87. package/src/generators/use-async-data/generator.ts +205 -204
  88. package/src/generators/use-async-data/runtime/useApiAsyncData.ts +329 -229
  89. package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +324 -245
  90. package/src/generators/use-async-data/templates.ts +257 -257
  91. package/src/generators/use-fetch/generator.ts +170 -169
  92. package/src/generators/use-fetch/runtime/useApiRequest.ts +354 -234
  93. package/src/generators/use-fetch/templates.ts +214 -214
  94. package/src/index.ts +303 -265
  95. package/src/module/index.ts +133 -0
  96. package/src/module/types.ts +31 -0
  97. package/src/generators/tanstack-query/generator.ts +0 -11
@@ -1,234 +1,354 @@
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 type { UseFetchOptions } from '#app';
8
- import {
9
- getGlobalHeaders,
10
- getGlobalBaseUrl,
11
- applyPick,
12
- applyRequestModifications,
13
- mergeCallbacks,
14
- type RequestContext,
15
- type ModifiedRequestContext,
16
- type FinishContext,
17
- type ApiRequestOptions as BaseApiRequestOptions,
18
- } from '../../shared/runtime/apiHelpers.js';
19
-
20
- /**
21
- * Helper type to infer transformed data type
22
- * If transform is provided, infer its return type
23
- * If pick is provided, return partial object (type inference for nested paths is complex)
24
- * Otherwise, return original type
25
- */
26
- type MaybeTransformed<T, Options> = Options extends { transform: (...args: any) => infer R }
27
- ? R
28
- : Options extends { pick: ReadonlyArray<any> }
29
- ? any // With nested paths, type inference is complex, so we use any
30
- : T;
31
-
32
- /**
33
- * Options for useFetch API requests with lifecycle callbacks.
34
- * Extends all native Nuxt useFetch options plus our custom callbacks, transform, and pick.
35
- * Native options like baseURL, method, body, headers, query, lazy, server, immediate, etc. are all available.
36
- */
37
- export type ApiRequestOptions<T = any> = BaseApiRequestOptions<T> & Omit<UseFetchOptions<T>, 'transform' | 'pick'>;
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
- // Apply global base URL from runtimeConfig.public.apiBaseUrl (if not already set per-composable)
118
- if (!modifiedOptions.baseURL) {
119
- modifiedOptions.baseURL = getGlobalBaseUrl();
120
- }
121
- if (!modifiedOptions.baseURL) {
122
- console.warn(
123
- '[nuxt-openapi-hyperfetch] No baseURL configured. Set runtimeConfig.public.apiBaseUrl in nuxt.config.ts or pass baseURL in options.'
124
- );
125
- }
126
-
127
- // Execute merged onRequest interceptor and apply modifications
128
- if (mergedCallbacks.onRequest) {
129
- try {
130
- const result = mergedCallbacks.onRequest(requestContext);
131
-
132
- // Handle async onRequest
133
- if (result && typeof result === 'object' && 'then' in result) {
134
- result
135
- .then((modifications) => {
136
- if (modifications) {
137
- applyRequestModifications(modifiedOptions, modifications);
138
- }
139
- })
140
- .catch((error) => {
141
- console.error('Error in merged onRequest callback:', error);
142
- });
143
- }
144
- // Handle sync onRequest with return value
145
- else if (result && typeof result === 'object') {
146
- applyRequestModifications(modifiedOptions, result);
147
- }
148
- } catch (error) {
149
- console.error('Error in merged onRequest callback:', error);
150
- }
151
- }
152
-
153
- // Make the actual request using Nuxt's useFetch
154
- const result = useFetch<T>(url, modifiedOptions);
155
-
156
- // Create a ref for transformed data
157
- type TransformedType = MaybeTransformed<T, Options>;
158
- const transformedData = ref<TransformedType | null>(null);
159
-
160
- // Track if callbacks have been executed to avoid duplicates
161
- let successExecuted = false;
162
- let errorExecuted = false;
163
-
164
- // Watch for changes in data, error, and pending states
165
- watch(
166
- () => [result.data.value, result.error.value, result.pending.value] as const,
167
- async ([data, error, pending], prev) => {
168
- const [prevData, prevError, prevPending] = prev ?? [undefined, undefined, undefined];
169
- // Apply transformations when data arrives
170
- if (data && data !== prevData) {
171
- let processedData: any = data;
172
-
173
- // Step 1: Apply pick if specified
174
- if (pick) {
175
- processedData = applyPick(processedData, pick);
176
- }
177
-
178
- // Step 2: Apply transform if specified
179
- if (transform) {
180
- try {
181
- processedData = transform(processedData);
182
- } catch (err) {
183
- console.error('Error in transform function:', err);
184
- }
185
- }
186
-
187
- // Update transformed data ref
188
- transformedData.value = processedData as TransformedType;
189
-
190
- // onSuccess - when data arrives and no error (using merged callback)
191
- if (!error && !successExecuted && mergedCallbacks.onSuccess) {
192
- successExecuted = true;
193
- try {
194
- await mergedCallbacks.onSuccess(processedData);
195
- } catch (err) {
196
- console.error('Error in merged onSuccess callback:', err);
197
- }
198
- }
199
- }
200
-
201
- // onError - when an error occurs (using merged callback)
202
- if (error && error !== prevError && !errorExecuted && mergedCallbacks.onError) {
203
- errorExecuted = true;
204
- try {
205
- await mergedCallbacks.onError(error);
206
- } catch (err) {
207
- console.error('Error in merged onError callback:', err);
208
- }
209
- }
210
-
211
- // onFinish - when request completes (was pending, now not) (using merged callback)
212
- if (prevPending && !pending && mergedCallbacks.onFinish) {
213
- const finishContext: FinishContext<TransformedType> = {
214
- data: transformedData.value || undefined,
215
- error: error || undefined,
216
- success: !!transformedData.value && !error,
217
- };
218
-
219
- try {
220
- await mergedCallbacks.onFinish(finishContext);
221
- } catch (err) {
222
- console.error('Error in merged onFinish callback:', err);
223
- }
224
- }
225
- },
226
- { immediate: true }
227
- );
228
-
229
- // Return result with transformed data
230
- return {
231
- ...result,
232
- data: transformedData as Ref<TransformedType | null>,
233
- };
234
- }
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, ref, computed } from 'vue';
7
+ import type { UseFetchOptions } from '#app';
8
+ import {
9
+ getGlobalHeaders,
10
+ getGlobalBaseUrl,
11
+ applyPick,
12
+ applyRequestModifications,
13
+ mergeCallbacks,
14
+ type RequestContext,
15
+ type ModifiedRequestContext,
16
+ type FinishContext,
17
+ type ApiRequestOptions as BaseApiRequestOptions,
18
+ } from '../../shared/runtime/apiHelpers.js';
19
+ import {
20
+ getGlobalApiPagination,
21
+ buildPaginationRequest,
22
+ extractPaginationMetaFromBody,
23
+ extractPaginationMetaFromHeaders,
24
+ unwrapDataKey,
25
+ type PaginationState,
26
+ } from '../../shared/runtime/pagination.js';
27
+
28
+ /**
29
+ * Helper type to infer transformed data type
30
+ * If transform is provided, infer its return type
31
+ * If pick is provided, return partial object (type inference for nested paths is complex)
32
+ * Otherwise, return original type
33
+ */
34
+ type MaybeTransformed<T, Options> = Options extends { transform: (...args: any) => infer R }
35
+ ? R
36
+ : Options extends { pick: ReadonlyArray<any> }
37
+ ? any // With nested paths, type inference is complex, so we use any
38
+ : T;
39
+
40
+ /**
41
+ * Options for useFetch API requests with lifecycle callbacks.
42
+ * Extends all native Nuxt useFetch options plus our custom callbacks, transform, and pick.
43
+ * Native options like baseURL, method, body, headers, query, lazy, server, immediate, etc. are all available.
44
+ */
45
+ export type ApiRequestOptions<T = any> = BaseApiRequestOptions<T> & Omit<UseFetchOptions<T>, 'transform' | 'pick'>;
46
+
47
+ /**
48
+ * Enhanced useFetch wrapper with lifecycle callbacks and request interception
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * // Basic usage
53
+ * const { data, error } = useApiRequest<Pet>('/api/pets', {
54
+ * method: 'POST',
55
+ * body: { name: 'Max' },
56
+ * });
57
+ *
58
+ * // With transform (type is inferred!)
59
+ * const { data } = useApiRequest<Pet>('/api/pets/1', {
60
+ * transform: (pet) => ({ displayName: pet.name, available: pet.status === 'available' })
61
+ * });
62
+ * // data is Ref<{ displayName: string, available: boolean }>
63
+ *
64
+ * // With pick (simple fields)
65
+ * const { data } = useApiRequest<Pet>('/api/pets/1', {
66
+ * pick: ['id', 'name'] as const
67
+ * });
68
+ *
69
+ * // With pick (nested dot notation)
70
+ * const { data } = useApiRequest('/api/user', {
71
+ * pick: ['person.name', 'person.email', 'status']
72
+ * });
73
+ * // Result: { person: { name: '...', email: '...' }, status: '...' }
74
+ *
75
+ * // With callbacks
76
+ * const { data } = useApiRequest<Pet>('/api/pets', {
77
+ * onRequest: (ctx) => ({ headers: { 'Authorization': `Bearer ${token}` } }),
78
+ * onSuccess: (pet) => console.log('Got pet:', pet),
79
+ * onError: (err) => console.error('Failed:', err),
80
+ * });
81
+ * ```
82
+ */
83
+ export function useApiRequest<T = any, Options extends ApiRequestOptions<T> = ApiRequestOptions<T>>(
84
+ url: string | (() => string),
85
+ options?: Options
86
+ ) {
87
+ const {
88
+ onRequest,
89
+ onSuccess,
90
+ onError,
91
+ onFinish,
92
+ skipGlobalCallbacks,
93
+ transform,
94
+ pick,
95
+ paginated,
96
+ initialPage,
97
+ initialPerPage,
98
+ paginationConfig,
99
+ ...fetchOptions
100
+ } = options || {};
101
+
102
+ // Resolve URL value for callbacks and pattern matching
103
+ const urlValue = typeof url === 'function' ? url() : url;
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // Pagination setup
107
+ // ---------------------------------------------------------------------------
108
+ const activePaginationConfig = paginationConfig ?? (paginated ? getGlobalApiPagination() : null);
109
+ const page = ref<number>(initialPage ?? activePaginationConfig?.request.defaults.page ?? 1);
110
+ const perPage = ref<number>(initialPerPage ?? activePaginationConfig?.request.defaults.perPage ?? 20);
111
+
112
+ // Reactive pagination state (populated after response)
113
+ const paginationState = ref<PaginationState>({
114
+ currentPage: page.value,
115
+ totalPages: 0,
116
+ total: 0,
117
+ perPage: perPage.value,
118
+ });
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Merge local and global callbacks
122
+ // ---------------------------------------------------------------------------
123
+ const mergedCallbacks = mergeCallbacks(
124
+ urlValue,
125
+ String(fetchOptions.method || 'GET'),
126
+ { onRequest, onSuccess, onError, onFinish },
127
+ skipGlobalCallbacks
128
+ );
129
+
130
+ // Apply global headers configuration (from composable or plugin)
131
+ const modifiedOptions = { ...fetchOptions };
132
+ const globalHeaders = getGlobalHeaders();
133
+ if (Object.keys(globalHeaders).length > 0) {
134
+ modifiedOptions.headers = {
135
+ ...globalHeaders,
136
+ ...modifiedOptions.headers, // User headers override global headers
137
+ };
138
+ }
139
+
140
+ // Apply global base URL from runtimeConfig.public.apiBaseUrl (if not already set per-composable)
141
+ if (!modifiedOptions.baseURL) {
142
+ modifiedOptions.baseURL = getGlobalBaseUrl();
143
+ }
144
+ if (!modifiedOptions.baseURL) {
145
+ console.warn(
146
+ '[nuxt-openapi-hyperfetch] No baseURL configured. Set runtimeConfig.public.apiBaseUrl in nuxt.config.ts or pass baseURL in options.'
147
+ );
148
+ }
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // Inject pagination request params before every request
152
+ // ---------------------------------------------------------------------------
153
+ if (paginated && activePaginationConfig) {
154
+ const existingOnRequestForPagination = modifiedOptions.onRequest;
155
+ modifiedOptions.onRequest = async (ctx) => {
156
+ // Inject page/perPage according to sendAs strategy
157
+ const paginationPayload = buildPaginationRequest(page.value, perPage.value, activePaginationConfig);
158
+ if (paginationPayload.query) {
159
+ ctx.options.query = { ...ctx.options.query, ...paginationPayload.query };
160
+ }
161
+ if (paginationPayload.body) {
162
+ ctx.options.body = {
163
+ ...(ctx.options.body && typeof ctx.options.body === 'object' ? ctx.options.body : {}),
164
+ ...paginationPayload.body,
165
+ };
166
+ }
167
+ if (paginationPayload.headers) {
168
+ ctx.options.headers = { ...ctx.options.headers, ...paginationPayload.headers };
169
+ }
170
+ if (existingOnRequestForPagination) {
171
+ await (existingOnRequestForPagination as Function)(ctx);
172
+ }
173
+ };
174
+ }
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // Extract pagination metadata from headers after response (metaSource: 'headers')
178
+ // ---------------------------------------------------------------------------
179
+ if (paginated && activePaginationConfig && activePaginationConfig.meta.metaSource === 'headers') {
180
+ const existingOnResponse = modifiedOptions.onResponse;
181
+ modifiedOptions.onResponse = async ({ response }) => {
182
+ const meta = extractPaginationMetaFromHeaders(response.headers, activePaginationConfig);
183
+ if (meta.total !== undefined) paginationState.value.total = meta.total;
184
+ if (meta.totalPages !== undefined) paginationState.value.totalPages = meta.totalPages;
185
+ if (meta.currentPage !== undefined) paginationState.value.currentPage = meta.currentPage;
186
+ if (meta.perPage !== undefined) paginationState.value.perPage = meta.perPage;
187
+ if (existingOnResponse) {
188
+ await (existingOnResponse as Function)({ response });
189
+ }
190
+ };
191
+ }
192
+
193
+ // If page/perPage refs change, re-trigger useFetch (add them to watch array)
194
+ if (paginated) {
195
+ modifiedOptions.watch = [...(modifiedOptions.watch ?? []), page, perPage];
196
+ }
197
+
198
+ // Pass onRequest to useFetch's native interceptor so async callbacks are
199
+ // properly awaited by ofetch before the request is sent.
200
+ if (mergedCallbacks.onRequest) {
201
+ const existingOnRequest = modifiedOptions.onRequest;
202
+ modifiedOptions.onRequest = async ({ options: fetchOpts }) => {
203
+ // Build context from the live options at request time
204
+ const requestContext: RequestContext = {
205
+ url: urlValue,
206
+ method: String(fetchOpts.method || modifiedOptions.method || 'GET'),
207
+ body: fetchOpts.body,
208
+ headers: fetchOpts.headers as Record<string, string> | undefined,
209
+ query: fetchOpts.query,
210
+ };
211
+ try {
212
+ const modifications = await mergedCallbacks.onRequest!(requestContext);
213
+ if (modifications && typeof modifications === 'object') {
214
+ applyRequestModifications(fetchOpts as Record<string, any>, modifications);
215
+ }
216
+ } catch (error) {
217
+ console.error('Error in merged onRequest callback:', error);
218
+ }
219
+ // Chain any pre-existing onRequest interceptor
220
+ if (existingOnRequest) {
221
+ await (existingOnRequest as Function)({ options: fetchOpts });
222
+ }
223
+ };
224
+ }
225
+
226
+ // Make the actual request using Nuxt's useFetch
227
+ const result = useFetch<T>(url, modifiedOptions);
228
+
229
+ // Create a ref for transformed data
230
+ type TransformedType = MaybeTransformed<T, Options>;
231
+ const transformedData = ref<TransformedType | null>(null);
232
+
233
+ // Track if callbacks have been executed to avoid duplicates
234
+ let successExecuted = false;
235
+ let errorExecuted = false;
236
+
237
+ // Watch for changes in data, error, and pending states
238
+ watch(
239
+ () => [result.data.value, result.error.value, result.pending.value] as const,
240
+ async ([data, error, pending], prev) => {
241
+ const [prevData, prevError, prevPending] = prev ?? [undefined, undefined, undefined];
242
+ // Apply transformations when data arrives
243
+ if (data && data !== prevData) {
244
+ // Unwrap dataKey for paginated body-based responses BEFORE pick/transform
245
+ let processedData: any =
246
+ paginated && activePaginationConfig && activePaginationConfig.meta.metaSource === 'body'
247
+ ? unwrapDataKey(data, activePaginationConfig)
248
+ : data;
249
+
250
+ // Extract body-based pagination meta from raw response
251
+ if (paginated && activePaginationConfig && activePaginationConfig.meta.metaSource === 'body') {
252
+ const meta = extractPaginationMetaFromBody(data, activePaginationConfig);
253
+ if (meta.total !== undefined) paginationState.value.total = meta.total;
254
+ if (meta.totalPages !== undefined) paginationState.value.totalPages = meta.totalPages;
255
+ if (meta.currentPage !== undefined) paginationState.value.currentPage = meta.currentPage;
256
+ if (meta.perPage !== undefined) paginationState.value.perPage = meta.perPage;
257
+ }
258
+
259
+ // Step 1: Apply pick if specified
260
+ if (pick) {
261
+ processedData = applyPick(processedData, pick);
262
+ }
263
+
264
+ // Step 2: Apply transform if specified
265
+ if (transform) {
266
+ try {
267
+ processedData = transform(processedData);
268
+ } catch (err) {
269
+ console.error('Error in transform function:', err);
270
+ }
271
+ }
272
+
273
+ // Update transformed data ref
274
+ transformedData.value = processedData as TransformedType;
275
+
276
+ // onSuccess - when data arrives and no error (using merged callback)
277
+ // NOTE: data !== null/undefined check instead of truthy to handle 0, false, ''
278
+ if (data != null && !error && !successExecuted && mergedCallbacks.onSuccess) {
279
+ successExecuted = true;
280
+ try {
281
+ await mergedCallbacks.onSuccess(processedData);
282
+ } catch (err) {
283
+ console.error('Error in merged onSuccess callback:', err);
284
+ }
285
+ }
286
+ }
287
+
288
+ // onError - when an error occurs (using merged callback)
289
+ if (error && error !== prevError && !errorExecuted && mergedCallbacks.onError) {
290
+ errorExecuted = true;
291
+ try {
292
+ await mergedCallbacks.onError(error);
293
+ } catch (err) {
294
+ console.error('Error in merged onError callback:', err);
295
+ }
296
+ }
297
+
298
+ // onFinish - when request completes (was pending, now not) (using merged callback)
299
+ if (prevPending && !pending && mergedCallbacks.onFinish) {
300
+ const finishContext: FinishContext<TransformedType> = {
301
+ data: transformedData.value ?? undefined,
302
+ error: error ?? undefined,
303
+ success: data != null && !error,
304
+ };
305
+
306
+ try {
307
+ await mergedCallbacks.onFinish(finishContext);
308
+ } catch (err) {
309
+ console.error('Error in merged onFinish callback:', err);
310
+ }
311
+ }
312
+ },
313
+ { immediate: true }
314
+ );
315
+
316
+ // Return result with transformed data and optional pagination
317
+ const baseResult = {
318
+ ...result,
319
+ data: transformedData as Ref<TransformedType | null>,
320
+ };
321
+
322
+ if (!paginated) return baseResult;
323
+
324
+ // Pagination computed helpers
325
+ const hasNextPage = computed(() => paginationState.value.currentPage < paginationState.value.totalPages);
326
+ const hasPrevPage = computed(() => paginationState.value.currentPage > 1);
327
+
328
+ const goToPage = (n: number) => {
329
+ page.value = n;
330
+ successExecuted = false;
331
+ errorExecuted = false;
332
+ };
333
+ const nextPage = () => { if (hasNextPage.value) goToPage(page.value + 1); };
334
+ const prevPage = () => { if (hasPrevPage.value) goToPage(page.value - 1); };
335
+ const setPerPage = (n: number) => {
336
+ perPage.value = n;
337
+ page.value = 1;
338
+ successExecuted = false;
339
+ errorExecuted = false;
340
+ };
341
+
342
+ return {
343
+ ...baseResult,
344
+ pagination: computed(() => ({
345
+ ...paginationState.value,
346
+ hasNextPage: hasNextPage.value,
347
+ hasPrevPage: hasPrevPage.value,
348
+ })),
349
+ goToPage,
350
+ nextPage,
351
+ prevPage,
352
+ setPerPage,
353
+ };
354
+ }