nuxt-custom-fetch 4.1.1 → 4.4.8

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/README.md CHANGED
@@ -1,38 +1,73 @@
1
1
  # Nuxt Custom Fetch
2
2
 
3
- A simple wrapper around Nuxt's `useAsyncData` to provide enhanced fetching capabilities with interceptors, request/response handling, and more.
3
+ `nuxt-custom-fetch` is a Nuxt 4 wrapper built on top of the official async-data primitives. It keeps a shared request layer with interceptors, deterministic key generation, param/query preprocessing, and a client compatibility fallback for calls made after mount.
4
4
 
5
- ## Version Compatibility
5
+ For new Nuxt 4 code, start with the official APIs first:
6
6
 
7
- - `v4`: Compatible with Nuxt v3.17.0 or higher
8
- - `v2`: Compatible with Nuxt v3.0.0 to v3.16.x
7
+ - `useFetch`
8
+ - `useAsyncData`
9
+ - `createUseFetch`
10
+ - `createUseAsyncData`
11
+ - `$fetch`
9
12
 
10
- ## Breaking Changes in v4
13
+ Use `CustomFetch` when you specifically need an extra request layer on top of those primitives, not as a replacement for them.
11
14
 
12
- 1. `http` method has been removed, use `request` instead
15
+ ## Compatibility
13
16
 
14
- ## Key Features
17
+ - `v4`: Nuxt `>= 4.4.0`
18
+ - `v2`: Nuxt `3.0.0` to `3.16.x`
15
19
 
16
- - Request lifecycle interceptors
17
- - Automatic hash-based key generation
18
- - Request parameter/query handling
19
- - Response transformation
20
- - Offline detection and handling
21
- - Debug logs for requests
22
- - Reactive fetching with `watch` support
23
- - Request cancellation with abort controller
20
+ ## Current Maintenance Summary
21
+
22
+ The current implementation is maintained around these guarantees:
23
+
24
+ - runtime behavior is aligned with Nuxt 4 async-data semantics where possible
25
+ - public method generics follow Nuxt `AsyncData` typing more closely
26
+ - reactive `key`, `baseURL`, `params`, `query`, `headers`, `body`, and `cache` values are resolved before each request
27
+ - generated keys include both `params` and `query`, which avoids stale client reuse when only one side changes
28
+ - same-key client compatibility requests share one async-data bucket, so `dedupe: 'cancel'` can abort the previous pending request
29
+ - the client compatibility path mirrors Nuxt 4 async-data behavior: `pending` follows the `pendingWhenIdle` config, `refreshNuxtData()` (the `app:data:refresh` hook) re-runs fallback requests, `getCachedData` is honored and successful data is written back to `nuxtApp.payload.data`
30
+ - timeouts and external abort signals are merged into one request signal (via `AbortSignal.timeout`/`AbortSignal.any` semantics), key watchers are only created for reactive keys, and a key change re-runs the request when `immediate`, prior data, or an in-flight request is present
31
+ - Vitest runtime tests and TypeScript type tests cover the wrapper behavior
32
+
33
+ ## When To Use This Module
34
+
35
+ `CustomFetch` is useful when you want:
36
+
37
+ - shared request and response interceptors
38
+ - deterministic hash-based request keys
39
+ - explicit `immutableKey` control
40
+ - param or query preprocessing through `handler`
41
+ - one request API that still works after mount on the client
42
+
43
+ If all you need is a typed composable with shared defaults, prefer Nuxt's official factories:
44
+
45
+ ```ts
46
+ export const useAPI = createUseFetch({
47
+ baseURL: '/api',
48
+ lazy: true
49
+ })
50
+
51
+ export const useCachedData = createUseAsyncData({
52
+ deep: false
53
+ })
54
+ ```
55
+
56
+ ## How It Works
57
+
58
+ - In `setup`, plugins, and other setup-compatible contexts, `CustomFetch` delegates back to `useAsyncData`.
59
+ - After mount on the client, or when `useAsyncData` is unavailable in the current context, it falls back to a compatibility mode.
60
+ - The compatibility mode still exposes `data`, `error`, `status`, `pending`, `refresh`, `execute`, and `clear`.
61
+ - The compatibility mode is not a full SSR payload or cache replacement.
62
+ - Calls that intentionally share the same `key` should keep `handler`, `deep`, `transform`, `pick`, `getCachedData`, and `default` consistent, matching Nuxt's keyed async-data rules.
24
63
 
25
64
  ## Installation
26
65
 
27
66
  ```bash
28
- npm install nuxt-custom-fetch
29
- # or
30
- yarn add nuxt-custom-fetch
31
- # or
32
67
  pnpm add nuxt-custom-fetch
33
68
  ```
34
69
 
35
- Then add the module to your `nuxt.config.ts`:
70
+ Register the module in `nuxt.config.ts`:
36
71
 
37
72
  ```ts
38
73
  export default defineNuxtConfig({
@@ -40,172 +75,176 @@ export default defineNuxtConfig({
40
75
  })
41
76
  ```
42
77
 
43
- ## Basic Usage
78
+ `CustomFetch` is auto-imported in Nuxt app code. In plain TypeScript helpers, importing it from `#imports` keeps editor support explicit.
44
79
 
45
- Create a global CustomFetch instance:
80
+ ## Quick Start
46
81
 
47
82
  ```ts
48
- const ajax = new CustomFetch({
49
- baseURL: 'https://api.example.com',
50
- // Optional configurations
51
- showLogs: true, // Show request logs in development
52
- immutableKey: false, // Enable to use only URL for generating cache keys
53
- // Optional request handler
54
- handler: (params) => {
55
- // Transform params/query before sending
56
- return params
57
- },
58
- // Optional offline handler
83
+ import { CustomFetch } from '#imports'
84
+
85
+ export const ajax = new CustomFetch({
86
+ baseURL: '/api',
87
+ showLogs: true,
88
+ handler: input => input,
59
89
  offline: () => {
60
- // Handle offline status
61
- console.log('Device is offline')
90
+ console.warn('Device is offline')
62
91
  }
63
92
  })
64
93
 
65
- // Available methods
66
- ajax.get('/api/users')
67
- ajax.post('/api/users', { body: { name: 'John' } })
68
- ajax.request('/api/users', { method: 'DELETE' })
94
+ export const getUsers = () =>
95
+ ajax.get<{ data: Array<{ id: number, name: string }> }>('/users')
96
+
97
+ export const createUser = (payload: { name: string }) =>
98
+ ajax.post<{ id: number, name: string }>('/users', {
99
+ body: payload
100
+ })
69
101
  ```
70
102
 
71
- ## Important Notes
103
+ Always `await` `ajax.get`, `ajax.post`, and `ajax.request` in setup-compatible code.
72
104
 
73
- ### Handling Requests in Client Components
105
+ ## Reactive Example
74
106
 
75
- 1. When using in client components, execute in `nextTick`, or set `{server: false}` to properly handle status changes.
107
+ ```ts
108
+ import { computed, ref } from 'vue'
109
+ import { CustomFetch } from '#imports'
110
+
111
+ const ajax = new CustomFetch({ baseURL: '/api' })
112
+
113
+ const page = ref(1)
114
+ const requestKey = computed(() => `list:${page.value}`)
115
+
116
+ const listState = await ajax.get<{
117
+ data: number[]
118
+ nums: number
119
+ }>('/get-list', {
120
+ key: requestKey,
121
+ params: { page }
122
+ }, {
123
+ watch: [page],
124
+ dedupe: 'cancel'
125
+ })
76
126
 
77
- 2. When using `refresh` and `execute` methods, note that parameters are not reactive, so they will always use the parameters from the first request.
127
+ page.value++
128
+ await listState.refresh()
129
+ ```
78
130
 
79
- 3. If you pass a reactive object with `watch` enabled, it will automatically trigger new requests when the watched values change.
131
+ ## Playground Real Examples
80
132
 
81
- ### Caching and Keys
133
+ The playground examples now use one consistent set of scenario names and helper names. The shared helper file lives in [playground/api/index.ts](playground/api/index.ts).
82
134
 
83
- The module generates hash-based keys for caching responses. You can:
84
- - Provide your own `key` for precise cache control
85
- - Enable `immutableKey` to use only the URL for generating cache keys (ignoring params/query)
135
+ ```ts
136
+ export const getGreeting = (params: Record<string, unknown>) =>
137
+ ajax.get<string>('/hello', { params })
138
+
139
+ export const getGreetingByUserId = (key: MaybeRefOrGetter<string>, { userId = 1 } = {}) =>
140
+ ajax.get<string>('/hello', {
141
+ key,
142
+ params: { userId }
143
+ }, {
144
+ default: () => '11'
145
+ })
146
+
147
+ export function getReactivePageList (page: Ref<number>) {
148
+ return ajax.get<{ data: number[], nums: number }>('/get-list', {
149
+ params: { page }
150
+ }, {
151
+ watch: [() => page.value]
152
+ })
153
+ }
154
+ ```
86
155
 
87
- ## Configuration Options
156
+ - Shared Greeting State: [playground/pages/example/v4-fetch.vue](playground/pages/example/v4-fetch.vue) and [playground/components/Test.vue](playground/components/Test.vue) use `getGreeting` to show that a page and a child component can share one keyed async-data bucket.
157
+ - Route-Driven Greeting: [playground/pages/example/v4-reactive-[id].vue](playground/pages/example/v4-reactive-%5Bid%5D.vue) uses `getGreetingByUserId` with a reactive key derived from the route.
158
+ - Reactive Page List: [playground/pages/example/reactive.vue](playground/pages/example/reactive.vue) uses `getReactivePageList` to show page-based refetching driven by a reactive page ref.
159
+ - Query Normalization: [playground/pages/example/handler.vue](playground/pages/example/handler.vue) shows how a `handler` can normalize and enrich list query parameters before the request is sent.
160
+ - Slow Metric Dedupe: [playground/pages/example/duplicate.vue](playground/pages/example/duplicate.vue) demonstrates same-key cancellation for repeated slow client requests with `dedupe: 'cancel'`.
161
+ - Manual Refresh & Clear: [playground/pages/example/test.vue](playground/pages/example/test.vue) uses `getGreeting` to compare `refresh()` and `clear()` across two independent keyed requests.
88
162
 
89
- ### CustomFetch Constructor Options
163
+ The remaining helper names follow the same rule: `getPageList` is the plain non-reactive list request, and `getDelayedPageMetric` is the intentionally slow metric request used for dedupe demonstrations.
90
164
 
91
- ```typescript
92
- // Create a new instance with configuration
93
- const ajax = new CustomFetch({
94
- baseURL: '', // Base URL for all requests
95
- immutableKey: false, // If true, only use URL for key generation (default: false)
96
- showLogs: true, // Show request logs (default: false in prod, true in dev)
97
-
98
- // Request handling
99
- useHandler: true, // Whether to use the handler function (default: true)
100
- handler: undefined, // Transform params/query before sending
101
-
102
- // Interceptors
103
- onRequest: undefined, // Before request is sent
104
- onRequestError: undefined, // When request error occurs
105
- onResponse: undefined, // After response is received
106
- onResponseError: undefined, // When response error occurs
107
-
108
- // Offline handling
109
- offline: undefined // Called when device is offline
110
- })
111
- ```
165
+ ## Request Semantics
112
166
 
113
- ### Request Method Options
114
-
115
- All request methods accept these parameters:
116
-
117
- ```typescript
118
- // Method signature example with proper TypeScript syntax
119
- function exampleUsage<DataT, ErrorT> () {
120
- // These are the parameters you would use
121
- return ajax.get<DataT, ErrorT>(
122
- 'https://api.example.com/endpoint', // URL (string)
123
- { // CustomFetchOptions (optional)
124
- params: { id: 123 }
125
- },
126
- { // AsyncDataOptions (optional)
127
- watch: ['someRef']
128
- }
129
- )
130
- }
131
- ```
167
+ ### Key generation and dedupe
132
168
 
133
- ## Advanced Examples
169
+ - Without an explicit `key`, the module hashes `url + method + resolved request options`.
170
+ - Both `params` and `query` participate in the generated key.
171
+ - `immutableKey: true` makes the generated key depend only on the URL.
172
+ - If you need exact cache control, provide your own `key`.
173
+ - Same key means shared async-data state.
174
+ - `dedupe: 'cancel'` aborts the previous in-flight request inside that shared state.
175
+ - `dedupe: 'defer'` reuses the existing pending request.
134
176
 
135
- ### API Module Pattern
177
+ ### Reactive inputs
136
178
 
137
- ```ts
138
- // api.ts
139
- export const userApi = {
140
- getUser: (id: string) =>
141
- ajax.get<UserData>(`/api/users/${id}`),
142
-
143
- createUser: (userData: UserCreatePayload) =>
144
- ajax.post<UserData>('/api/users', { body: userData }),
145
-
146
- updateUser: (id: string, userData: UserUpdatePayload) =>
147
- ajax.request<UserData>(`/api/users/${id}`, {
148
- method: 'PUT',
149
- body: userData
150
- })
151
- }
152
- ```
179
+ - `key`, `baseURL`, `params`, `query`, `headers`, `body`, and `cache` can be refs, computed values, or getters.
180
+ - Reactive inputs are deeply resolved before every request.
181
+ - Use `watch` when you want a reactive source to trigger a refetch.
153
182
 
154
- ### Using in Components
183
+ ### Handler behavior
155
184
 
156
- ```ts
157
- // UserProfile.vue
158
- import { userApi } from './api'
185
+ - `handler` receives a merged object built from `params` and `query`.
186
+ - If `query` is present, the processed output is written back to `query`.
187
+ - Otherwise the processed output is written back to `params`.
188
+ - Set `useHandler: false` on a request to bypass preprocessing.
189
+
190
+ ### Client compatibility mode
159
191
 
160
- // Option 1: Using await
161
- const { data: user, error, refresh } = await userApi.getUser('123')
192
+ - Client calls made after mount reuse existing same-key async-data state when available.
193
+ - If no Nuxt-managed keyed state exists yet, the module creates and caches a compatibility async-data instance by key.
194
+ - `refresh`, `execute`, `clear`, `watch`, status updates, and cancellation still work in this mode.
195
+ - This mode should not be treated as a full SSR payload cache replacement.
162
196
 
163
- // Option 2: Using without await
164
- const { data: user, pending, error, refresh } = userApi.getUser('123')
197
+ ## Public API
165
198
 
166
- // Using with reactive parameters and watch
167
- const userId = ref('123')
168
- const { data: user } = await userApi.getUser(userId.value, {}, {
169
- watch: [userId] // Will refetch when userId changes
199
+ ```ts
200
+ const ajax = new CustomFetch({
201
+ baseURL: '',
202
+ immutableKey: false,
203
+ showLogs: false,
204
+ useHandler: true,
205
+ handler: undefined,
206
+ onRequest: undefined,
207
+ onRequestError: undefined,
208
+ onResponse: undefined,
209
+ onResponseError: undefined,
210
+ offline: undefined
170
211
  })
171
212
  ```
172
213
 
173
- ## Types
214
+ Available methods:
174
215
 
175
- For detailed type information, see the TypeScript definitions:
216
+ - `ajax.get(url, config?, asyncDataOptions?)`
217
+ - `ajax.post(url, config?, asyncDataOptions?)`
218
+ - `ajax.request(url, { method, ...config }, asyncDataOptions?)`
176
219
 
177
- [use-async-data-type](https://nuxt.com/docs/api/composables/use-async-data#type)
220
+ The return value follows Nuxt's `AsyncData<...>` shape and can use the same `default`, `pick`, `transform`, `watch`, `dedupe`, and `timeout` options you already know from `useAsyncData`.
178
221
 
179
- ### useAsyncDataType
222
+ ## Typing Notes
180
223
 
181
- ```ts
182
- export declare class CustomFetch {
183
- baseURL: string
184
- immutableKey: boolean
185
- offline: typeof Noop
186
- showLogs: boolean
187
- constructor (config: CustomFetchOptions)
188
- request<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config: CustomFetchOptions & {
189
- method: FetchMethod
190
- }, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
191
- get<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
192
- post<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>
193
- }
224
+ - `CustomFetch` mirrors Nuxt async-data generics closely enough for `default`, `pick`, and `transform` to narrow the final `data` type.
225
+ - Playground examples and type tests cover explicit generics, default values, and reactive arguments.
226
+ - If you want a custom wrapper with only shared defaults, Nuxt's `createUseFetch` and `createUseAsyncData` remain the simpler choice.
194
227
 
195
- export type FetchMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT' | /* lowercase variants */ 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace' | 'connect' | undefined
228
+ ## Nuxt 4 API Reminders
196
229
 
197
- export interface CustomFetchOptions extends Omit<FetchOptions, 'method'> {
198
- key?: MaybeRefOrGetter<string>
199
- immutableKey?: boolean
200
- showLogs?: boolean
201
- baseURL?: string
202
- useHandler?: boolean
203
- handler?: (mergedObject: FetchOptions['params'] & FetchOptions['query']) => Record<string, any>
204
- offline?: () => void
205
- }
206
- ```
230
+ - `useFetch` is the official shortcut for `useAsyncData + $fetch`.
231
+ - `$fetch` alone inside SSR setup will fetch twice during hydration unless it is wrapped by `useAsyncData` or replaced with `useFetch`.
232
+ - Relative `useFetch` calls on the server forward headers and cookies automatically. Plain `$fetch` does not.
233
+ - `dedupe`, `timeout`, `watch`, reactive keys, and `AbortSignal` are part of Nuxt's async-data contract.
207
234
 
208
235
  ## Development
209
236
 
210
- - Run `npm run dev:prepare` to generate type stubs
211
- - Use `npm run dev` to start the playground in development mode
237
+ - `pnpm dev:prepare` builds stubs and prepares the playground
238
+ - `pnpm dev` starts the playground
239
+ - `pnpm dev:build` builds the playground
240
+ - `pnpm test` runs the Vitest suite
241
+ - `pnpm run test:coverage` generates a coverage report
242
+ - `pnpm run test:types` runs TypeScript type checks
243
+
244
+ ## References
245
+
246
+ - https://nuxt.com/docs/4.x/api/composables/create-use-async-data
247
+ - https://nuxt.com/docs/4.x/api/composables/create-use-fetch
248
+ - https://nuxt.com/docs/4.x/api/composables/use-async-data
249
+ - https://nuxt.com/docs/4.x/api/composables/use-fetch
250
+ - https://nuxt.com/docs/4.x/api/utils/dollarfetch
package/dist/module.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import * as _nuxt_schema from '@nuxt/schema';
1
+ import * as nuxt_schema from 'nuxt/schema';
2
2
 
3
3
  interface ModuleOptions {
4
4
  }
5
- declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
5
+ declare const _default: nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
6
6
 
7
7
  export { _default as default };
8
8
  export type { ModuleOptions };
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "configKey": "customFetch",
4
- "version": ">=3.17.0",
4
+ "version": ">=4.4.0",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -5,7 +5,7 @@ const module$1 = defineNuxtModule({
5
5
  meta: {
6
6
  name: "nuxt-custom-fetch",
7
7
  configKey: "customFetch",
8
- version: ">=3.17.0"
8
+ version: ">=4.4.0"
9
9
  },
10
10
  defaults: {},
11
11
  setup(options, nuxt) {
@@ -1,10 +1,14 @@
1
- import type { NitroFetchRequest } from 'nitro/types';
1
+ import type { NitroFetchRequest } from 'nitropack';
2
2
  import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
3
- import type { CustomFetchOptions, FetchMethod, Interceptors, KeysOf, PickFrom } from './type.js';
3
+ import type { CustomFetchOptions, CustomFetchRequestOptions, Interceptors, KeysOf, PickFrom } from './type.js';
4
4
  import { Noop } from './utils.js';
5
- type CustomFetchReturnValue<DataT, NuxtErrorDataT> = AsyncData<PickFrom<DataT, KeysOf<DataT>> | undefined, (NuxtErrorDataT extends Error | NuxtError<unknown> ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
5
+ type CustomFetchData<DataT, PickKeys extends KeysOf<DataT>, DefaultT> = DefaultT | PickFrom<DataT, PickKeys>;
6
+ type CustomFetchError<NuxtErrorDataT> = (NuxtErrorDataT extends Error | NuxtError<unknown> ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined;
7
+ type CustomFetchAsyncData<DataT, PickKeys extends KeysOf<DataT>, DefaultT, NuxtErrorDataT> = AsyncData<CustomFetchData<DataT, PickKeys, DefaultT>, CustomFetchError<NuxtErrorDataT>>;
8
+ type CustomFetchReturnValue<DataT, PickKeys extends KeysOf<DataT>, DefaultT, NuxtErrorDataT> = CustomFetchAsyncData<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
9
+ export declare function __resetCustomFetchCaches(): void;
6
10
  export declare class CustomFetch {
7
- baseURL: string;
11
+ baseURL: import("vue").MaybeRefOrGetter<string>;
8
12
  immutableKey: boolean;
9
13
  _config: CustomFetchOptions;
10
14
  _baseHandler: CustomFetchOptions['handler'];
@@ -13,10 +17,12 @@ export declare class CustomFetch {
13
17
  showLogs: boolean;
14
18
  constructor(config: CustomFetchOptions);
15
19
  private baseConfig;
16
- request<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config: CustomFetchOptions & {
17
- method: FetchMethod;
18
- }, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>;
19
- get<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>;
20
- post<DataT, NuxtErrorDataT = Error | null>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<DataT>): CustomFetchReturnValue<DataT, NuxtErrorDataT>;
20
+ private resolveFetchConfig;
21
+ request<ResT, NuxtErrorDataT = Error | null, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(url: NitroFetchRequest, config: CustomFetchRequestOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
22
+ request<ResT, NuxtErrorDataT = Error | null, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(url: NitroFetchRequest, config: CustomFetchRequestOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
23
+ get<ResT, NuxtErrorDataT = Error | null, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
24
+ get<ResT, NuxtErrorDataT = Error | null, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
25
+ post<ResT, NuxtErrorDataT = Error | null, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
26
+ post<ResT, NuxtErrorDataT = Error | null, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
21
27
  }
22
28
  export {};
@@ -1,9 +1,62 @@
1
- import { asyncDataDefaults, pendingWhenIdle } from "#build/nuxt.config.mjs";
2
- import { clearNuxtData, computed, createError, getCurrentScope, onScopeDispose, reactive, ref, shallowRef, toValue, unref, useAsyncData, useNuxtApp, useRequestFetch, useRuntimeConfig, watch } from "#imports";
3
1
  import { hash, serialize } from "ohash";
4
- import { generateOptionSegments, Noop, pick } from "./utils.js";
2
+ import { asyncDataDefaults, granularCachedData, pendingWhenIdle } from "#build/nuxt.config.mjs";
3
+ import { clearNuxtData, computed, createError, getCurrentScope, isRef, onScopeDispose, reactive, ref, shallowRef, toValue, unref, useAsyncData, useNuxtApp, useRequestFetch, useRuntimeConfig, watch } from "#imports";
4
+ import { generateOptionSegments, Noop, pick, resolveReactiveValue } from "./utils.js";
5
5
  const _cachedController = /* @__PURE__ */ new Map();
6
+ const _cachedClientAsyncData = /* @__PURE__ */ new Map();
7
+ const MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES = 50;
6
8
  const REPLACE_REG = /[-_]/g;
9
+ const FALLBACK_TO_CLIENT_ASYNC_DATA_RE = /component is already mounted|outside of a plugin|outside of a nuxt instance|requires access to the nuxt instance/i;
10
+ function createAbortController() {
11
+ return typeof AbortController !== "undefined" ? new AbortController() : void 0;
12
+ }
13
+ function linkAbortSignal(signal, controller) {
14
+ if (!signal || !controller) {
15
+ return;
16
+ }
17
+ if (signal.aborted) {
18
+ controller.abort(signal.reason);
19
+ return;
20
+ }
21
+ signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
22
+ }
23
+ function createMergedSignal(signals, timeout) {
24
+ const controller = createAbortController();
25
+ if (!controller) {
26
+ return void 0;
27
+ }
28
+ const sources = signals.filter((signal) => !!signal);
29
+ if (typeof timeout === "number" && timeout >= 0 && typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
30
+ sources.push(AbortSignal.timeout(timeout));
31
+ }
32
+ for (const signal of sources) {
33
+ linkAbortSignal(signal, controller);
34
+ }
35
+ return controller.signal;
36
+ }
37
+ function shouldFallbackToClientAsyncData(error) {
38
+ return error instanceof Error && FALLBACK_TO_CLIENT_ASYNC_DATA_RE.test(error.message);
39
+ }
40
+ function pruneClientAsyncDataCache() {
41
+ while (_cachedClientAsyncData.size > MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES) {
42
+ const oldestEntry = _cachedClientAsyncData.entries().next().value;
43
+ if (!oldestEntry) {
44
+ return;
45
+ }
46
+ const [, asyncData] = oldestEntry;
47
+ asyncData.clear();
48
+ }
49
+ }
50
+ export function __resetCustomFetchCaches() {
51
+ for (const controller of _cachedController.values()) {
52
+ controller.abort();
53
+ }
54
+ _cachedController.clear();
55
+ for (const asyncData of _cachedClientAsyncData.values()) {
56
+ asyncData.clear();
57
+ }
58
+ _cachedClientAsyncData.clear();
59
+ }
7
60
  export class CustomFetch {
8
61
  baseURL;
9
62
  immutableKey = false;
@@ -32,7 +85,9 @@ export class CustomFetch {
32
85
  };
33
86
  }
34
87
  baseConfig(config) {
35
- const { useHandler = true, handler, query = {}, params = {} } = config;
88
+ const { useHandler = true, handler } = config;
89
+ const query = resolveReactiveValue(toValue(config.query)) || {};
90
+ const params = resolveReactiveValue(toValue(config.params)) || {};
36
91
  const baseHandler = handler || this._baseHandler;
37
92
  const _name = Object.keys(query).length ? "query" : "params";
38
93
  const mergeObj = {
@@ -44,16 +99,79 @@ export class CustomFetch {
44
99
  }
45
100
  return { [_name]: { ...mergeObj } };
46
101
  }
102
+ resolveFetchConfig(config, timeout) {
103
+ const { handler: _handler, useHandler: _useHandler, ...rawConfig } = config;
104
+ const baseConfig = this.baseConfig(config);
105
+ const baseURL = toValue(rawConfig.baseURL);
106
+ const body = resolveReactiveValue(toValue(rawConfig.body));
107
+ const _cache = toValue(rawConfig.cache);
108
+ const cache = typeof _cache === "boolean" ? void 0 : _cache;
109
+ const headers = resolveReactiveValue(toValue(rawConfig.headers));
110
+ const method = toValue(rawConfig.method);
111
+ const params = resolveReactiveValue(toValue(baseConfig.params ?? rawConfig.params));
112
+ const query = resolveReactiveValue(toValue(baseConfig.query ?? rawConfig.query));
113
+ return {
114
+ ...rawConfig,
115
+ ...baseConfig,
116
+ baseURL,
117
+ body,
118
+ cache,
119
+ headers,
120
+ method,
121
+ params,
122
+ query,
123
+ timeout
124
+ };
125
+ }
47
126
  request(url, config, options = {}) {
48
- const app = useRuntimeConfig().app;
49
- config.baseURL ??= this.baseURL || app.baseURL;
50
- Object.assign(config, this.baseConfig(config));
51
- const generateOptionSegmentsWithConfig = generateOptionSegments(config);
52
- if (this.showLogs && import.meta.client) {
53
- const { body: _body, ...resetConfig } = config;
127
+ const runtimeConfig = useRuntimeConfig();
128
+ const resolvedConfig = {
129
+ ...config,
130
+ baseURL: config.baseURL ?? (toValue(this.baseURL) || runtimeConfig.app?.baseURL || "")
131
+ };
132
+ const {
133
+ immutableKey,
134
+ key: _key,
135
+ offline: _offline,
136
+ handler: _handlerConfig,
137
+ onRequest,
138
+ onRequestError,
139
+ onResponse,
140
+ onResponseError,
141
+ showLogs: _showLogs,
142
+ useHandler: _useHandler,
143
+ ...fetchConfig
144
+ } = resolvedConfig;
145
+ const offlineHandler = _offline ?? this.offline;
146
+ const showLogs = _showLogs ?? this.showLogs;
147
+ if (import.meta.client && typeof navigator !== "undefined" && !navigator.onLine) {
148
+ offlineHandler();
149
+ }
150
+ const interceptors = this._interceptors;
151
+ const requestFetch = useRequestFetch();
152
+ const requestBehaviorConfig = {
153
+ handler: _handlerConfig,
154
+ useHandler: _useHandler
155
+ };
156
+ const _config = reactive({ ...fetchConfig });
157
+ const getResolvedFetchConfig = (timeout) => this.resolveFetchConfig({
158
+ ..._config,
159
+ ...requestBehaviorConfig
160
+ }, timeout);
161
+ const initialFetchConfig = getResolvedFetchConfig(options.timeout);
162
+ if (import.meta.dev && import.meta.client && showLogs) {
163
+ const logConfig = Object.fromEntries(Object.entries({
164
+ baseURL: initialFetchConfig.baseURL,
165
+ cache: initialFetchConfig.cache,
166
+ headers: initialFetchConfig.headers,
167
+ key: toValue(resolvedConfig.key),
168
+ method: initialFetchConfig.method,
169
+ params: initialFetchConfig.params,
170
+ query: initialFetchConfig.query
171
+ }).filter(([, value]) => value !== void 0));
54
172
  let bodyLogs;
55
173
  try {
56
- bodyLogs = serialize(_body);
174
+ bodyLogs = serialize(initialFetchConfig.body);
57
175
  } catch (error) {
58
176
  console.warn("[Custom Fetch] couldn't serialize [Body]:", error);
59
177
  }
@@ -61,18 +179,12 @@ export class CustomFetch {
61
179
  "\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 [Custom Fetch] \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014",
62
180
  `[Request URL]: ${url}`,
63
181
  "",
64
- `[Query]: ${serialize(resetConfig)}`,
182
+ `[Query]: ${serialize(logConfig)}`,
65
183
  "",
66
184
  `[Body]: ${bodyLogs}`,
67
185
  "\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014"
68
186
  ].join("\n"));
69
187
  }
70
- const { onRequest, onRequestError, onResponse, onResponseError, offline, handler, useHandler, showLogs, immutableKey, ...asyncDataOptions } = config;
71
- if (import.meta.client && navigator && !navigator.onLine) {
72
- this.offline();
73
- }
74
- const interceptors = this._interceptors;
75
- const _config = reactive({ ...asyncDataOptions });
76
188
  const defaultOptions = {
77
189
  async onRequest(ctx) {
78
190
  const allFns = [interceptors.onRequest, onRequest].flat();
@@ -108,99 +220,265 @@ export class CustomFetch {
108
220
  }
109
221
  };
110
222
  const hashValue = ["custom_fetch:", url];
111
- if (import.meta.dev && !config.key && (this.immutableKey || immutableKey)) {
223
+ const useImmutableKey = immutableKey ?? this.immutableKey;
224
+ if (import.meta.dev && !config.key && useImmutableKey) {
112
225
  console.warn("[Custom Fetch] immutableKey is enabled, the key will be generated by hash([custom_fetch:, url])");
113
226
  }
114
- if (!this.immutableKey && !immutableKey) {
115
- hashValue.push(...generateOptionSegmentsWithConfig);
227
+ if (!useImmutableKey) {
228
+ hashValue.push(...generateOptionSegments({
229
+ ...initialFetchConfig,
230
+ method: initialFetchConfig.method ?? resolvedConfig.method
231
+ }));
116
232
  }
117
233
  const hashKey = hash(hashValue).replace(REPLACE_REG, "").slice(0, 10);
118
- const key = computed(() => toValue(config.key) || hashKey);
119
- watch(key, (key2, oldKey) => {
120
- if (oldKey) {
121
- _cachedController.get(oldKey)?.abort?.();
122
- _cachedController.delete(oldKey);
123
- } else {
124
- const controller2 = typeof AbortController !== "undefined" ? new AbortController() : {};
125
- _cachedController.set(key2, controller2);
126
- }
127
- });
128
- const _handler = () => {
129
- if (_cachedController.get(key.value)) {
130
- _cachedController.get(key.value)?.abort?.();
131
- }
132
- return useRequestFetch()(url, {
133
- signal: _cachedController.get(key.value)?.signal,
234
+ const key = computed(() => toValue(resolvedConfig.key) || hashKey);
235
+ const executeRequest = (executeOptions = {}) => {
236
+ const timeout = executeOptions.timeout ?? options.timeout;
237
+ const signal = createMergedSignal([executeOptions.signal], timeout);
238
+ return requestFetch(url, {
134
239
  ...defaultOptions,
135
- ..._config
240
+ ...getResolvedFetchConfig(timeout),
241
+ signal
242
+ });
243
+ };
244
+ const _handler = (_nuxtApp, context) => {
245
+ return executeRequest({
246
+ signal: context.signal,
247
+ timeout: options.timeout
136
248
  });
137
249
  };
138
- const controller = typeof AbortController !== "undefined" ? new AbortController() : {};
139
250
  const nuxtApp = useNuxtApp();
140
- if (import.meta.client && !nuxtApp.isHydrating) {
141
- if (nuxtApp._asyncData[key.value]?._deps) {
142
- nuxtApp._asyncData[key.value].execute({
143
- cause: "initial",
144
- dedupe: options.dedupe
145
- });
146
- return nuxtApp._asyncData[key.value];
147
- }
251
+ const createClientAsyncDataFallback = () => {
148
252
  const _ref = options.deep ? ref : shallowRef;
149
- options.default ??= () => asyncDataDefaults.value;
150
- const asyncData = {
151
- data: _ref(void 0),
152
- error: _ref(void 0),
153
- status: _ref("idle"),
154
- pending: _ref(false),
155
- clear: () => clearNuxtData(key.value)
253
+ const usePendingRef = pendingWhenIdle;
254
+ const getDefaultValue = () => {
255
+ if (options.default) {
256
+ return unref(options.default());
257
+ }
258
+ return asyncDataDefaults.value;
156
259
  };
157
- if (pendingWhenIdle) {
158
- asyncData.pending.value = true;
159
- }
160
- asyncData.status.value = "pending";
161
- const promise = new Promise((resolve, reject) => {
162
- try {
163
- resolve(_handler());
164
- _cachedController.set(key.value, controller);
165
- } catch (err) {
166
- reject(err);
260
+ const resolveCachedData = (cause = "refresh:manual") => {
261
+ if (options.getCachedData) {
262
+ return options.getCachedData(key.value, nuxtApp, { cause });
167
263
  }
168
- }).then(async (_result) => {
169
- let result = _result;
170
- if (options?.transform) {
171
- result = await options.transform(_result);
264
+ if (nuxtApp.isHydrating) {
265
+ return nuxtApp.payload?.data?.[key.value];
172
266
  }
173
- if (options?.pick) {
174
- result = pick(result, options.pick);
267
+ if (cause !== "refresh:manual" && cause !== "refresh:hook") {
268
+ return nuxtApp.static?.data?.[key.value];
175
269
  }
176
- asyncData.data.value = result;
177
- asyncData.error.value = asyncDataDefaults.errorValue;
178
- asyncData.status.value = "success";
179
- return asyncData;
180
- }).catch((error) => {
181
- asyncData.error.value = createError(error);
182
- asyncData.data.value = unref(options.default());
183
- asyncData.status.value = "error";
184
- return asyncData;
185
- }).finally(() => {
186
- if (pendingWhenIdle) {
187
- asyncData.pending.value = false;
270
+ return void 0;
271
+ };
272
+ const writePayloadData = (value) => {
273
+ if (nuxtApp.payload?.data) {
274
+ nuxtApp.payload.data[key.value] = value;
275
+ }
276
+ };
277
+ const isKeyReactive = isRef(resolvedConfig.key) || typeof resolvedConfig.key === "function";
278
+ let activeController;
279
+ let activeRequest;
280
+ let requestId = 0;
281
+ let hasData = false;
282
+ let keyChanging = false;
283
+ let stopKeyWatch;
284
+ let stopOptionWatch;
285
+ let stopRefreshHook;
286
+ const initialStatus = options.immediate === false ? "idle" : "pending";
287
+ const statusRef = _ref(initialStatus);
288
+ const pendingRef = usePendingRef ? _ref(initialStatus === "pending") : computed(() => statusRef.value === "pending");
289
+ const setPending = (value) => {
290
+ if (usePendingRef) {
291
+ pendingRef.value = value;
292
+ }
293
+ };
294
+ const stopWatchers = () => {
295
+ stopKeyWatch?.();
296
+ stopKeyWatch = void 0;
297
+ stopOptionWatch?.();
298
+ stopOptionWatch = void 0;
299
+ stopRefreshHook?.();
300
+ stopRefreshHook = void 0;
301
+ };
302
+ const asyncData = {
303
+ data: _ref(getDefaultValue()),
304
+ error: _ref(asyncDataDefaults.errorValue),
305
+ status: statusRef,
306
+ pending: pendingRef,
307
+ clear: () => {
308
+ stopWatchers();
309
+ activeController?.abort();
310
+ _cachedController.delete(key.value);
311
+ if (_cachedClientAsyncData.get(key.value) === asyncData) {
312
+ _cachedClientAsyncData.delete(key.value);
313
+ }
314
+ hasData = false;
315
+ asyncData.data.value = getDefaultValue();
316
+ asyncData.error.value = asyncDataDefaults.errorValue;
317
+ asyncData.status.value = "idle";
318
+ setPending(false);
319
+ clearNuxtData(key.value);
320
+ },
321
+ refresh: async (executeOptions) => {
322
+ await asyncData.execute(executeOptions);
323
+ },
324
+ execute: async (executeOptions) => {
325
+ const cause = executeOptions?.cause;
326
+ const dedupe = executeOptions?.dedupe ?? options.dedupe ?? "cancel";
327
+ if (activeRequest) {
328
+ if (dedupe === "defer") {
329
+ return activeRequest;
330
+ }
331
+ activeController?.abort();
332
+ }
333
+ if (granularCachedData || cause === "initial" || nuxtApp.isHydrating) {
334
+ const cachedData = resolveCachedData(cause);
335
+ if (cachedData !== void 0) {
336
+ writePayloadData(cachedData);
337
+ hasData = true;
338
+ asyncData.data.value = cachedData;
339
+ asyncData.error.value = asyncDataDefaults.errorValue;
340
+ asyncData.status.value = "success";
341
+ setPending(false);
342
+ return;
343
+ }
344
+ }
345
+ const currentRequestId = ++requestId;
346
+ const controller = createAbortController();
347
+ activeController = controller;
348
+ linkAbortSignal(executeOptions?.signal, controller);
349
+ if (controller) {
350
+ _cachedController.set(key.value, controller);
351
+ }
352
+ setPending(true);
353
+ asyncData.status.value = "pending";
354
+ asyncData.error.value = asyncDataDefaults.errorValue;
355
+ activeRequest = executeRequest({
356
+ ...executeOptions,
357
+ signal: controller?.signal
358
+ }).then(async (result) => {
359
+ if (currentRequestId !== requestId) {
360
+ return;
361
+ }
362
+ let data = result;
363
+ if (options.transform) {
364
+ data = await options.transform(result);
365
+ }
366
+ let finalData = data;
367
+ if (options.pick) {
368
+ finalData = pick(data, options.pick);
369
+ }
370
+ const value = finalData;
371
+ writePayloadData(value);
372
+ hasData = true;
373
+ asyncData.data.value = value;
374
+ asyncData.error.value = asyncDataDefaults.errorValue;
375
+ asyncData.status.value = "success";
376
+ }).catch((error) => {
377
+ if (currentRequestId !== requestId || controller?.signal.aborted) {
378
+ return;
379
+ }
380
+ hasData = false;
381
+ asyncData.error.value = createError(error);
382
+ asyncData.data.value = getDefaultValue();
383
+ asyncData.status.value = "error";
384
+ }).finally(() => {
385
+ if (currentRequestId !== requestId) {
386
+ return;
387
+ }
388
+ activeRequest = void 0;
389
+ activeController = void 0;
390
+ _cachedController.delete(key.value);
391
+ if (asyncData.status.value === "pending") {
392
+ asyncData.status.value = "idle";
393
+ }
394
+ setPending(false);
395
+ });
396
+ await activeRequest;
397
+ }
398
+ };
399
+ _cachedClientAsyncData.set(key.value, asyncData);
400
+ stopRefreshHook = nuxtApp.hook?.("app:data:refresh", async (keys) => {
401
+ if (!keys || keys.includes(key.value)) {
402
+ await asyncData.execute({ cause: "refresh:hook" });
188
403
  }
189
- _cachedController.delete(key.value);
190
404
  });
191
- asyncData.refresh = asyncData.execute = () => _handler().then((result) => asyncData.data.value = result);
405
+ if (isKeyReactive) {
406
+ stopKeyWatch = watch(key, (newKey, oldKey) => {
407
+ if (!((newKey || oldKey) && newKey !== oldKey)) {
408
+ return;
409
+ }
410
+ keyChanging = true;
411
+ const hadData = hasData;
412
+ const wasRunning = activeRequest !== void 0;
413
+ if (oldKey) {
414
+ _cachedController.get(oldKey)?.abort?.();
415
+ _cachedController.delete(oldKey);
416
+ if (_cachedClientAsyncData.get(oldKey) === asyncData) {
417
+ _cachedClientAsyncData.delete(oldKey);
418
+ }
419
+ }
420
+ _cachedClientAsyncData.set(newKey, asyncData);
421
+ const keyTriggersExecute = options._keyTriggersExecute !== false;
422
+ if (keyTriggersExecute && (options.immediate !== false || hadData || wasRunning)) {
423
+ void asyncData.execute({ cause: "watch" });
424
+ }
425
+ void Promise.resolve().then(() => {
426
+ keyChanging = false;
427
+ });
428
+ }, { flush: "sync" });
429
+ }
192
430
  const hasScope = getCurrentScope();
193
431
  if (options.watch) {
194
- const unsub = watch(options.watch, async () => {
195
- asyncData.refresh();
432
+ stopOptionWatch = watch(options.watch, async () => {
433
+ if (keyChanging) {
434
+ return;
435
+ }
436
+ await asyncData.refresh({ cause: "watch" });
196
437
  }, { flush: "post" });
197
- if (hasScope) {
198
- onScopeDispose(unsub);
438
+ }
439
+ if (!hasScope) {
440
+ pruneClientAsyncDataCache();
441
+ }
442
+ if (hasScope) {
443
+ onScopeDispose(stopWatchers);
444
+ }
445
+ if (options.immediate === false) {
446
+ return Promise.resolve(asyncData);
447
+ }
448
+ return asyncData.execute({ cause: "initial" }).then(() => asyncData);
449
+ };
450
+ const sharedAsyncData = nuxtApp._asyncData?.[key.value];
451
+ const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
452
+ if (import.meta.client && !nuxtApp.isHydrating) {
453
+ if (sharedAsyncData?._deps && typeof sharedAsyncData.execute === "function") {
454
+ void sharedAsyncData.execute({
455
+ cause: "initial",
456
+ dedupe: options.dedupe
457
+ });
458
+ return sharedAsyncData;
459
+ }
460
+ if (cachedClientAsyncData) {
461
+ if (options.immediate === false) {
462
+ return Promise.resolve(cachedClientAsyncData);
199
463
  }
464
+ return cachedClientAsyncData.execute({
465
+ cause: "initial",
466
+ dedupe: options.dedupe
467
+ }).then(() => cachedClientAsyncData);
468
+ }
469
+ return createClientAsyncDataFallback();
470
+ }
471
+ try {
472
+ return useAsyncData(key, _handler, options);
473
+ } catch (error) {
474
+ if (!import.meta.client || !shouldFallbackToClientAsyncData(error)) {
475
+ throw error;
476
+ }
477
+ if (import.meta.dev) {
478
+ console.warn("[Custom Fetch] Falling back to client compatibility mode outside setup-compatible async data context.");
200
479
  }
201
- return promise;
480
+ return createClientAsyncDataFallback();
202
481
  }
203
- return useAsyncData(key, _handler, options);
204
482
  }
205
483
  get(url, config = {}, options) {
206
484
  return this.request(url, {
@@ -1,25 +1,40 @@
1
1
  import type { MaybeRefOrGetter } from '#imports';
2
2
  import type { FetchOptions } from 'ofetch';
3
3
  export type { FetchContext, FetchResponse } from 'ofetch';
4
+ type NativeFetchValue = ArrayBuffer | Blob | Date | File | FormData | Headers | Request | URLSearchParams;
5
+ export type MaybeRefDeep<T> = T extends (...args: any[]) => any ? T : T extends NativeFetchValue ? MaybeRefOrGetter<T> : T extends Array<infer U> ? MaybeRefOrGetter<Array<MaybeRefDeep<U>>> : T extends ReadonlyArray<infer U> ? MaybeRefOrGetter<ReadonlyArray<MaybeRefDeep<U>>> : T extends object ? MaybeRefOrGetter<{
6
+ [K in keyof T]: MaybeRefDeep<T[K]>;
7
+ }> : MaybeRefOrGetter<T>;
4
8
  /** https://github.com/nuxt/nuxt/blob/edeb0759a455dbafd030f0b5ae1d5a39ad0dfc2a/packages/nuxt/src/app/composables/asyncData.ts#L20 */
5
9
  export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? keyof T extends K[number] ? T : K[number] extends never ? T : Pick<T, K[number]> : T;
6
10
  export type KeysOf<T> = Array<T extends T ? keyof T extends string ? keyof T : never : never>;
7
11
  export type FetchMethod = 'options' | 'GET' | 'POST' | 'get' | 'HEAD' | 'PATCH' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'post' | 'head' | 'patch' | 'put' | 'delete' | 'connect' | 'trace' | undefined;
8
- export interface CustomFetchOptions extends Omit<FetchOptions, 'method'> {
12
+ export interface ResolvedCustomFetchOptions extends Omit<FetchOptions, 'method'> {
13
+ method?: FetchMethod;
14
+ }
15
+ export interface CustomFetchOptions extends Omit<FetchOptions, 'method' | 'baseURL' | 'query' | 'params' | 'body' | 'headers' | 'cache'> {
9
16
  /** unique key for fetch */
10
17
  key?: MaybeRefOrGetter<string>;
11
18
  /** hash key for fetch, with [customFetch: + url] without query */
12
19
  immutableKey?: boolean;
13
20
  /** show logs */
14
21
  showLogs?: boolean;
15
- baseURL?: string;
22
+ baseURL?: MaybeRefOrGetter<string>;
23
+ query?: MaybeRefDeep<NonNullable<FetchOptions['query']>>;
24
+ params?: MaybeRefDeep<NonNullable<FetchOptions['params']>>;
25
+ body?: MaybeRefDeep<FetchOptions['body']>;
26
+ headers?: MaybeRefDeep<NonNullable<FetchOptions['headers']>>;
27
+ cache?: MaybeRefOrGetter<FetchOptions['cache']>;
16
28
  /** is use handler to deal with query or pramas */
17
29
  useHandler?: boolean;
18
30
  /** handler to deal with query or pramas */
19
- handler?: (mergedObject: FetchOptions['params'] & FetchOptions['query']) => Record<string, any>;
31
+ handler?: (mergedObject: Record<string, unknown>) => Record<string, unknown>;
20
32
  /** offline handler */
21
33
  offline?: () => void;
22
34
  }
35
+ export interface CustomFetchRequestOptions extends CustomFetchOptions {
36
+ method: FetchMethod;
37
+ }
23
38
  export interface Interceptors {
24
39
  onRequest?: FetchOptions['onRequest'];
25
40
  onRequestError?: FetchOptions['onRequestError'];
@@ -1,6 +1,9 @@
1
- import type { CustomFetchOptions, FetchMethod } from './type.js';
1
+ import type { MaybeRef } from '#imports';
2
+ import type { CustomFetchOptions, FetchMethod, MaybeRefDeep } from './type.js';
2
3
  export declare function Noop(): void;
4
+ export declare function resolveReactiveValue<T>(value: MaybeRefDeep<T>): T;
5
+ export declare function resolveReactiveValue<T>(value: T): T;
3
6
  export declare function generateOptionSegments<_ResT>(opts: CustomFetchOptions & {
4
- method: FetchMethod;
5
- }): (string | Record<string, string> | undefined)[];
7
+ method: MaybeRef<FetchMethod>;
8
+ }): (string | Record<string, unknown> | undefined)[];
6
9
  export declare function pick(obj: Record<string, any>, keys: string[]): any;
@@ -1,39 +1,86 @@
1
- import { reactive, toValue } from "#imports";
1
+ import { toValue } from "#imports";
2
2
  import { isPlainObject } from "@vue/shared";
3
3
  import { hash } from "ohash";
4
4
  export function Noop() {
5
5
  }
6
+ function getGlobalConstructor(name) {
7
+ const constructor = globalThis[name];
8
+ return typeof constructor === "function" ? constructor : void 0;
9
+ }
10
+ function isInstanceOf(value, constructor) {
11
+ return typeof constructor === "function" && value instanceof constructor;
12
+ }
13
+ function isBlobValue(value) {
14
+ return isInstanceOf(value, getGlobalConstructor("Blob"));
15
+ }
16
+ function isFileValue(value) {
17
+ return isInstanceOf(value, getGlobalConstructor("File"));
18
+ }
19
+ function isFormDataValue(value) {
20
+ return isInstanceOf(value, getGlobalConstructor("FormData"));
21
+ }
22
+ function isHeadersValue(value) {
23
+ return isInstanceOf(value, getGlobalConstructor("Headers"));
24
+ }
25
+ function isRequestValue(value) {
26
+ return isInstanceOf(value, getGlobalConstructor("Request"));
27
+ }
28
+ function isURLSearchParamsValue(value) {
29
+ return isInstanceOf(value, getGlobalConstructor("URLSearchParams"));
30
+ }
31
+ function isSpecialNativeValue(value) {
32
+ if (!value || typeof value !== "object") {
33
+ return false;
34
+ }
35
+ return value instanceof ArrayBuffer || isBlobValue(value) || value instanceof Date || isFileValue(value) || isFormDataValue(value) || isHeadersValue(value) || isRequestValue(value) || isURLSearchParamsValue(value);
36
+ }
37
+ export function resolveReactiveValue(value) {
38
+ const resolvedValue = toValue(value);
39
+ if (resolvedValue !== value) {
40
+ return resolveReactiveValue(resolvedValue);
41
+ }
42
+ if (Array.isArray(resolvedValue)) {
43
+ return resolvedValue.map((item) => resolveReactiveValue(item));
44
+ }
45
+ if (isSpecialNativeValue(resolvedValue)) {
46
+ return resolvedValue;
47
+ }
48
+ if (isPlainObject(resolvedValue)) {
49
+ return Object.fromEntries(Object.entries(resolvedValue).map(([key, item]) => [key, resolveReactiveValue(item)]));
50
+ }
51
+ return resolvedValue;
52
+ }
6
53
  export function generateOptionSegments(opts) {
7
54
  const segments = [
8
55
  toValue(opts.method)?.toUpperCase() || "GET",
9
56
  toValue(opts.baseURL)
10
57
  ];
11
- for (const _obj of [opts.params || opts.query]) {
12
- const obj = toValue(_obj);
58
+ for (const _obj of [opts.params, opts.query]) {
59
+ const obj = resolveReactiveValue(toValue(_obj));
13
60
  if (!obj) {
14
61
  continue;
15
62
  }
16
63
  const unwrapped = {};
17
64
  for (const [key, value] of Object.entries(obj)) {
18
- unwrapped[toValue(key)] = toValue(value);
65
+ unwrapped[String(toValue(key))] = resolveReactiveValue(value);
19
66
  }
20
67
  segments.push(unwrapped);
21
68
  }
22
- if (opts.body) {
23
- const value = toValue(opts.body);
69
+ if (opts.body !== void 0) {
70
+ const value = resolveReactiveValue(toValue(opts.body));
24
71
  if (!value) {
25
72
  segments.push(hash(value));
26
73
  } else if (value instanceof ArrayBuffer) {
27
- segments.push(hash(Object.fromEntries([...new Uint8Array(value).entries()].map(([k, v]) => [k, v.toString()]))));
28
- } else if (value instanceof FormData) {
74
+ segments.push(hash(Object.fromEntries(Array.from(new Uint8Array(value).entries(), ([key, item]) => [key, item.toString()]))));
75
+ } else if (isFormDataValue(value)) {
29
76
  const obj = {};
30
77
  for (const entry of value.entries()) {
31
78
  const [key, val] = entry;
32
- obj[key] = val instanceof File ? val.name : val;
79
+ obj[key] = isFileValue(val) ? val.name : val;
33
80
  }
34
81
  segments.push(hash(obj));
35
82
  } else if (isPlainObject(value)) {
36
- segments.push(hash(reactive(value)));
83
+ segments.push(hash(resolveReactiveValue(value)));
37
84
  } else {
38
85
  try {
39
86
  segments.push(hash(value));
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "type": "module",
4
- "version": "4.1.1",
5
- "packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
4
+ "version": "4.4.8",
5
+ "packageManager": "pnpm@11.7.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -26,6 +26,10 @@
26
26
  "echo:husky": "echo 'npx nano-staged' > .husky/pre-commit && echo 'npx --no-install commitlint --edit \"$1\"' > .husky/commit-msg",
27
27
  "lint": "eslint .",
28
28
  "lint:fix": "eslint . --fix",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest",
31
+ "test:coverage": "vitest run --coverage",
32
+ "test:types": "tsc -p tsconfig.json --noEmit",
29
33
  "prepare": "husky",
30
34
  "commit": "git-cz",
31
35
  "prerelease": "changelogen --prerelease && pnpm prepack && npm publish --tag alpha",
@@ -36,28 +40,34 @@
36
40
  "path": "node_modules/cz-git"
37
41
  }
38
42
  },
43
+ "peerDependencies": {
44
+ "nuxt": ">=4.4.0",
45
+ "vue": "^3.5.30"
46
+ },
39
47
  "dependencies": {
40
48
  "@vue/shared": "^3.5.30",
41
- "ohash": "^2.0.11",
42
- "vue": "^3.5.30"
49
+ "ohash": "^2.0.11"
43
50
  },
44
51
  "devDependencies": {
45
- "@antfu/eslint-config": "^7.7.0",
46
- "@commitlint/cli": "^20.4.3",
47
- "@commitlint/config-conventional": "^20.4.3",
48
- "@nuxt/kit": "4.3.1",
52
+ "@antfu/eslint-config": "^9.0.0",
53
+ "@commitlint/cli": "^21.0.2",
54
+ "@commitlint/config-conventional": "^21.0.2",
55
+ "@nuxt/kit": "4.4.8",
49
56
  "@nuxt/module-builder": "^1.0.2",
50
- "@nuxt/schema": "4.3.1",
51
- "@types/node": "^25.4.0",
57
+ "@nuxt/schema": "4.4.8",
58
+ "@types/node": "^25.5.0",
59
+ "@vitest/coverage-v8": "^4.1.9",
52
60
  "changelogen": "^0.6.2",
53
61
  "commitizen": "^4.3.1",
54
62
  "cz-git": "^1.12.0",
55
63
  "eslint": "^10.0.3",
56
64
  "husky": "^9.1.7",
57
- "nano-staged": "^0.9.0",
58
- "nitro": "npm:nitropack@^2.13.1",
59
- "nuxt": "4.3.1",
60
- "typescript": "5.9.3"
65
+ "nano-staged": "^1.0.2",
66
+ "nitropack": "^2.13.1",
67
+ "nuxt": "4.4.8",
68
+ "typescript": "6.0.3",
69
+ "vitest": "^4.1.9",
70
+ "vue": "^3.5.30"
61
71
  },
62
72
  "husky": {
63
73
  "hooks": {
@@ -65,6 +75,6 @@
65
75
  }
66
76
  },
67
77
  "nano-staged": {
68
- "*": "eslint . --fix"
78
+ "*": "eslint --fix"
69
79
  }
70
80
  }