@hyper-fetch/core 9.6.1 → 9.7.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.
Files changed (134) 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/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -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
+ };
@@ -14,6 +14,7 @@ import type { HttpAdapterType } from "http-adapter";
14
14
  import { parseResponse, HttpAdapter } from "http-adapter";
15
15
  import type { LogLevel } from "managers";
16
16
  import { AppManager, LoggerManager, RequestManager } from "managers";
17
+ import { resetOptimisticState } from "optimistic/optimistic.settlement";
17
18
  import type { PluginInstance, PluginMethodParameters, PluginMethods } from "plugin";
18
19
  import type { RequestInstance, RequestJSON, RequestOptionsType } from "request";
19
20
  import { getRequestKey, getSimpleKey, Request, scopeKey } from "request";
@@ -30,10 +31,48 @@ import type {
30
31
  ExtractAdapterDefaultQueryParamsType,
31
32
  ExtractAdapterRequestOptionsType,
32
33
  } from "types";
33
- import { getUniqueRequestId } from "utils";
34
+ import { getUniqueRequestId, throwOutsideLifecycle } from "utils";
34
35
 
35
36
  import { interceptRequest, interceptResponse, resolveClientMode } from "./client.utils";
36
37
 
38
+ /**
39
+ * Response interceptors run when the adapter is already done, so nothing else can handle their failure.
40
+ * A throwing or rejecting interceptor ends the request with the error response - the same way as failing request
41
+ * interceptors do - instead of leaving it pending forever.
42
+ */
43
+ const interceptResponseSafely = async <GlobalErrorType, Adapter extends AdapterInstance>({
44
+ client,
45
+ interceptors,
46
+ response,
47
+ request,
48
+ }: {
49
+ client: Client<any, Adapter>;
50
+ interceptors: ResponseInterceptorType<ClientInstance>[];
51
+ response: ResponseType<any, GlobalErrorType, Adapter>;
52
+ request: RequestInstance;
53
+ }): Promise<ResponseType<any, GlobalErrorType, Adapter>> => {
54
+ try {
55
+ return (await interceptResponse<GlobalErrorType, ClientInstance>(
56
+ interceptors,
57
+ response as ResponseType<any, GlobalErrorType, AdapterInstance>,
58
+ request,
59
+ )) as ResponseType<any, GlobalErrorType, Adapter>;
60
+ } catch (error) {
61
+ const { adapter } = client;
62
+ client.logger.error({ title: "Response interceptor failed", type: "system", extra: { error, request } });
63
+
64
+ return {
65
+ data: null,
66
+ error: adapter.unstable_internalErrorMapping(error as Parameters<Adapter["unstable_internalErrorMapping"]>[0]),
67
+ status: adapter.systemErrorStatus,
68
+ success: false,
69
+ extra: adapter.systemErrorExtra,
70
+ requestTimestamp: response.requestTimestamp,
71
+ responseTimestamp: response.responseTimestamp,
72
+ };
73
+ }
74
+ };
75
+
37
76
  /**
38
77
  * **Client** is a class that allows you to configure the connection with the server and then use it to create
39
78
  * requests. It allows you to set global defaults for the requests configuration, query params configuration.
@@ -157,7 +196,7 @@ export class Client<
157
196
  */
158
197
  setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {
159
198
  this.loggerManager = callback(this);
160
- this.loggerManager.initialize(this, "Client");
199
+ this.logger = this.loggerManager.initialize(this, "Client");
161
200
  return this;
162
201
  };
163
202
 
@@ -309,7 +348,17 @@ export class Client<
309
348
  }
310
349
 
311
350
  this.plugins.forEach((plugin) => {
312
- plugin.trigger(key, data);
351
+ try {
352
+ plugin.trigger(key, data);
353
+ } catch (error) {
354
+ // Plugins only observe the lifecycle - a failing one can't break the requests, the cache or other plugins
355
+ this.logger.error({
356
+ title: `Plugin "${plugin.name}" failed`,
357
+ type: "system",
358
+ extra: { plugin: plugin.name, method: key, error },
359
+ });
360
+ throwOutsideLifecycle(error);
361
+ }
313
362
  });
314
363
 
315
364
  return this;
@@ -360,7 +409,13 @@ export class Client<
360
409
  unstable_modifyErrorResponse = async (
361
410
  response: ResponseType<any, GlobalErrorType, Adapter>,
362
411
  request: RequestInstance,
363
- ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onErrorCallbacks, response, request);
412
+ ) =>
413
+ interceptResponseSafely<GlobalErrorType, Adapter>({
414
+ client: this,
415
+ interceptors: this.unstable_onErrorCallbacks,
416
+ response,
417
+ request,
418
+ });
364
419
 
365
420
  /**
366
421
  * Private helper to run async on-success response processing
@@ -369,14 +424,25 @@ export class Client<
369
424
  unstable_modifySuccessResponse = async (
370
425
  response: ResponseType<any, GlobalErrorType, Adapter>,
371
426
  request: RequestInstance,
372
- ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onSuccessCallbacks, response, request);
427
+ ) =>
428
+ interceptResponseSafely<GlobalErrorType, Adapter>({
429
+ client: this,
430
+ interceptors: this.unstable_onSuccessCallbacks,
431
+ response,
432
+ request,
433
+ });
373
434
 
374
435
  /**
375
436
  * Private helper to run async response processing
376
437
  * @private
377
438
  */
378
439
  unstable_modifyResponse = async (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>
379
- interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onResponseCallbacks, response, request);
440
+ interceptResponseSafely<GlobalErrorType, Adapter>({
441
+ client: this,
442
+ interceptors: this.unstable_onResponseCallbacks,
443
+ response,
444
+ request,
445
+ });
380
446
 
381
447
  /**
382
448
  * Reconstruct a Request class instance from its serialized JSON form.
@@ -410,7 +476,20 @@ export class Client<
410
476
  clear = () => {
411
477
  const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
412
478
 
479
+ // Queued and ongoing requests are removed while their listeners still exist - it aborts the ongoing ones
480
+ // and resolves the pending `send()` promises, which otherwise would never settle
481
+ [this.fetchDispatcher, this.submitDispatcher].forEach((dispatcher) => {
482
+ dispatcher.getQueuesKeys().forEach((queryKey) => {
483
+ dispatcher.getQueue(queryKey).requests.forEach(({ request, requestId }) => {
484
+ dispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
485
+ });
486
+ });
487
+ });
488
+ // Requests sent outside of the dispatchers
489
+ this.requestManager.abortAll();
490
+
413
491
  this.requestManager.abortControllers.clear();
492
+ resetOptimisticState(this);
414
493
  this.fetchDispatcher.clear();
415
494
  this.submitDispatcher.clear();
416
495
  this.cache.clear();
@@ -420,6 +499,8 @@ export class Client<
420
499
  this.submitDispatcher.emitter.removeAllListeners();
421
500
  this.cache.emitter.removeAllListeners();
422
501
  this.appManager.unmount();
502
+ // App manager can be shared between the clears, so the listeners of the removed modules have to go away
503
+ this.appManager.emitter.removeAllListeners();
423
504
 
424
505
  this.cache = cache?.() || new Cache();
425
506
  this.appManager = appManager?.() || new AppManager();
@@ -465,7 +546,20 @@ export class Client<
465
546
  }
466
547
 
467
548
  const parsedData = parseResponse(response);
468
- this.cache.set({ ...config, cacheKey, scope }, parsedData);
549
+ this.cache.set(
550
+ { ...config, cacheKey, scope },
551
+ {
552
+ // Hydrated responses did not go through the dispatcher, so the request details get their neutral values
553
+ retries: 0,
554
+ isCanceled: false,
555
+ isOffline: false,
556
+ willRetry: false,
557
+ addedTimestamp: parsedData?.requestTimestamp,
558
+ triggerTimestamp: parsedData?.requestTimestamp,
559
+ ...parsedData,
560
+ hydrated: true,
561
+ },
562
+ );
469
563
  });
470
564
  };
471
565
 
@@ -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;