nuxt-custom-fetch 4.4.0 → 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
@@ -26,6 +26,8 @@ The current implementation is maintained around these guarantees:
26
26
  - reactive `key`, `baseURL`, `params`, `query`, `headers`, `body`, and `cache` values are resolved before each request
27
27
  - generated keys include both `params` and `query`, which avoids stale client reuse when only one side changes
28
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
29
31
  - Vitest runtime tests and TypeScript type tests cover the wrapper behavior
30
32
 
31
33
  ## When To Use This Module
@@ -103,8 +105,8 @@ Always `await` `ajax.get`, `ajax.post`, and `ajax.request` in setup-compatible c
103
105
  ## Reactive Example
104
106
 
105
107
  ```ts
106
- import { CustomFetch } from '#imports'
107
108
  import { computed, ref } from 'vue'
109
+ import { CustomFetch } from '#imports'
108
110
 
109
111
  const ajax = new CustomFetch({ baseURL: '/api' })
110
112
 
@@ -1,4 +1,4 @@
1
- import type { NitroFetchRequest } from 'nitro/types';
1
+ import type { NitroFetchRequest } from 'nitropack';
2
2
  import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
3
3
  import type { CustomFetchOptions, CustomFetchRequestOptions, Interceptors, KeysOf, PickFrom } from './type.js';
4
4
  import { Noop } from './utils.js';
@@ -1,6 +1,6 @@
1
- import { asyncDataDefaults } 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";
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
4
  import { generateOptionSegments, Noop, pick, resolveReactiveValue } from "./utils.js";
5
5
  const _cachedController = /* @__PURE__ */ new Map();
6
6
  const _cachedClientAsyncData = /* @__PURE__ */ new Map();
@@ -15,10 +15,24 @@ function linkAbortSignal(signal, controller) {
15
15
  return;
16
16
  }
17
17
  if (signal.aborted) {
18
- controller.abort();
18
+ controller.abort(signal.reason);
19
19
  return;
20
20
  }
21
- signal.addEventListener("abort", () => controller.abort(), { once: true });
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;
22
36
  }
23
37
  function shouldFallbackToClientAsyncData(error) {
24
38
  return error instanceof Error && FALLBACK_TO_CLIENT_ASYNC_DATA_RE.test(error.message);
@@ -90,7 +104,8 @@ export class CustomFetch {
90
104
  const baseConfig = this.baseConfig(config);
91
105
  const baseURL = toValue(rawConfig.baseURL);
92
106
  const body = resolveReactiveValue(toValue(rawConfig.body));
93
- const cache = toValue(rawConfig.cache);
107
+ const _cache = toValue(rawConfig.cache);
108
+ const cache = typeof _cache === "boolean" ? void 0 : _cache;
94
109
  const headers = resolveReactiveValue(toValue(rawConfig.headers));
95
110
  const method = toValue(rawConfig.method);
96
111
  const params = resolveReactiveValue(toValue(baseConfig.params ?? rawConfig.params));
@@ -218,12 +233,12 @@ export class CustomFetch {
218
233
  const hashKey = hash(hashValue).replace(REPLACE_REG, "").slice(0, 10);
219
234
  const key = computed(() => toValue(resolvedConfig.key) || hashKey);
220
235
  const executeRequest = (executeOptions = {}) => {
221
- const controller = createAbortController();
222
- linkAbortSignal(executeOptions.signal, controller);
236
+ const timeout = executeOptions.timeout ?? options.timeout;
237
+ const signal = createMergedSignal([executeOptions.signal], timeout);
223
238
  return requestFetch(url, {
224
239
  ...defaultOptions,
225
- ...getResolvedFetchConfig(executeOptions.timeout ?? options.timeout),
226
- signal: controller?.signal
240
+ ...getResolvedFetchConfig(timeout),
241
+ signal
227
242
  });
228
243
  };
229
244
  const _handler = (_nuxtApp, context) => {
@@ -232,30 +247,63 @@ export class CustomFetch {
232
247
  timeout: options.timeout
233
248
  });
234
249
  };
250
+ const nuxtApp = useNuxtApp();
235
251
  const createClientAsyncDataFallback = () => {
236
252
  const _ref = options.deep ? ref : shallowRef;
253
+ const usePendingRef = pendingWhenIdle;
237
254
  const getDefaultValue = () => {
238
255
  if (options.default) {
239
256
  return unref(options.default());
240
257
  }
241
258
  return asyncDataDefaults.value;
242
259
  };
260
+ const resolveCachedData = (cause = "refresh:manual") => {
261
+ if (options.getCachedData) {
262
+ return options.getCachedData(key.value, nuxtApp, { cause });
263
+ }
264
+ if (nuxtApp.isHydrating) {
265
+ return nuxtApp.payload?.data?.[key.value];
266
+ }
267
+ if (cause !== "refresh:manual" && cause !== "refresh:hook") {
268
+ return nuxtApp.static?.data?.[key.value];
269
+ }
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";
243
278
  let activeController;
244
279
  let activeRequest;
245
280
  let requestId = 0;
281
+ let hasData = false;
282
+ let keyChanging = false;
246
283
  let stopKeyWatch;
247
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
+ };
248
294
  const stopWatchers = () => {
249
295
  stopKeyWatch?.();
250
296
  stopKeyWatch = void 0;
251
297
  stopOptionWatch?.();
252
298
  stopOptionWatch = void 0;
299
+ stopRefreshHook?.();
300
+ stopRefreshHook = void 0;
253
301
  };
254
302
  const asyncData = {
255
303
  data: _ref(getDefaultValue()),
256
304
  error: _ref(asyncDataDefaults.errorValue),
257
- status: _ref(options.immediate === false ? "idle" : "pending"),
258
- pending: _ref(options.immediate !== false),
305
+ status: statusRef,
306
+ pending: pendingRef,
259
307
  clear: () => {
260
308
  stopWatchers();
261
309
  activeController?.abort();
@@ -263,16 +311,18 @@ export class CustomFetch {
263
311
  if (_cachedClientAsyncData.get(key.value) === asyncData) {
264
312
  _cachedClientAsyncData.delete(key.value);
265
313
  }
314
+ hasData = false;
266
315
  asyncData.data.value = getDefaultValue();
267
316
  asyncData.error.value = asyncDataDefaults.errorValue;
268
317
  asyncData.status.value = "idle";
269
- asyncData.pending.value = false;
318
+ setPending(false);
270
319
  clearNuxtData(key.value);
271
320
  },
272
321
  refresh: async (executeOptions) => {
273
322
  await asyncData.execute(executeOptions);
274
323
  },
275
324
  execute: async (executeOptions) => {
325
+ const cause = executeOptions?.cause;
276
326
  const dedupe = executeOptions?.dedupe ?? options.dedupe ?? "cancel";
277
327
  if (activeRequest) {
278
328
  if (dedupe === "defer") {
@@ -280,6 +330,18 @@ export class CustomFetch {
280
330
  }
281
331
  activeController?.abort();
282
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
+ }
283
345
  const currentRequestId = ++requestId;
284
346
  const controller = createAbortController();
285
347
  activeController = controller;
@@ -287,7 +349,7 @@ export class CustomFetch {
287
349
  if (controller) {
288
350
  _cachedController.set(key.value, controller);
289
351
  }
290
- asyncData.pending.value = true;
352
+ setPending(true);
291
353
  asyncData.status.value = "pending";
292
354
  asyncData.error.value = asyncDataDefaults.errorValue;
293
355
  activeRequest = executeRequest({
@@ -305,13 +367,17 @@ export class CustomFetch {
305
367
  if (options.pick) {
306
368
  finalData = pick(data, options.pick);
307
369
  }
308
- asyncData.data.value = finalData;
370
+ const value = finalData;
371
+ writePayloadData(value);
372
+ hasData = true;
373
+ asyncData.data.value = value;
309
374
  asyncData.error.value = asyncDataDefaults.errorValue;
310
375
  asyncData.status.value = "success";
311
376
  }).catch((error) => {
312
377
  if (currentRequestId !== requestId || controller?.signal.aborted) {
313
378
  return;
314
379
  }
380
+ hasData = false;
315
381
  asyncData.error.value = createError(error);
316
382
  asyncData.data.value = getDefaultValue();
317
383
  asyncData.status.value = "error";
@@ -325,30 +391,48 @@ export class CustomFetch {
325
391
  if (asyncData.status.value === "pending") {
326
392
  asyncData.status.value = "idle";
327
393
  }
328
- asyncData.pending.value = false;
394
+ setPending(false);
329
395
  });
330
396
  await activeRequest;
331
397
  }
332
398
  };
333
399
  _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
- }
341
- }
342
- if (newKey !== oldKey) {
343
- _cachedClientAsyncData.set(newKey, asyncData);
344
- }
345
- if (newKey !== oldKey && options.immediate !== false) {
346
- void asyncData.execute({ cause: "watch" });
400
+ stopRefreshHook = nuxtApp.hook?.("app:data:refresh", async (keys) => {
401
+ if (!keys || keys.includes(key.value)) {
402
+ await asyncData.execute({ cause: "refresh:hook" });
347
403
  }
348
404
  });
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
+ }
349
430
  const hasScope = getCurrentScope();
350
431
  if (options.watch) {
351
432
  stopOptionWatch = watch(options.watch, async () => {
433
+ if (keyChanging) {
434
+ return;
435
+ }
352
436
  await asyncData.refresh({ cause: "watch" });
353
437
  }, { flush: "post" });
354
438
  }
@@ -363,7 +447,6 @@ export class CustomFetch {
363
447
  }
364
448
  return asyncData.execute({ cause: "initial" }).then(() => asyncData);
365
449
  };
366
- const nuxtApp = useNuxtApp();
367
450
  const sharedAsyncData = nuxtApp._asyncData?.[key.value];
368
451
  const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
369
452
  if (import.meta.client && !nuxtApp.isHydrating) {
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "type": "module",
4
- "version": "4.4.0",
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",
@@ -40,30 +40,34 @@
40
40
  "path": "node_modules/cz-git"
41
41
  }
42
42
  },
43
+ "peerDependencies": {
44
+ "nuxt": ">=4.4.0",
45
+ "vue": "^3.5.30"
46
+ },
43
47
  "dependencies": {
44
48
  "@vue/shared": "^3.5.30",
45
- "ohash": "^2.0.11",
46
- "vue": "^3.5.30"
49
+ "ohash": "^2.0.11"
47
50
  },
48
51
  "devDependencies": {
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",
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",
53
56
  "@nuxt/module-builder": "^1.0.2",
54
- "@nuxt/schema": "4.4.2",
57
+ "@nuxt/schema": "4.4.8",
55
58
  "@types/node": "^25.5.0",
56
- "@vitest/coverage-v8": "^3.2.4",
59
+ "@vitest/coverage-v8": "^4.1.9",
57
60
  "changelogen": "^0.6.2",
58
61
  "commitizen": "^4.3.1",
59
62
  "cz-git": "^1.12.0",
60
63
  "eslint": "^10.0.3",
61
64
  "husky": "^9.1.7",
62
- "nano-staged": "^0.9.0",
63
- "nitro": "npm:nitropack@^2.13.1",
64
- "nuxt": "4.4.2",
65
- "typescript": "5.9.3",
66
- "vitest": "^3.2.4"
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"
67
71
  },
68
72
  "husky": {
69
73
  "hooks": {
@@ -71,6 +75,6 @@
71
75
  }
72
76
  },
73
77
  "nano-staged": {
74
- "*": "eslint . --fix"
78
+ "*": "eslint --fix"
75
79
  }
76
80
  }