nuxt-openapi-hyperfetch 0.2.7-alpha.1 → 0.2.8-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 (60) hide show
  1. package/.editorconfig +26 -26
  2. package/.prettierignore +17 -17
  3. package/CONTRIBUTING.md +291 -291
  4. package/INSTRUCTIONS.md +327 -327
  5. package/LICENSE +202 -202
  6. package/README.md +231 -231
  7. package/dist/cli/config.d.ts +9 -2
  8. package/dist/cli/config.js +1 -1
  9. package/dist/cli/logo.js +5 -5
  10. package/dist/cli/messages.d.ts +1 -0
  11. package/dist/cli/messages.js +2 -0
  12. package/dist/cli/prompts.d.ts +5 -0
  13. package/dist/cli/prompts.js +12 -0
  14. package/dist/cli/types.d.ts +1 -1
  15. package/dist/generators/components/connector-generator/templates.js +12 -12
  16. package/dist/generators/use-async-data/templates.js +17 -17
  17. package/dist/generators/use-fetch/templates.js +14 -14
  18. package/dist/index.js +39 -27
  19. package/dist/module/index.js +19 -0
  20. package/dist/module/types.d.ts +7 -0
  21. package/docs/API-REFERENCE.md +886 -886
  22. package/docs/generated-components.md +615 -615
  23. package/docs/headless-composables-ui.md +569 -569
  24. package/eslint.config.js +85 -85
  25. package/package.json +1 -1
  26. package/src/cli/config.ts +147 -140
  27. package/src/cli/logger.ts +124 -124
  28. package/src/cli/logo.ts +25 -25
  29. package/src/cli/messages.ts +4 -0
  30. package/src/cli/prompts.ts +14 -1
  31. package/src/cli/types.ts +50 -50
  32. package/src/generators/components/connector-generator/generator.ts +138 -138
  33. package/src/generators/components/connector-generator/templates.ts +254 -254
  34. package/src/generators/components/connector-generator/types.ts +34 -34
  35. package/src/generators/components/schema-analyzer/index.ts +44 -44
  36. package/src/generators/components/schema-analyzer/intent-detector.ts +187 -187
  37. package/src/generators/components/schema-analyzer/openapi-reader.ts +96 -96
  38. package/src/generators/components/schema-analyzer/resource-grouper.ts +166 -166
  39. package/src/generators/components/schema-analyzer/schema-field-mapper.ts +268 -268
  40. package/src/generators/components/schema-analyzer/types.ts +177 -177
  41. package/src/generators/nuxt-server/generator.ts +272 -272
  42. package/src/generators/shared/runtime/apiHelpers.ts +535 -535
  43. package/src/generators/shared/runtime/pagination.ts +323 -323
  44. package/src/generators/shared/runtime/useDeleteConnector.ts +109 -109
  45. package/src/generators/shared/runtime/useDetailConnector.ts +64 -64
  46. package/src/generators/shared/runtime/useFormConnector.ts +139 -139
  47. package/src/generators/shared/runtime/useListConnector.ts +148 -148
  48. package/src/generators/shared/runtime/zod-error-merger.ts +119 -119
  49. package/src/generators/shared/templates/api-callbacks-plugin.ts +399 -399
  50. package/src/generators/shared/templates/api-pagination-plugin.ts +158 -158
  51. package/src/generators/use-async-data/generator.ts +205 -205
  52. package/src/generators/use-async-data/runtime/useApiAsyncData.ts +329 -329
  53. package/src/generators/use-async-data/runtime/useApiAsyncDataRaw.ts +324 -324
  54. package/src/generators/use-async-data/templates.ts +257 -257
  55. package/src/generators/use-fetch/generator.ts +170 -170
  56. package/src/generators/use-fetch/runtime/useApiRequest.ts +354 -354
  57. package/src/generators/use-fetch/templates.ts +214 -214
  58. package/src/index.ts +305 -303
  59. package/src/module/index.ts +158 -133
  60. package/src/module/types.ts +39 -31
@@ -1,354 +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, 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
- }
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
+ }