@hyper-fetch/core 9.6.0 → 9.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  35. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  36. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  37. package/__tests__/features/request/request.inference.spec.ts +269 -0
  38. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  39. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  40. package/__tests__/features/request/request.values.spec.ts +408 -0
  41. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  42. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  43. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  44. package/__tests__/utils/fixtures.utils.ts +193 -0
  45. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  46. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  47. package/dist/cache/cache.d.ts +12 -1
  48. package/dist/cache/cache.d.ts.map +1 -1
  49. package/dist/cache/cache.events.d.ts +20 -6
  50. package/dist/cache/cache.events.d.ts.map +1 -1
  51. package/dist/cache/cache.utils.d.ts +1 -0
  52. package/dist/cache/cache.utils.d.ts.map +1 -1
  53. package/dist/client/client.d.ts +3 -3
  54. package/dist/client/client.d.ts.map +1 -1
  55. package/dist/client/client.utils.d.ts.map +1 -1
  56. package/dist/dispatcher/dispatcher.d.ts +26 -5
  57. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  58. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  59. package/dist/index.mjs +2127 -1741
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  62. package/dist/managers/app/app.manager.d.ts +9 -0
  63. package/dist/managers/app/app.manager.d.ts.map +1 -1
  64. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  65. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  66. package/dist/managers/request/request.manager.d.ts.map +1 -1
  67. package/dist/managers/request/request.manager.types.d.ts +2 -0
  68. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  69. package/dist/mocker/mocker.d.ts +1 -1
  70. package/dist/mocker/mocker.d.ts.map +1 -1
  71. package/dist/plugin/plugin.d.ts +2 -0
  72. package/dist/plugin/plugin.d.ts.map +1 -1
  73. package/dist/request/request.d.ts +1 -1
  74. package/dist/request/request.d.ts.map +1 -1
  75. package/dist/request/request.utils.d.ts.map +1 -1
  76. package/dist/utils/emitter.utils.d.ts.map +1 -1
  77. package/dist/utils/error.utils.d.ts +17 -0
  78. package/dist/utils/error.utils.d.ts.map +1 -0
  79. package/dist/utils/index.d.ts +1 -0
  80. package/dist/utils/index.d.ts.map +1 -1
  81. package/package.json +1 -1
  82. package/src/adapter/adapter.bindings.ts +46 -18
  83. package/src/adapter/adapter.utils.ts +47 -7
  84. package/src/cache/cache.events.ts +24 -8
  85. package/src/cache/cache.ts +109 -21
  86. package/src/cache/cache.utils.ts +33 -10
  87. package/src/client/client.ts +99 -7
  88. package/src/client/client.utils.ts +10 -4
  89. package/src/dispatcher/dispatcher.ts +273 -133
  90. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  91. package/src/managers/app/app.manager.constants.ts +12 -1
  92. package/src/managers/app/app.manager.ts +43 -23
  93. package/src/managers/app/app.manager.utils.ts +8 -4
  94. package/src/managers/logger/logger.manager.ts +21 -8
  95. package/src/managers/request/request.manager.ts +7 -1
  96. package/src/managers/request/request.manager.types.ts +2 -0
  97. package/src/mocker/mocker.ts +14 -11
  98. package/src/plugin/plugin.ts +6 -0
  99. package/src/request/request.ts +31 -22
  100. package/src/request/request.utils.ts +23 -15
  101. package/src/utils/emitter.utils.ts +9 -2
  102. package/src/utils/error.utils.ts +29 -0
  103. package/src/utils/index.ts +1 -0
@@ -15,6 +15,9 @@ import { Request, scopeKey } from "request";
15
15
  import type { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from "types";
16
16
  import { EventEmitter } from "utils";
17
17
 
18
+ /** Timers can't wait longer than 2^31-1 ms (~24.8 days) - a longer delay overflows and fires immediately */
19
+ const MAX_TIMER_DELAY = 2_147_483_647;
20
+
18
21
  /**
19
22
  * Cache class handles the data exchange with the dispatchers.
20
23
  *
@@ -108,7 +111,9 @@ export class Cache<Adapter extends AdapterInstance> {
108
111
  if (processedResponse.success && isCachingAllowed) {
109
112
  this.logger.debug({ title: "Saving response to cache storage", type: "system", extra: { request, data } });
110
113
  this.storage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);
111
- this.lazyStorage?.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);
114
+ this.runLazyStorage("set", storageKey, (lazyStorage) =>
115
+ lazyStorage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData),
116
+ );
112
117
  this.client.triggerPlugins("onCacheItemChange", {
113
118
  cache: this,
114
119
  cacheKey,
@@ -167,6 +172,11 @@ export class Cache<Adapter extends AdapterInstance> {
167
172
  get = <Response, Error>(cacheKey: string): CacheValueType<Response, Error, Adapter> | undefined => {
168
173
  this.getLazyResource<Response, Error>(cacheKey);
169
174
  const cachedData = this.storage.get<Response, Error, Adapter>(cacheKey);
175
+
176
+ // Data saved by another cache version is never returned - the lazy resource check above removes it
177
+ if (cachedData && cachedData.version !== this.version) {
178
+ return undefined;
179
+ }
170
180
  return cachedData;
171
181
  };
172
182
 
@@ -186,15 +196,21 @@ export class Cache<Adapter extends AdapterInstance> {
186
196
  */
187
197
  delete = (cacheKey: string): void => {
188
198
  this.logger.debug({ title: "Deleting cache element", type: "system", extra: { cacheKey } });
199
+ // Removed element has nothing left to collect - pending collector would only emit the deletion once again
200
+ clearTimeout(this.garbageCollectors.get(cacheKey));
201
+ this.garbageCollectors.delete(cacheKey);
202
+
203
+ // Listeners are subscribed with the cache key of the request, scoped elements are stored under another key
204
+ const listenersKey = this.storage.get(cacheKey)?.cacheKey ?? cacheKey;
189
205
  this.storage.delete(cacheKey);
190
- this.lazyStorage?.delete(cacheKey);
206
+ this.runLazyStorage("delete", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));
191
207
 
192
208
  this.client.triggerPlugins("onCacheItemDelete", {
193
209
  cache: this,
194
210
  cacheKey,
195
211
  });
196
212
 
197
- this.events.emitDelete(cacheKey);
213
+ this.events.emitDelete(cacheKey, false, listenersKey);
198
214
  };
199
215
 
200
216
  /**
@@ -219,7 +235,11 @@ export class Cache<Adapter extends AdapterInstance> {
219
235
  cacheKey: notifyCacheKey,
220
236
  });
221
237
 
222
- this.events.emitInvalidation(notifyCacheKey);
238
+ // Listeners are subscribed with the cache key of the request, scoped elements are stored under another key.
239
+ // The key of the element goes as the event data, so they can tell the scopes apart.
240
+ const listenersKey =
241
+ notifyCacheKey === invalidateStorageKey ? (value?.cacheKey ?? notifyCacheKey) : notifyCacheKey;
242
+ this.events.emitInvalidation(invalidateStorageKey, false, listenersKey);
223
243
  };
224
244
 
225
245
  if (key instanceof Request) {
@@ -227,8 +247,10 @@ export class Cache<Adapter extends AdapterInstance> {
227
247
  } else if (typeof key === "string") {
228
248
  handleInvalidation(key);
229
249
  } else if (keys.length > 0) {
250
+ // Global and sticky expressions remember the position of the last match, which would skip some of the keys
251
+ const matcher = new RegExp(key.source, key.flags.replaceAll(/[gy]/g, ""));
230
252
  keys.forEach((entityKey) => {
231
- if (key.test(entityKey)) {
253
+ if (matcher.test(entityKey)) {
232
254
  handleInvalidation(entityKey);
233
255
  }
234
256
  });
@@ -249,23 +271,34 @@ export class Cache<Adapter extends AdapterInstance> {
249
271
  getLazyResource = async <Response, Error>(
250
272
  cacheKey: string,
251
273
  ): Promise<CacheValueType<Response, Error, Adapter> | undefined> => {
252
- const data = await this.lazyStorage?.get<Response, Error, Adapter>(cacheKey);
274
+ const data = await this.runLazyStorage("get", cacheKey, (lazyStorage) =>
275
+ lazyStorage.get<Response, Error, Adapter>(cacheKey),
276
+ );
253
277
  const syncData = this.storage.get<Response, Error, Adapter>(cacheKey);
254
278
 
255
279
  // No data in lazy storage
256
- const hasLazyData = this.lazyStorage && data;
257
- if (hasLazyData) {
280
+ if (data) {
258
281
  const now = Date.now();
259
282
  const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;
260
- const isStaleData = data.staleTime <= now - data.responseTimestamp;
283
+ // Storages based on JSON turn Infinity into null - such data never gets stale
284
+ const isStaleData = data.staleTime === null ? false : data.staleTime <= now - data.responseTimestamp;
261
285
  const isValidLazyData = data.version === this.version;
286
+ // Collectors do not survive the application restart, so outdated data has to be removed once we meet it
287
+ const isExpiredData = this.client.appManager.isOnline && this.getTimeLeft(data, now) < 0;
262
288
 
263
- if (!isValidLazyData) {
264
- this.lazyStorage?.delete(cacheKey);
289
+ if (!isValidLazyData || isExpiredData) {
290
+ this.runLazyStorage("delete", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));
265
291
  }
266
- if (isNewestData && !isStaleData && isValidLazyData) {
292
+ if (isNewestData && !isStaleData && isValidLazyData && !isExpiredData) {
267
293
  this.storage.set<Response, Error, Adapter>(cacheKey, data);
268
- this.events.emitCacheData<Response, Error, Adapter>({ ...data, cacheKey, cached: true });
294
+ // Data loaded to the sync storage is collected the same way as the data set directly
295
+ this.scheduleGarbageCollector(cacheKey);
296
+ // Data events are emitted with the request cacheKey, which differs from the storage key for scoped requests
297
+ this.events.emitCacheData<Response, Error, Adapter>({
298
+ ...data,
299
+ cacheKey: typeof data.cacheKey === "string" ? data.cacheKey : cacheKey,
300
+ cached: true,
301
+ });
269
302
  return data;
270
303
  }
271
304
  }
@@ -273,6 +306,7 @@ export class Cache<Adapter extends AdapterInstance> {
273
306
  const isValidData = syncData?.version === this.version;
274
307
  if (syncData && !isValidData) {
275
308
  this.delete(cacheKey);
309
+ return undefined;
276
310
  }
277
311
  return syncData;
278
312
  };
@@ -308,31 +342,34 @@ export class Cache<Adapter extends AdapterInstance> {
308
342
 
309
343
  // Clear running garbage collectors for given key
310
344
  clearTimeout(this.garbageCollectors.get(cacheKey));
345
+ this.garbageCollectors.delete(cacheKey);
311
346
 
312
347
  // Garbage collect
313
348
  if (cacheData) {
314
- const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - Date.now();
349
+ const timeLeft = this.getTimeLeft(cacheData, Date.now());
315
350
  // null
316
351
  if (cacheData.cacheTime === null) {
317
352
  this.logger.debug({ title: "Cache time is null", type: "system", extra: { cacheKey } });
318
353
  }
319
354
  // Infinity
320
- else if (
321
- (cacheData.cacheTime !== null && JSON.stringify(cacheData.cacheTime) === "null") ||
322
- cacheData.cacheTime === Infinity
323
- ) {
355
+ else if (timeLeft === Infinity) {
324
356
  this.logger.debug({ title: "Cache time is Infinite", type: "system", extra: { cacheKey } });
325
357
  }
326
358
  // Run garbage collector
327
359
  else if (timeLeft >= 0) {
360
+ // Longer delays are split into parts, as timers fire immediately when the delay is too big for them
361
+ const delay = Math.min(timeLeft, MAX_TIMER_DELAY);
328
362
  this.garbageCollectors.set(
329
363
  cacheKey,
330
364
  setTimeout(() => {
331
- if (this.client.appManager.isOnline) {
365
+ this.garbageCollectors.delete(cacheKey);
366
+ if (delay < timeLeft) {
367
+ this.scheduleGarbageCollector(cacheKey);
368
+ } else if (this.client.appManager.isOnline) {
332
369
  this.logger.info({ title: "Garbage collecting cache data", type: "system", extra: { cacheKey } });
333
370
  this.delete(cacheKey);
334
371
  }
335
- }, timeLeft),
372
+ }, delay),
336
373
  );
337
374
  }
338
375
  // Delete if value is stale and we are online
@@ -344,10 +381,61 @@ export class Cache<Adapter extends AdapterInstance> {
344
381
  };
345
382
 
346
383
  /**
347
- * Clear cache storages
384
+ * Time left to the garbage collection of the cache element. Returns Infinity for elements stored forever
385
+ * and a negative value for outdated elements or elements without valid times.
386
+ */
387
+ private getTimeLeft = (cacheData: Pick<CacheValueType, "cacheTime" | "responseTimestamp">, now: number): number => {
388
+ const { cacheTime, responseTimestamp } = cacheData;
389
+ // Storages based on JSON turn Infinity into null
390
+ if (cacheTime === null || (typeof cacheTime === "number" && !Number.isFinite(cacheTime))) {
391
+ return Infinity;
392
+ }
393
+ const timeLeft = cacheTime + responseTimestamp - now;
394
+ // Missing times can't be scheduled, such element is treated as outdated
395
+ return Number.isNaN(timeLeft) ? -1 : timeLeft;
396
+ };
397
+
398
+ /**
399
+ * Lazy storage is an external resource (IndexedDB, AsyncStorage etc.) - its failures are logged, they must not
400
+ * break the cache flow nor end up as unhandled promise rejections.
401
+ */
402
+ private runLazyStorage = async <Result>(
403
+ action: "get" | "set" | "delete" | "clear",
404
+ cacheKey: string,
405
+ callback: (lazyStorage: CacheAsyncStorageType) => Promise<Result>,
406
+ ): Promise<Result | undefined> => {
407
+ if (!this.lazyStorage) {
408
+ return undefined;
409
+ }
410
+ try {
411
+ return await callback(this.lazyStorage);
412
+ } catch (error) {
413
+ this.logger?.error({
414
+ title: `Lazy storage "${action}" failed`,
415
+ type: "system",
416
+ extra: { cacheKey, error },
417
+ });
418
+ return undefined;
419
+ }
420
+ };
421
+
422
+ /**
423
+ * Clear cache storages - the memory and the lazy one. Data left in the lazy storage would be loaded back
424
+ * by the next read, for example for the next user after a logout.
348
425
  */
349
426
  clear = async (): Promise<void> => {
350
427
  this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));
428
+ this.garbageCollectors.clear();
351
429
  this.storage.clear();
430
+
431
+ await this.runLazyStorage("clear", "*", async (lazyStorage) => {
432
+ const keys = [...(await lazyStorage.keys())];
433
+ // One element that can't be removed must not keep the others in the storage
434
+ const results = await Promise.allSettled(keys.map((key) => lazyStorage.delete(key)));
435
+ const failed = results.find((result) => result.status === "rejected");
436
+ if (failed) {
437
+ throw failed.reason;
438
+ }
439
+ });
352
440
  };
353
441
  }
@@ -9,7 +9,8 @@ export const getCacheData = <T extends RequestInstance>(
9
9
  const { data, success } = response;
10
10
 
11
11
  const previousData = !success && previousResponse ? previousResponse.data : null;
12
- const computedData = data || previousData;
12
+ // Only missing data falls back to the previous one - falsy responses like `0`, `false` or `""` are valid data
13
+ const computedData = data ?? previousData;
13
14
 
14
15
  return { ...response, data: computedData };
15
16
  };
@@ -50,14 +51,15 @@ const isPlainArray = (value: unknown): value is unknown[] => {
50
51
  };
51
52
 
52
53
  /**
53
- * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.
54
- * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.
55
- * Only plain objects and arrays are traversed, other values are compared with `Object.is`.
56
- * @param prev previous value
57
- * @param next incoming value
58
- * @returns `next` sharing unchanged references with `prev`
54
+ * Structures nested deeper than this are not compared - it keeps extremely deep data from overflowing the call stack.
59
55
  */
60
- export const replaceEqualDeep = <T>(prev: unknown, next: T): T => {
56
+ const STRUCTURAL_SHARING_MAX_DEPTH = 500;
57
+
58
+ /**
59
+ * @param ancestors containers of `next` that are being compared right now - their number is the current depth
60
+ * and meeting one of them again means a cycle
61
+ */
62
+ const shareEqualParts = <T>(prev: unknown, next: T, ancestors: Set<unknown>): T => {
61
63
  if (Object.is(prev, next)) {
62
64
  return prev as T;
63
65
  }
@@ -67,6 +69,12 @@ export const replaceEqualDeep = <T>(prev: unknown, next: T): T => {
67
69
  return next;
68
70
  }
69
71
 
72
+ // Circular and extremely deep structures are not traversed further
73
+ if (ancestors.size > STRUCTURAL_SHARING_MAX_DEPTH || ancestors.has(next)) {
74
+ return next;
75
+ }
76
+ ancestors.add(next);
77
+
70
78
  const prevItems = prev as Record<string, unknown>;
71
79
  const nextItems = next as Record<string, unknown>;
72
80
  const prevKeys = Object.keys(prevItems);
@@ -77,14 +85,29 @@ export const replaceEqualDeep = <T>(prev: unknown, next: T): T => {
77
85
  nextKeys.forEach((key) => {
78
86
  const prevValue = prevItems[key];
79
87
  const nextValue = nextItems[key];
80
- const value = replaceEqualDeep(prevValue, nextValue);
88
+ const value = shareEqualParts(prevValue, nextValue, ancestors);
81
89
  copy[key] = value;
82
90
  // undefined values are equal only when the key existed before
83
91
  // eslint-disable-next-line prefer-object-has-own -- Object.hasOwn is not available in older runtimes
84
- if (value === prevValue && (value !== undefined || Object.prototype.hasOwnProperty.call(prevItems, key))) {
92
+ if (Object.is(value, prevValue) && (value !== undefined || Object.prototype.hasOwnProperty.call(prevItems, key))) {
85
93
  equalItems += 1;
86
94
  }
87
95
  });
88
96
 
97
+ ancestors.delete(next);
98
+
89
99
  return (prevKeys.length === nextKeys.length && equalItems === prevKeys.length ? prev : copy) as T;
90
100
  };
101
+
102
+ /**
103
+ * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.
104
+ * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.
105
+ * Only plain objects and arrays are traversed, other values are compared with `Object.is`.
106
+ * Circular references and extremely deep structures are not traversed - such parts are taken from `next` as they are.
107
+ * @param prev previous value
108
+ * @param next incoming value
109
+ * @returns `next` sharing unchanged references with `prev`
110
+ */
111
+ export const replaceEqualDeep = <T>(prev: unknown, next: T): T => {
112
+ return shareEqualParts(prev, next, new Set());
113
+ };
@@ -30,10 +30,48 @@ import type {
30
30
  ExtractAdapterDefaultQueryParamsType,
31
31
  ExtractAdapterRequestOptionsType,
32
32
  } from "types";
33
- import { getUniqueRequestId } from "utils";
33
+ import { getUniqueRequestId, throwOutsideLifecycle } from "utils";
34
34
 
35
35
  import { interceptRequest, interceptResponse, resolveClientMode } from "./client.utils";
36
36
 
37
+ /**
38
+ * Response interceptors run when the adapter is already done, so nothing else can handle their failure.
39
+ * A throwing or rejecting interceptor ends the request with the error response - the same way as failing request
40
+ * interceptors do - instead of leaving it pending forever.
41
+ */
42
+ const interceptResponseSafely = async <GlobalErrorType, Adapter extends AdapterInstance>({
43
+ client,
44
+ interceptors,
45
+ response,
46
+ request,
47
+ }: {
48
+ client: Client<any, Adapter>;
49
+ interceptors: ResponseInterceptorType<ClientInstance>[];
50
+ response: ResponseType<any, GlobalErrorType, Adapter>;
51
+ request: RequestInstance;
52
+ }): Promise<ResponseType<any, GlobalErrorType, Adapter>> => {
53
+ try {
54
+ return (await interceptResponse<GlobalErrorType, ClientInstance>(
55
+ interceptors,
56
+ response as ResponseType<any, GlobalErrorType, AdapterInstance>,
57
+ request,
58
+ )) as ResponseType<any, GlobalErrorType, Adapter>;
59
+ } catch (error) {
60
+ const { adapter } = client;
61
+ client.logger.error({ title: "Response interceptor failed", type: "system", extra: { error, request } });
62
+
63
+ return {
64
+ data: null,
65
+ error: adapter.unstable_internalErrorMapping(error as Parameters<Adapter["unstable_internalErrorMapping"]>[0]),
66
+ status: adapter.systemErrorStatus,
67
+ success: false,
68
+ extra: adapter.systemErrorExtra,
69
+ requestTimestamp: response.requestTimestamp,
70
+ responseTimestamp: response.responseTimestamp,
71
+ };
72
+ }
73
+ };
74
+
37
75
  /**
38
76
  * **Client** is a class that allows you to configure the connection with the server and then use it to create
39
77
  * requests. It allows you to set global defaults for the requests configuration, query params configuration.
@@ -157,7 +195,7 @@ export class Client<
157
195
  */
158
196
  setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {
159
197
  this.loggerManager = callback(this);
160
- this.loggerManager.initialize(this, "Client");
198
+ this.logger = this.loggerManager.initialize(this, "Client");
161
199
  return this;
162
200
  };
163
201
 
@@ -309,7 +347,17 @@ export class Client<
309
347
  }
310
348
 
311
349
  this.plugins.forEach((plugin) => {
312
- plugin.trigger(key, data);
350
+ try {
351
+ plugin.trigger(key, data);
352
+ } catch (error) {
353
+ // Plugins only observe the lifecycle - a failing one can't break the requests, the cache or other plugins
354
+ this.logger.error({
355
+ title: `Plugin "${plugin.name}" failed`,
356
+ type: "system",
357
+ extra: { plugin: plugin.name, method: key, error },
358
+ });
359
+ throwOutsideLifecycle(error);
360
+ }
313
361
  });
314
362
 
315
363
  return this;
@@ -360,7 +408,13 @@ export class Client<
360
408
  unstable_modifyErrorResponse = async (
361
409
  response: ResponseType<any, GlobalErrorType, Adapter>,
362
410
  request: RequestInstance,
363
- ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onErrorCallbacks, response, request);
411
+ ) =>
412
+ interceptResponseSafely<GlobalErrorType, Adapter>({
413
+ client: this,
414
+ interceptors: this.unstable_onErrorCallbacks,
415
+ response,
416
+ request,
417
+ });
364
418
 
365
419
  /**
366
420
  * Private helper to run async on-success response processing
@@ -369,14 +423,25 @@ export class Client<
369
423
  unstable_modifySuccessResponse = async (
370
424
  response: ResponseType<any, GlobalErrorType, Adapter>,
371
425
  request: RequestInstance,
372
- ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onSuccessCallbacks, response, request);
426
+ ) =>
427
+ interceptResponseSafely<GlobalErrorType, Adapter>({
428
+ client: this,
429
+ interceptors: this.unstable_onSuccessCallbacks,
430
+ response,
431
+ request,
432
+ });
373
433
 
374
434
  /**
375
435
  * Private helper to run async response processing
376
436
  * @private
377
437
  */
378
438
  unstable_modifyResponse = async (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>
379
- interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onResponseCallbacks, response, request);
439
+ interceptResponseSafely<GlobalErrorType, Adapter>({
440
+ client: this,
441
+ interceptors: this.unstable_onResponseCallbacks,
442
+ response,
443
+ request,
444
+ });
380
445
 
381
446
  /**
382
447
  * Reconstruct a Request class instance from its serialized JSON form.
@@ -410,6 +475,18 @@ export class Client<
410
475
  clear = () => {
411
476
  const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
412
477
 
478
+ // Queued and ongoing requests are removed while their listeners still exist - it aborts the ongoing ones
479
+ // and resolves the pending `send()` promises, which otherwise would never settle
480
+ [this.fetchDispatcher, this.submitDispatcher].forEach((dispatcher) => {
481
+ dispatcher.getQueuesKeys().forEach((queryKey) => {
482
+ dispatcher.getQueue(queryKey).requests.forEach(({ request, requestId }) => {
483
+ dispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
484
+ });
485
+ });
486
+ });
487
+ // Requests sent outside of the dispatchers
488
+ this.requestManager.abortAll();
489
+
413
490
  this.requestManager.abortControllers.clear();
414
491
  this.fetchDispatcher.clear();
415
492
  this.submitDispatcher.clear();
@@ -420,6 +497,8 @@ export class Client<
420
497
  this.submitDispatcher.emitter.removeAllListeners();
421
498
  this.cache.emitter.removeAllListeners();
422
499
  this.appManager.unmount();
500
+ // App manager can be shared between the clears, so the listeners of the removed modules have to go away
501
+ this.appManager.emitter.removeAllListeners();
423
502
 
424
503
  this.cache = cache?.() || new Cache();
425
504
  this.appManager = appManager?.() || new AppManager();
@@ -465,7 +544,20 @@ export class Client<
465
544
  }
466
545
 
467
546
  const parsedData = parseResponse(response);
468
- this.cache.set({ ...config, cacheKey, scope }, parsedData);
547
+ this.cache.set(
548
+ { ...config, cacheKey, scope },
549
+ {
550
+ // Hydrated responses did not go through the dispatcher, so the request details get their neutral values
551
+ retries: 0,
552
+ isCanceled: false,
553
+ isOffline: false,
554
+ willRetry: false,
555
+ addedTimestamp: parsedData?.requestTimestamp,
556
+ triggerTimestamp: parsedData?.requestTimestamp,
557
+ ...parsedData,
558
+ hydrated: true,
559
+ },
560
+ );
469
561
  });
470
562
  };
471
563
 
@@ -29,9 +29,12 @@ export const interceptRequest = async (interceptors: RequestInterceptorType[], r
29
29
  if (!request.requestOptions.disableRequestInterceptors) {
30
30
  // eslint-disable-next-line no-restricted-syntax
31
31
  for (const interceptor of interceptors) {
32
+ // Interceptors create a pipeline - each one receives the request returned by the previous one
32
33
  // eslint-disable-next-line no-await-in-loop
33
- newRequest = (await interceptor(request)) as RequestInstance;
34
- if (!newRequest) {throw new Error("Request modifier must return request");}
34
+ newRequest = (await interceptor(newRequest)) as RequestInstance;
35
+ if (!newRequest) {
36
+ throw new Error("Request modifier must return request");
37
+ }
35
38
  }
36
39
  }
37
40
  return newRequest;
@@ -46,9 +49,12 @@ export const interceptResponse = async <GlobalErrorType, Client extends ClientIn
46
49
  if (!request.requestOptions.disableResponseInterceptors) {
47
50
  // eslint-disable-next-line no-restricted-syntax
48
51
  for (const interceptor of interceptors) {
52
+ // Interceptors create a pipeline - each one receives the response returned by the previous one
49
53
  // eslint-disable-next-line no-await-in-loop
50
- newResponse = await interceptor(response, request);
51
- if (!newResponse) {throw new Error("Response modifier must return data");}
54
+ newResponse = await interceptor(newResponse, request);
55
+ if (!newResponse) {
56
+ throw new Error("Response modifier must return data");
57
+ }
52
58
  }
53
59
  }
54
60
  return newResponse;