nuxt-custom-fetch 4.1.0 → 4.4.0

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,71 @@
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
+ - Vitest runtime tests and TypeScript type tests cover the wrapper behavior
30
+
31
+ ## When To Use This Module
32
+
33
+ `CustomFetch` is useful when you want:
34
+
35
+ - shared request and response interceptors
36
+ - deterministic hash-based request keys
37
+ - explicit `immutableKey` control
38
+ - param or query preprocessing through `handler`
39
+ - one request API that still works after mount on the client
40
+
41
+ If all you need is a typed composable with shared defaults, prefer Nuxt's official factories:
42
+
43
+ ```ts
44
+ export const useAPI = createUseFetch({
45
+ baseURL: '/api',
46
+ lazy: true
47
+ })
48
+
49
+ export const useCachedData = createUseAsyncData({
50
+ deep: false
51
+ })
52
+ ```
53
+
54
+ ## How It Works
55
+
56
+ - In `setup`, plugins, and other setup-compatible contexts, `CustomFetch` delegates back to `useAsyncData`.
57
+ - After mount on the client, or when `useAsyncData` is unavailable in the current context, it falls back to a compatibility mode.
58
+ - The compatibility mode still exposes `data`, `error`, `status`, `pending`, `refresh`, `execute`, and `clear`.
59
+ - The compatibility mode is not a full SSR payload or cache replacement.
60
+ - 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
61
 
25
62
  ## Installation
26
63
 
27
64
  ```bash
28
- npm install nuxt-custom-fetch
29
- # or
30
- yarn add nuxt-custom-fetch
31
- # or
32
65
  pnpm add nuxt-custom-fetch
33
66
  ```
34
67
 
35
- Then add the module to your `nuxt.config.ts`:
68
+ Register the module in `nuxt.config.ts`:
36
69
 
37
70
  ```ts
38
71
  export default defineNuxtConfig({
@@ -40,172 +73,176 @@ export default defineNuxtConfig({
40
73
  })
41
74
  ```
42
75
 
43
- ## Basic Usage
76
+ `CustomFetch` is auto-imported in Nuxt app code. In plain TypeScript helpers, importing it from `#imports` keeps editor support explicit.
44
77
 
45
- Create a global CustomFetch instance:
78
+ ## Quick Start
46
79
 
47
80
  ```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
81
+ import { CustomFetch } from '#imports'
82
+
83
+ export const ajax = new CustomFetch({
84
+ baseURL: '/api',
85
+ showLogs: true,
86
+ handler: input => input,
59
87
  offline: () => {
60
- // Handle offline status
61
- console.log('Device is offline')
88
+ console.warn('Device is offline')
62
89
  }
63
90
  })
64
91
 
65
- // Available methods
66
- ajax.get('/api/users')
67
- ajax.post('/api/users', { body: { name: 'John' } })
68
- ajax.request('/api/users', { method: 'DELETE' })
92
+ export const getUsers = () =>
93
+ ajax.get<{ data: Array<{ id: number, name: string }> }>('/users')
94
+
95
+ export const createUser = (payload: { name: string }) =>
96
+ ajax.post<{ id: number, name: string }>('/users', {
97
+ body: payload
98
+ })
69
99
  ```
70
100
 
71
- ## Important Notes
101
+ Always `await` `ajax.get`, `ajax.post`, and `ajax.request` in setup-compatible code.
72
102
 
73
- ### Handling Requests in Client Components
103
+ ## Reactive Example
74
104
 
75
- 1. When using in client components, execute in `nextTick`, or set `{server: false}` to properly handle status changes.
105
+ ```ts
106
+ import { CustomFetch } from '#imports'
107
+ import { computed, ref } from 'vue'
108
+
109
+ const ajax = new CustomFetch({ baseURL: '/api' })
110
+
111
+ const page = ref(1)
112
+ const requestKey = computed(() => `list:${page.value}`)
113
+
114
+ const listState = await ajax.get<{
115
+ data: number[]
116
+ nums: number
117
+ }>('/get-list', {
118
+ key: requestKey,
119
+ params: { page }
120
+ }, {
121
+ watch: [page],
122
+ dedupe: 'cancel'
123
+ })
76
124
 
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.
125
+ page.value++
126
+ await listState.refresh()
127
+ ```
78
128
 
79
- 3. If you pass a reactive object with `watch` enabled, it will automatically trigger new requests when the watched values change.
129
+ ## Playground Real Examples
80
130
 
81
- ### Caching and Keys
131
+ 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
132
 
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)
133
+ ```ts
134
+ export const getGreeting = (params: Record<string, unknown>) =>
135
+ ajax.get<string>('/hello', { params })
136
+
137
+ export const getGreetingByUserId = (key: MaybeRefOrGetter<string>, { userId = 1 } = {}) =>
138
+ ajax.get<string>('/hello', {
139
+ key,
140
+ params: { userId }
141
+ }, {
142
+ default: () => '11'
143
+ })
144
+
145
+ export function getReactivePageList (page: Ref<number>) {
146
+ return ajax.get<{ data: number[], nums: number }>('/get-list', {
147
+ params: { page }
148
+ }, {
149
+ watch: [() => page.value]
150
+ })
151
+ }
152
+ ```
86
153
 
87
- ## Configuration Options
154
+ - 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.
155
+ - 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.
156
+ - 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.
157
+ - 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.
158
+ - 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'`.
159
+ - 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
160
 
89
- ### CustomFetch Constructor Options
161
+ 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
162
 
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
- ```
163
+ ## Request Semantics
112
164
 
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
- ```
165
+ ### Key generation and dedupe
132
166
 
133
- ## Advanced Examples
167
+ - Without an explicit `key`, the module hashes `url + method + resolved request options`.
168
+ - Both `params` and `query` participate in the generated key.
169
+ - `immutableKey: true` makes the generated key depend only on the URL.
170
+ - If you need exact cache control, provide your own `key`.
171
+ - Same key means shared async-data state.
172
+ - `dedupe: 'cancel'` aborts the previous in-flight request inside that shared state.
173
+ - `dedupe: 'defer'` reuses the existing pending request.
134
174
 
135
- ### API Module Pattern
175
+ ### Reactive inputs
136
176
 
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
- ```
177
+ - `key`, `baseURL`, `params`, `query`, `headers`, `body`, and `cache` can be refs, computed values, or getters.
178
+ - Reactive inputs are deeply resolved before every request.
179
+ - Use `watch` when you want a reactive source to trigger a refetch.
153
180
 
154
- ### Using in Components
181
+ ### Handler behavior
155
182
 
156
- ```ts
157
- // UserProfile.vue
158
- import { userApi } from './api'
183
+ - `handler` receives a merged object built from `params` and `query`.
184
+ - If `query` is present, the processed output is written back to `query`.
185
+ - Otherwise the processed output is written back to `params`.
186
+ - Set `useHandler: false` on a request to bypass preprocessing.
187
+
188
+ ### Client compatibility mode
159
189
 
160
- // Option 1: Using await
161
- const { data: user, error, refresh } = await userApi.getUser('123')
190
+ - Client calls made after mount reuse existing same-key async-data state when available.
191
+ - If no Nuxt-managed keyed state exists yet, the module creates and caches a compatibility async-data instance by key.
192
+ - `refresh`, `execute`, `clear`, `watch`, status updates, and cancellation still work in this mode.
193
+ - This mode should not be treated as a full SSR payload cache replacement.
162
194
 
163
- // Option 2: Using without await
164
- const { data: user, pending, error, refresh } = userApi.getUser('123')
195
+ ## Public API
165
196
 
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
197
+ ```ts
198
+ const ajax = new CustomFetch({
199
+ baseURL: '',
200
+ immutableKey: false,
201
+ showLogs: false,
202
+ useHandler: true,
203
+ handler: undefined,
204
+ onRequest: undefined,
205
+ onRequestError: undefined,
206
+ onResponse: undefined,
207
+ onResponseError: undefined,
208
+ offline: undefined
170
209
  })
171
210
  ```
172
211
 
173
- ## Types
212
+ Available methods:
174
213
 
175
- For detailed type information, see the TypeScript definitions:
214
+ - `ajax.get(url, config?, asyncDataOptions?)`
215
+ - `ajax.post(url, config?, asyncDataOptions?)`
216
+ - `ajax.request(url, { method, ...config }, asyncDataOptions?)`
176
217
 
177
- [use-async-data-type](https://nuxt.com/docs/api/composables/use-async-data#type)
218
+ 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
219
 
179
- ### useAsyncDataType
220
+ ## Typing Notes
180
221
 
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
- }
222
+ - `CustomFetch` mirrors Nuxt async-data generics closely enough for `default`, `pick`, and `transform` to narrow the final `data` type.
223
+ - Playground examples and type tests cover explicit generics, default values, and reactive arguments.
224
+ - If you want a custom wrapper with only shared defaults, Nuxt's `createUseFetch` and `createUseAsyncData` remain the simpler choice.
194
225
 
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
226
+ ## Nuxt 4 API Reminders
196
227
 
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
- ```
228
+ - `useFetch` is the official shortcut for `useAsyncData + $fetch`.
229
+ - `$fetch` alone inside SSR setup will fetch twice during hydration unless it is wrapped by `useAsyncData` or replaced with `useFetch`.
230
+ - Relative `useFetch` calls on the server forward headers and cookies automatically. Plain `$fetch` does not.
231
+ - `dedupe`, `timeout`, `watch`, reactive keys, and `AbortSignal` are part of Nuxt's async-data contract.
207
232
 
208
233
  ## Development
209
234
 
210
- - Run `npm run dev:prepare` to generate type stubs
211
- - Use `npm run dev` to start the playground in development mode
235
+ - `pnpm dev:prepare` builds stubs and prepares the playground
236
+ - `pnpm dev` starts the playground
237
+ - `pnpm dev:build` builds the playground
238
+ - `pnpm test` runs the Vitest suite
239
+ - `pnpm run test:coverage` generates a coverage report
240
+ - `pnpm run test:types` runs TypeScript type checks
241
+
242
+ ## References
243
+
244
+ - https://nuxt.com/docs/4.x/api/composables/create-use-async-data
245
+ - https://nuxt.com/docs/4.x/api/composables/create-use-fetch
246
+ - https://nuxt.com/docs/4.x/api/composables/use-async-data
247
+ - https://nuxt.com/docs/4.x/api/composables/use-fetch
248
+ - 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
1
  import type { NitroFetchRequest } from 'nitro/types';
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,48 @@
1
- import { asyncDataDefaults, pendingWhenIdle } from "#build/nuxt.config.mjs";
1
+ import { asyncDataDefaults } from "#build/nuxt.config.mjs";
2
2
  import { clearNuxtData, computed, createError, getCurrentScope, onScopeDispose, reactive, ref, shallowRef, toValue, unref, useAsyncData, useNuxtApp, useRequestFetch, useRuntimeConfig, watch } from "#imports";
3
3
  import { hash, serialize } from "ohash";
4
- import { generateOptionSegments, Noop, pick } from "./utils.js";
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();
19
+ return;
20
+ }
21
+ signal.addEventListener("abort", () => controller.abort(), { once: true });
22
+ }
23
+ function shouldFallbackToClientAsyncData(error) {
24
+ return error instanceof Error && FALLBACK_TO_CLIENT_ASYNC_DATA_RE.test(error.message);
25
+ }
26
+ function pruneClientAsyncDataCache() {
27
+ while (_cachedClientAsyncData.size > MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES) {
28
+ const oldestEntry = _cachedClientAsyncData.entries().next().value;
29
+ if (!oldestEntry) {
30
+ return;
31
+ }
32
+ const [, asyncData] = oldestEntry;
33
+ asyncData.clear();
34
+ }
35
+ }
36
+ export function __resetCustomFetchCaches() {
37
+ for (const controller of _cachedController.values()) {
38
+ controller.abort();
39
+ }
40
+ _cachedController.clear();
41
+ for (const asyncData of _cachedClientAsyncData.values()) {
42
+ asyncData.clear();
43
+ }
44
+ _cachedClientAsyncData.clear();
45
+ }
7
46
  export class CustomFetch {
8
47
  baseURL;
9
48
  immutableKey = false;
@@ -32,7 +71,9 @@ export class CustomFetch {
32
71
  };
33
72
  }
34
73
  baseConfig(config) {
35
- const { useHandler = true, handler, query = {}, params = {} } = config;
74
+ const { useHandler = true, handler } = config;
75
+ const query = resolveReactiveValue(toValue(config.query)) || {};
76
+ const params = resolveReactiveValue(toValue(config.params)) || {};
36
77
  const baseHandler = handler || this._baseHandler;
37
78
  const _name = Object.keys(query).length ? "query" : "params";
38
79
  const mergeObj = {
@@ -44,16 +85,78 @@ export class CustomFetch {
44
85
  }
45
86
  return { [_name]: { ...mergeObj } };
46
87
  }
88
+ resolveFetchConfig(config, timeout) {
89
+ const { handler: _handler, useHandler: _useHandler, ...rawConfig } = config;
90
+ const baseConfig = this.baseConfig(config);
91
+ const baseURL = toValue(rawConfig.baseURL);
92
+ const body = resolveReactiveValue(toValue(rawConfig.body));
93
+ const cache = toValue(rawConfig.cache);
94
+ const headers = resolveReactiveValue(toValue(rawConfig.headers));
95
+ const method = toValue(rawConfig.method);
96
+ const params = resolveReactiveValue(toValue(baseConfig.params ?? rawConfig.params));
97
+ const query = resolveReactiveValue(toValue(baseConfig.query ?? rawConfig.query));
98
+ return {
99
+ ...rawConfig,
100
+ ...baseConfig,
101
+ baseURL,
102
+ body,
103
+ cache,
104
+ headers,
105
+ method,
106
+ params,
107
+ query,
108
+ timeout
109
+ };
110
+ }
47
111
  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;
112
+ const runtimeConfig = useRuntimeConfig();
113
+ const resolvedConfig = {
114
+ ...config,
115
+ baseURL: config.baseURL ?? (toValue(this.baseURL) || runtimeConfig.app?.baseURL || "")
116
+ };
117
+ const {
118
+ immutableKey,
119
+ key: _key,
120
+ offline: _offline,
121
+ handler: _handlerConfig,
122
+ onRequest,
123
+ onRequestError,
124
+ onResponse,
125
+ onResponseError,
126
+ showLogs: _showLogs,
127
+ useHandler: _useHandler,
128
+ ...fetchConfig
129
+ } = resolvedConfig;
130
+ const offlineHandler = _offline ?? this.offline;
131
+ const showLogs = _showLogs ?? this.showLogs;
132
+ if (import.meta.client && typeof navigator !== "undefined" && !navigator.onLine) {
133
+ offlineHandler();
134
+ }
135
+ const interceptors = this._interceptors;
136
+ const requestFetch = useRequestFetch();
137
+ const requestBehaviorConfig = {
138
+ handler: _handlerConfig,
139
+ useHandler: _useHandler
140
+ };
141
+ const _config = reactive({ ...fetchConfig });
142
+ const getResolvedFetchConfig = (timeout) => this.resolveFetchConfig({
143
+ ..._config,
144
+ ...requestBehaviorConfig
145
+ }, timeout);
146
+ const initialFetchConfig = getResolvedFetchConfig(options.timeout);
147
+ if (import.meta.dev && import.meta.client && showLogs) {
148
+ const logConfig = Object.fromEntries(Object.entries({
149
+ baseURL: initialFetchConfig.baseURL,
150
+ cache: initialFetchConfig.cache,
151
+ headers: initialFetchConfig.headers,
152
+ key: toValue(resolvedConfig.key),
153
+ method: initialFetchConfig.method,
154
+ params: initialFetchConfig.params,
155
+ query: initialFetchConfig.query
156
+ }).filter(([, value]) => value !== void 0));
54
157
  let bodyLogs;
55
158
  try {
56
- bodyLogs = serialize(_body);
159
+ bodyLogs = serialize(initialFetchConfig.body);
57
160
  } catch (error) {
58
161
  console.warn("[Custom Fetch] couldn't serialize [Body]:", error);
59
162
  }
@@ -61,18 +164,12 @@ export class CustomFetch {
61
164
  "\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
165
  `[Request URL]: ${url}`,
63
166
  "",
64
- `[Query]: ${serialize(resetConfig)}`,
167
+ `[Query]: ${serialize(logConfig)}`,
65
168
  "",
66
169
  `[Body]: ${bodyLogs}`,
67
170
  "\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
171
  ].join("\n"));
69
172
  }
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
173
  const defaultOptions = {
77
174
  async onRequest(ctx) {
78
175
  const allFns = [interceptors.onRequest, onRequest].flat();
@@ -108,99 +205,197 @@ export class CustomFetch {
108
205
  }
109
206
  };
110
207
  const hashValue = ["custom_fetch:", url];
111
- if (import.meta.dev && !config.key && (this.immutableKey || immutableKey)) {
208
+ const useImmutableKey = immutableKey ?? this.immutableKey;
209
+ if (import.meta.dev && !config.key && useImmutableKey) {
112
210
  console.warn("[Custom Fetch] immutableKey is enabled, the key will be generated by hash([custom_fetch:, url])");
113
211
  }
114
- if (!this.immutableKey && !immutableKey) {
115
- hashValue.push(...generateOptionSegmentsWithConfig);
212
+ if (!useImmutableKey) {
213
+ hashValue.push(...generateOptionSegments({
214
+ ...initialFetchConfig,
215
+ method: initialFetchConfig.method ?? resolvedConfig.method
216
+ }));
116
217
  }
117
218
  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,
219
+ const key = computed(() => toValue(resolvedConfig.key) || hashKey);
220
+ const executeRequest = (executeOptions = {}) => {
221
+ const controller = createAbortController();
222
+ linkAbortSignal(executeOptions.signal, controller);
223
+ return requestFetch(url, {
134
224
  ...defaultOptions,
135
- ..._config
225
+ ...getResolvedFetchConfig(executeOptions.timeout ?? options.timeout),
226
+ signal: controller?.signal
136
227
  });
137
228
  };
138
- const controller = typeof AbortController !== "undefined" ? new AbortController() : {};
139
- 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
- }
229
+ const _handler = (_nuxtApp, context) => {
230
+ return executeRequest({
231
+ signal: context.signal,
232
+ timeout: options.timeout
233
+ });
234
+ };
235
+ const createClientAsyncDataFallback = () => {
148
236
  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)
237
+ const getDefaultValue = () => {
238
+ if (options.default) {
239
+ return unref(options.default());
240
+ }
241
+ return asyncDataDefaults.value;
156
242
  };
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);
243
+ let activeController;
244
+ let activeRequest;
245
+ let requestId = 0;
246
+ let stopKeyWatch;
247
+ let stopOptionWatch;
248
+ const stopWatchers = () => {
249
+ stopKeyWatch?.();
250
+ stopKeyWatch = void 0;
251
+ stopOptionWatch?.();
252
+ stopOptionWatch = void 0;
253
+ };
254
+ const asyncData = {
255
+ data: _ref(getDefaultValue()),
256
+ error: _ref(asyncDataDefaults.errorValue),
257
+ status: _ref(options.immediate === false ? "idle" : "pending"),
258
+ pending: _ref(options.immediate !== false),
259
+ clear: () => {
260
+ stopWatchers();
261
+ activeController?.abort();
262
+ _cachedController.delete(key.value);
263
+ if (_cachedClientAsyncData.get(key.value) === asyncData) {
264
+ _cachedClientAsyncData.delete(key.value);
265
+ }
266
+ asyncData.data.value = getDefaultValue();
267
+ asyncData.error.value = asyncDataDefaults.errorValue;
268
+ asyncData.status.value = "idle";
269
+ asyncData.pending.value = false;
270
+ clearNuxtData(key.value);
271
+ },
272
+ refresh: async (executeOptions) => {
273
+ await asyncData.execute(executeOptions);
274
+ },
275
+ execute: async (executeOptions) => {
276
+ const dedupe = executeOptions?.dedupe ?? options.dedupe ?? "cancel";
277
+ if (activeRequest) {
278
+ if (dedupe === "defer") {
279
+ return activeRequest;
280
+ }
281
+ activeController?.abort();
282
+ }
283
+ const currentRequestId = ++requestId;
284
+ const controller = createAbortController();
285
+ activeController = controller;
286
+ linkAbortSignal(executeOptions?.signal, controller);
287
+ if (controller) {
288
+ _cachedController.set(key.value, controller);
289
+ }
290
+ asyncData.pending.value = true;
291
+ asyncData.status.value = "pending";
292
+ asyncData.error.value = asyncDataDefaults.errorValue;
293
+ activeRequest = executeRequest({
294
+ ...executeOptions,
295
+ signal: controller?.signal
296
+ }).then(async (result) => {
297
+ if (currentRequestId !== requestId) {
298
+ return;
299
+ }
300
+ let data = result;
301
+ if (options.transform) {
302
+ data = await options.transform(result);
303
+ }
304
+ let finalData = data;
305
+ if (options.pick) {
306
+ finalData = pick(data, options.pick);
307
+ }
308
+ asyncData.data.value = finalData;
309
+ asyncData.error.value = asyncDataDefaults.errorValue;
310
+ asyncData.status.value = "success";
311
+ }).catch((error) => {
312
+ if (currentRequestId !== requestId || controller?.signal.aborted) {
313
+ return;
314
+ }
315
+ asyncData.error.value = createError(error);
316
+ asyncData.data.value = getDefaultValue();
317
+ asyncData.status.value = "error";
318
+ }).finally(() => {
319
+ if (currentRequestId !== requestId) {
320
+ return;
321
+ }
322
+ activeRequest = void 0;
323
+ activeController = void 0;
324
+ _cachedController.delete(key.value);
325
+ if (asyncData.status.value === "pending") {
326
+ asyncData.status.value = "idle";
327
+ }
328
+ asyncData.pending.value = false;
329
+ });
330
+ await activeRequest;
167
331
  }
168
- }).then(async (_result) => {
169
- let result = _result;
170
- if (options?.transform) {
171
- result = await options.transform(_result);
332
+ };
333
+ _cachedClientAsyncData.set(key.value, asyncData);
334
+ stopKeyWatch = watch(key, (newKey, oldKey) => {
335
+ if (oldKey) {
336
+ _cachedController.get(oldKey)?.abort?.();
337
+ _cachedController.delete(oldKey);
338
+ if (_cachedClientAsyncData.get(oldKey) === asyncData) {
339
+ _cachedClientAsyncData.delete(oldKey);
340
+ }
172
341
  }
173
- if (options?.pick) {
174
- result = pick(result, options.pick);
342
+ if (newKey !== oldKey) {
343
+ _cachedClientAsyncData.set(newKey, asyncData);
175
344
  }
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;
345
+ if (newKey !== oldKey && options.immediate !== false) {
346
+ void asyncData.execute({ cause: "watch" });
188
347
  }
189
- _cachedController.delete(key.value);
190
348
  });
191
- asyncData.refresh = asyncData.execute = () => _handler().then((result) => asyncData.data.value = result);
192
349
  const hasScope = getCurrentScope();
193
350
  if (options.watch) {
194
- const unsub = watch(options.watch, async () => {
195
- asyncData.refresh();
351
+ stopOptionWatch = watch(options.watch, async () => {
352
+ await asyncData.refresh({ cause: "watch" });
196
353
  }, { flush: "post" });
197
- if (hasScope) {
198
- onScopeDispose(unsub);
354
+ }
355
+ if (!hasScope) {
356
+ pruneClientAsyncDataCache();
357
+ }
358
+ if (hasScope) {
359
+ onScopeDispose(stopWatchers);
360
+ }
361
+ if (options.immediate === false) {
362
+ return Promise.resolve(asyncData);
363
+ }
364
+ return asyncData.execute({ cause: "initial" }).then(() => asyncData);
365
+ };
366
+ const nuxtApp = useNuxtApp();
367
+ const sharedAsyncData = nuxtApp._asyncData?.[key.value];
368
+ const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
369
+ if (import.meta.client && !nuxtApp.isHydrating) {
370
+ if (sharedAsyncData?._deps && typeof sharedAsyncData.execute === "function") {
371
+ void sharedAsyncData.execute({
372
+ cause: "initial",
373
+ dedupe: options.dedupe
374
+ });
375
+ return sharedAsyncData;
376
+ }
377
+ if (cachedClientAsyncData) {
378
+ if (options.immediate === false) {
379
+ return Promise.resolve(cachedClientAsyncData);
199
380
  }
381
+ return cachedClientAsyncData.execute({
382
+ cause: "initial",
383
+ dedupe: options.dedupe
384
+ }).then(() => cachedClientAsyncData);
385
+ }
386
+ return createClientAsyncDataFallback();
387
+ }
388
+ try {
389
+ return useAsyncData(key, _handler, options);
390
+ } catch (error) {
391
+ if (!import.meta.client || !shouldFallbackToClientAsyncData(error)) {
392
+ throw error;
393
+ }
394
+ if (import.meta.dev) {
395
+ console.warn("[Custom Fetch] Falling back to client compatibility mode outside setup-compatible async data context.");
200
396
  }
201
- return promise;
397
+ return createClientAsyncDataFallback();
202
398
  }
203
- return useAsyncData(key, _handler, options);
204
399
  }
205
400
  get(url, config = {}, options) {
206
401
  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,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "type": "module",
4
- "version": "4.1.0",
4
+ "version": "4.4.0",
5
5
  "packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -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",
@@ -42,13 +46,14 @@
42
46
  "vue": "^3.5.30"
43
47
  },
44
48
  "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",
49
+ "@antfu/eslint-config": "^7.7.3",
50
+ "@commitlint/cli": "^20.5.0",
51
+ "@commitlint/config-conventional": "^20.5.0",
52
+ "@nuxt/kit": "4.4.2",
49
53
  "@nuxt/module-builder": "^1.0.2",
50
- "@nuxt/schema": "4.3.1",
51
- "@types/node": "^25.4.0",
54
+ "@nuxt/schema": "4.4.2",
55
+ "@types/node": "^25.5.0",
56
+ "@vitest/coverage-v8": "^3.2.4",
52
57
  "changelogen": "^0.6.2",
53
58
  "commitizen": "^4.3.1",
54
59
  "cz-git": "^1.12.0",
@@ -56,8 +61,9 @@
56
61
  "husky": "^9.1.7",
57
62
  "nano-staged": "^0.9.0",
58
63
  "nitro": "npm:nitropack@^2.13.1",
59
- "nuxt": "4.3.1",
60
- "typescript": "5.9.3"
64
+ "nuxt": "4.4.2",
65
+ "typescript": "5.9.3",
66
+ "vitest": "^3.2.4"
61
67
  },
62
68
  "husky": {
63
69
  "hooks": {