@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
package/dist/index.mjs CHANGED
@@ -147,6 +147,11 @@ var Plugin = class {
147
147
  this.pluginMethods.onCacheItemDelete = callback;
148
148
  return this;
149
149
  };
150
+ /** Called when a cache entry is invalidated */
151
+ onCacheItemInvalidate = (callback) => {
152
+ this.pluginMethods.onCacheItemInvalidate = callback;
153
+ return this;
154
+ };
150
155
  /** Called when the adapter fetcher is about to execute a request */
151
156
  onAdapterFetch = (callback) => {
152
157
  this.pluginMethods.onAdapterFetch = callback;
@@ -224,14 +229,17 @@ function createRequestHooks(initial) {
224
229
  }
225
230
  //#endregion
226
231
  //#region src/mocker/mocker.ts
227
- var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, onAbortError, adapter }) => {
232
+ var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, adapter }) => {
228
233
  if (!request.unstable_mock) throw new RequestProcessingError("Mock should be defined when calling mocker");
229
234
  let thrown = false;
230
235
  const { requestTime = 20, responseTime = 20, totalUploaded = 1e3, totalDownloaded = 1e3, timeout } = request.unstable_mock.config;
231
- const { data, error, status, success = true, extra = request.client.adapter.defaultExtra } = await request.unstable_mock.fn({
236
+ const result = await request.unstable_mock.fn({
232
237
  request,
233
238
  requestId
234
239
  });
240
+ const { data, error, status, extra = request.client.adapter.defaultExtra } = result;
241
+ const hasData = data !== void 0 && data !== null;
242
+ const { success = !error || hasData } = result;
235
243
  createAbortListener({
236
244
  status: adapter.systemErrorStatus,
237
245
  extra: adapter.systemErrorExtra,
@@ -255,6 +263,7 @@ var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError
255
263
  if (thrown) {
256
264
  resolveProgress(true);
257
265
  clearInterval(timer);
266
+ return;
258
267
  }
259
268
  const currentTime = Math.min(totalTime, Date.now() - dataStart);
260
269
  currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;
@@ -268,7 +277,8 @@ var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError
268
277
  }
269
278
  }, interval);
270
279
  });
271
- if (typeof timeout === "number") setTimeout(() => {
280
+ let timeoutId;
281
+ if (typeof timeout === "number") timeoutId = setTimeout(() => {
272
282
  thrown = true;
273
283
  onTimeoutError({
274
284
  status: 0,
@@ -281,11 +291,9 @@ var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError
281
291
  onResponseStart();
282
292
  }
283
293
  if (!thrown) await progress(responseTime, totalDownloaded, onResponseProgress);
284
- if (thrown) onAbortError({
285
- status: adapter.systemErrorStatus,
286
- extra: adapter.systemErrorExtra
287
- });
288
- else if (success || error && data) onSuccess({
294
+ clearTimeout(timeoutId);
295
+ if (thrown) return;
296
+ if (success || error && data) onSuccess({
289
297
  data,
290
298
  error,
291
299
  status,
@@ -296,7 +304,7 @@ var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError
296
304
  status,
297
305
  extra
298
306
  });
299
- if (!thrown) onResponseEnd();
307
+ onResponseEnd();
300
308
  };
301
309
  //#endregion
302
310
  //#region src/adapter/adapter.bindings.ts
@@ -309,8 +317,9 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
309
317
  let request = baseRequest;
310
318
  let requestTotal = 1;
311
319
  let responseTotal = 1;
312
- let previousRequestTotal = 0;
313
- let previousResponseTotal = 0;
320
+ let previousRequestProgress = null;
321
+ let previousResponseProgress = null;
322
+ const isSameProgress = (previous, next) => !!previous && previous.total === next.total && previous.loaded === next.loaded;
314
323
  logger.debug({
315
324
  title: `Running middleware callbacks`,
316
325
  type: "request",
@@ -327,7 +336,11 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
327
336
  let payload = request.payload;
328
337
  if (request.unstable_payloadMapper) payload = await request.unstable_payloadMapper(request.payload);
329
338
  else if (unstable_payloadMapper) payload = await unstable_payloadMapper(payload);
330
- const adapterOptions = request.options;
339
+ const adapterDefaults = client.adapter.unstable_getAdapterDefaults?.(request);
340
+ const adapterOptions = adapterDefaults ? {
341
+ ...adapterDefaults,
342
+ ...request.options
343
+ } : request.options;
331
344
  const startTime = Date.now();
332
345
  onStartTime(startTime);
333
346
  const getRequestStartTimestamp = () => {
@@ -344,8 +357,11 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
344
357
  };
345
358
  const handleRequestProgress = (startTimestamp, progressTimestamp, progressEvent) => {
346
359
  const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
347
- if (previousRequestTotal !== 100) {
348
- previousRequestTotal = progress.total;
360
+ if (!isSameProgress(previousRequestProgress, progress)) {
361
+ previousRequestProgress = {
362
+ total: progress.total,
363
+ loaded: progress.loaded
364
+ };
349
365
  requestManager.events.emitUploadProgress({
350
366
  ...progress,
351
367
  requestId,
@@ -355,8 +371,11 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
355
371
  };
356
372
  const handleResponseProgress = (startTimestamp, progressTimestamp, progressEvent) => {
357
373
  const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
358
- if (previousResponseTotal !== 100) {
359
- previousResponseTotal = progress.total;
374
+ if (!isSameProgress(previousResponseProgress, progress)) {
375
+ previousResponseProgress = {
376
+ total: progress.total,
377
+ loaded: progress.loaded
378
+ };
360
379
  requestManager.events.emitDownloadProgress({
361
380
  ...progress,
362
381
  requestId,
@@ -460,16 +479,28 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
460
479
  requestTimestamp: startTime,
461
480
  responseTimestamp: Date.now()
462
481
  };
463
- response = await request.client.unstable_modifyResponse?.(response, request);
464
- response = await request.client.unstable_modifySuccessResponse?.(response, request);
465
- client.triggerPlugins("onRequestSuccess", {
466
- response,
467
- request
468
- });
469
- client.triggerPlugins("onRequestFinished", {
470
- response,
471
- request
472
- });
482
+ try {
483
+ response = await request.client.unstable_modifyResponse?.(response, request);
484
+ response = await request.client.unstable_modifySuccessResponse?.(response, request);
485
+ client.triggerPlugins("onRequestSuccess", {
486
+ response,
487
+ request
488
+ });
489
+ client.triggerPlugins("onRequestFinished", {
490
+ response,
491
+ request
492
+ });
493
+ } catch (interceptorError) {
494
+ response = {
495
+ data: null,
496
+ error: internalErrorMapping(interceptorError),
497
+ success: false,
498
+ status,
499
+ extra,
500
+ requestTimestamp: startTime,
501
+ responseTimestamp: Date.now()
502
+ };
503
+ }
473
504
  resolve(response);
474
505
  logger.info({
475
506
  title: `Response success`,
@@ -609,16 +640,25 @@ function getAdapterOnError({ request, requestId, startTime, resolve, logger }) {
609
640
  requestTimestamp: startTime,
610
641
  responseTimestamp: Date.now()
611
642
  };
612
- response = await client.unstable_modifyResponse(response, request);
613
- response = await client.unstable_modifyErrorResponse(response, request);
614
- client.triggerPlugins("onRequestError", {
615
- response,
616
- request
617
- });
618
- client.triggerPlugins("onRequestFinished", {
619
- response,
620
- request
621
- });
643
+ try {
644
+ response = await client.unstable_modifyResponse(response, request);
645
+ response = await client.unstable_modifyErrorResponse(response, request);
646
+ client.triggerPlugins("onRequestError", {
647
+ response,
648
+ request
649
+ });
650
+ client.triggerPlugins("onRequestFinished", {
651
+ response,
652
+ request
653
+ });
654
+ } catch (interceptorError) {
655
+ response = {
656
+ ...response,
657
+ data: null,
658
+ error: interceptorError,
659
+ success: false
660
+ };
661
+ }
622
662
  resolve(response);
623
663
  logger.error({
624
664
  title: `Request error`,
@@ -633,93 +673,439 @@ function getAdapterOnError({ request, requestId, startTime, resolve, logger }) {
633
673
  };
634
674
  }
635
675
  //#endregion
636
- //#region src/utils/uuid.utils.ts
637
- var getUniqueRequestId = (request) => {
638
- return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
676
+ //#region src/adapter/adapter.utils.ts
677
+ var TimeoutError = class extends Error {
678
+ constructor() {
679
+ super("Request timeout");
680
+ this.name = "TimeoutError";
681
+ }
639
682
  };
640
- //#endregion
641
- //#region src/utils/emitter.utils.ts
642
- var import_events = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
643
- var R = typeof Reflect === "object" ? Reflect : null;
644
- var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
645
- return Function.prototype.apply.call(target, receiver, args);
646
- };
647
- var ReflectOwnKeys;
648
- if (R && typeof R.ownKeys === "function") ReflectOwnKeys = R.ownKeys;
649
- else if (Object.getOwnPropertySymbols) ReflectOwnKeys = function ReflectOwnKeys(target) {
650
- return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
651
- };
652
- else ReflectOwnKeys = function ReflectOwnKeys(target) {
653
- return Object.getOwnPropertyNames(target);
654
- };
655
- function ProcessEmitWarning(warning) {
656
- if (console && console.warn) console.warn(warning);
683
+ var AbortError = class extends Error {
684
+ constructor() {
685
+ super("Request aborted");
686
+ this.name = "AbortError";
657
687
  }
658
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
659
- return value !== value;
660
- };
661
- function EventEmitter() {
662
- EventEmitter.init.call(this);
688
+ };
689
+ var DeletedError = class extends Error {
690
+ constructor() {
691
+ super("Request deleted");
692
+ this.name = "DeletedError";
663
693
  }
664
- module.exports = EventEmitter;
665
- module.exports.once = once;
666
- EventEmitter.EventEmitter = EventEmitter;
667
- EventEmitter.prototype._events = void 0;
668
- EventEmitter.prototype._eventsCount = 0;
669
- EventEmitter.prototype._maxListeners = void 0;
670
- var defaultMaxListeners = 10;
671
- function checkListener(listener) {
672
- if (typeof listener !== "function") throw new TypeError("The \"listener\" argument must be of type Function. Received type " + typeof listener);
694
+ };
695
+ var RequestProcessingError = class extends Error {
696
+ description = void 0;
697
+ constructor(description) {
698
+ super("Request processing error");
699
+ this.description = description;
700
+ this.name = "RequestProcessingError";
673
701
  }
674
- Object.defineProperty(EventEmitter, "defaultMaxListeners", {
675
- enumerable: true,
676
- get: function() {
677
- return defaultMaxListeners;
678
- },
679
- set: function(arg) {
680
- if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received " + arg + ".");
681
- defaultMaxListeners = arg;
682
- }
702
+ };
703
+ var UnexpectedError = class extends Error {
704
+ description = void 0;
705
+ constructor(description) {
706
+ super("Unexpected error");
707
+ this.description = description;
708
+ this.name = "UnexpectedError";
709
+ }
710
+ };
711
+ var getErrorMessage = (errorCase) => {
712
+ if (errorCase === "timeout") return new TimeoutError();
713
+ if (errorCase === "abort") return new AbortError();
714
+ if (errorCase === "deleted") return new DeletedError();
715
+ if (errorCase === "processing") return new RequestProcessingError();
716
+ return new UnexpectedError();
717
+ };
718
+ var stringifyValue = (response) => {
719
+ try {
720
+ return JSON.stringify(response);
721
+ } catch {
722
+ return "";
723
+ }
724
+ };
725
+ /**
726
+ * Payloads which are sent as they are - `fetch`, XHR and other transports know how to handle them
727
+ * (and how to describe them with the `Content-Type` header)
728
+ */
729
+ var isRawPayload = (payload) => {
730
+ return typeof FormData !== "undefined" && payload instanceof FormData || typeof Blob !== "undefined" && payload instanceof Blob || typeof URLSearchParams !== "undefined" && payload instanceof URLSearchParams || typeof ReadableStream !== "undefined" && payload instanceof ReadableStream || typeof ArrayBuffer !== "undefined" && (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload));
731
+ };
732
+ /** `HeadersInit` can be an object, a list of pairs or the `Headers` instance */
733
+ var getHeadersEntries = (headers) => {
734
+ if (!headers) return [];
735
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
736
+ const entries = [];
737
+ headers.forEach((value, key) => entries.push([key, value]));
738
+ return entries;
739
+ }
740
+ if (Array.isArray(headers)) return headers;
741
+ return Object.entries(headers);
742
+ };
743
+ var getAdapterHeaders = (request) => {
744
+ const isObject = typeof request.payload === "object" && request.payload !== null;
745
+ const entries = getHeadersEntries(request.headers);
746
+ const hasContentType = entries.some(([name]) => name.toLowerCase() === "content-type");
747
+ const headers = {};
748
+ if (isObject && !isRawPayload(request.payload) && !hasContentType) headers["Content-Type"] = "application/json";
749
+ entries.forEach(([name, value]) => {
750
+ if (value !== void 0 && value !== null) headers[name] = value;
683
751
  });
684
- EventEmitter.init = function() {
685
- if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
686
- this._events = Object.create(null);
687
- this._eventsCount = 0;
688
- }
689
- this._maxListeners = this._maxListeners || void 0;
752
+ return headers;
753
+ };
754
+ var getAdapterPayload = (data) => {
755
+ if (isRawPayload(data)) return data;
756
+ return stringifyValue(data);
757
+ };
758
+ //#endregion
759
+ //#region src/adapter/adapter.ts
760
+ var defaultMapper = (value) => value;
761
+ /**
762
+ * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,
763
+ * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class
764
+ * to integrate custom transport layers (e.g., axios, graphql, firebase).
765
+ */
766
+ var Adapter = class {
767
+ /** Fetching function */
768
+ unstable_fetcher;
769
+ /**
770
+ * ********************
771
+ * Defaults
772
+ * ********************
773
+ */
774
+ name;
775
+ defaultMethod;
776
+ defaultExtra;
777
+ systemErrorStatus;
778
+ systemErrorExtra;
779
+ defaultRequestOptions = void 0;
780
+ logger;
781
+ initialized = false;
782
+ client;
783
+ unstable_onInitializeCallback = void 0;
784
+ unstable_queryParamsMapperConfig;
785
+ unstable_headerMapperConfig;
786
+ unstable_payloadMapperConfig;
787
+ unstable_endpointMapperConfig;
788
+ /**
789
+ * Type-only carrier of the additional `createRequest` fields declared by this adapter.
790
+ * It has no runtime value - adapters read those fields from `request.requestOptions`.
791
+ */
792
+ unstable_requestOptionsType = void 0;
793
+ constructor(options) {
794
+ this.options = options;
795
+ this.name = options.name;
796
+ this.defaultMethod = options.defaultMethod;
797
+ this.defaultExtra = options.defaultExtra;
798
+ this.systemErrorStatus = options.systemErrorStatus;
799
+ this.systemErrorExtra = options.systemErrorExtra;
800
+ this.defaultRequestOptions = options.defaultRequestOptions;
801
+ }
802
+ /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */
803
+ initialize = (client) => {
804
+ this.logger = client.loggerManager.initialize(client, "Adapter");
805
+ this.initialized = true;
806
+ this.client = client;
807
+ this.unstable_onInitializeCallback?.({ client });
808
+ return this;
690
809
  };
691
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
692
- if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received " + n + ".");
693
- this._maxListeners = n;
810
+ /** Register a callback invoked once the adapter is initialized with a client. */
811
+ onInitialize = (callback) => {
812
+ this.unstable_onInitializeCallback = callback;
694
813
  return this;
695
814
  };
696
- function _getMaxListeners(that) {
697
- if (that._maxListeners === void 0) return EventEmitter.defaultMaxListeners;
698
- return that._maxListeners;
699
- }
700
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
701
- return _getMaxListeners(this);
815
+ /**
816
+ * ********************
817
+ * Options Setters
818
+ * ********************
819
+ */
820
+ unstable_internalErrorMapping = (error) => error;
821
+ /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
822
+ unstable_headerMapper = getAdapterHeaders;
823
+ /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
824
+ unstable_payloadMapper = getAdapterPayload;
825
+ /** Method to get the endpoint for the adapter request. */
826
+ unstable_endpointMapper = defaultMapper;
827
+ /** Method to get request data and transform them to the required format. */
828
+ unstable_queryParamsMapper = defaultMapper;
829
+ /** Get default adapter options for the request. */
830
+ unstable_getAdapterDefaults = void 0;
831
+ /** Get default request options for the request. */
832
+ unstable_getRequestDefaults = void 0;
833
+ /**
834
+ * Get formatted endpoint name of the request.
835
+ * Helpful in displaying long endpoints like in case of graphql schemas etc.
836
+ */
837
+ unstable_devtoolsEndpointGetter = (endpoint) => endpoint;
838
+ /**
839
+ * ********************
840
+ * Methods
841
+ * ********************
842
+ */
843
+ /** Set the default HTTP method used when a request does not specify one. */
844
+ setDefaultMethod = (method) => {
845
+ this.defaultMethod = method;
846
+ return this;
702
847
  };
703
- EventEmitter.prototype.emit = function emit(type) {
704
- var args = [];
705
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
706
- var doError = type === "error";
707
- var events = this._events;
708
- if (events !== void 0) doError = doError && events.error === void 0;
709
- else if (!doError) return false;
710
- if (doError) {
711
- var er;
712
- if (args.length > 0) er = args[0];
713
- if (er instanceof Error) throw er;
714
- var err = /* @__PURE__ */ new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
715
- err.context = er;
716
- throw err;
717
- }
718
- var handler = events[type];
719
- if (handler === void 0) return false;
720
- if (typeof handler === "function") ReflectApply(handler, this, args);
721
- else {
722
- var len = handler.length;
848
+ /** Set the default extra metadata attached to every request response (e.g., headers, status). */
849
+ setDefaultExtra = (extra) => {
850
+ this.defaultExtra = extra;
851
+ return this;
852
+ };
853
+ /** Set a function that formats the endpoint string for display in devtools. */
854
+ setDevtoolsEndpointGetter = (callback) => {
855
+ this.unstable_devtoolsEndpointGetter = callback;
856
+ return this;
857
+ };
858
+ /**
859
+ * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
860
+ */
861
+ setRequestDefaults = (callback) => {
862
+ this.unstable_getRequestDefaults = callback;
863
+ return this;
864
+ };
865
+ /**
866
+ * Set the adapter default options added to every sent request
867
+ */
868
+ setAdapterDefaults = (callback) => {
869
+ this.unstable_getAdapterDefaults = callback;
870
+ return this;
871
+ };
872
+ /** Set a custom mapping for internal adapter errors before they are returned in the response. */
873
+ setInternalErrorMapping = (callback) => {
874
+ this.unstable_internalErrorMapping = callback;
875
+ return this;
876
+ };
877
+ /**
878
+ * Set the custom header mapping function
879
+ */
880
+ setHeaderMapper = (headerMapper) => {
881
+ this.unstable_headerMapper = ((req) => headerMapper(req, this.unstable_headerMapperConfig));
882
+ return this;
883
+ };
884
+ /**
885
+ * Set the request payload mapping function which gets triggered before request is send
886
+ */
887
+ setPayloadMapper = (payloadMapper) => {
888
+ this.unstable_payloadMapper = ((req) => payloadMapper(req, this.unstable_payloadMapperConfig));
889
+ return this;
890
+ };
891
+ /**
892
+ * Set the endpoint mapping function which transforms the endpoint string before the request is sent
893
+ */
894
+ setEndpointMapper = (endpointMapper) => {
895
+ this.unstable_endpointMapper = ((endpoint) => endpointMapper(endpoint, this.unstable_endpointMapperConfig));
896
+ return this;
897
+ };
898
+ /**
899
+ * Set the query params mapping function which get triggered before request get sent
900
+ */
901
+ setQueryParamsMapper = (queryParamsMapper) => {
902
+ this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
903
+ return this;
904
+ };
905
+ /** Set the configuration object passed as the second argument to the query params mapper. */
906
+ setQueryParamsMapperConfig = (config) => {
907
+ this.unstable_queryParamsMapperConfig = config;
908
+ return this;
909
+ };
910
+ /** Set the configuration object passed as the second argument to the header mapper. */
911
+ setHeaderMapperConfig = (config) => {
912
+ this.unstable_headerMapperConfig = config;
913
+ return this;
914
+ };
915
+ /** Set the configuration object passed as the second argument to the endpoint mapper. */
916
+ setEndpointMapperConfig = (config) => {
917
+ this.unstable_endpointMapperConfig = config;
918
+ return this;
919
+ };
920
+ /** Set the configuration object passed as the second argument to the payload mapper. */
921
+ setPayloadMapperConfig = (config) => {
922
+ this.unstable_payloadMapperConfig = config;
923
+ return this;
924
+ };
925
+ /**
926
+ * ********************
927
+ * Fetching
928
+ * ********************
929
+ */
930
+ /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */
931
+ setFetcher(fetcher) {
932
+ this.unstable_fetcher = fetcher.bind(this);
933
+ return this;
934
+ }
935
+ /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
936
+ async fetch(request, requestId) {
937
+ let startTime;
938
+ const execute = async (resolve) => {
939
+ try {
940
+ if (!this.initialized) throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
941
+ if (!this.unstable_fetcher) throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
942
+ this.client.triggerPlugins("onAdapterFetch", {
943
+ adapter: this,
944
+ request,
945
+ requestId
946
+ });
947
+ const bindings = await getAdapterBindings({
948
+ request,
949
+ requestId,
950
+ resolve,
951
+ internalErrorMapping: this.unstable_internalErrorMapping,
952
+ onStartTime: (time) => {
953
+ startTime = time;
954
+ }
955
+ });
956
+ if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
957
+ return this.unstable_fetcher(bindings);
958
+ } catch (error) {
959
+ return getAdapterOnError({
960
+ request,
961
+ requestId,
962
+ startTime: startTime || Date.now(),
963
+ logger: this.logger,
964
+ resolve
965
+ })({
966
+ error: this.unstable_internalErrorMapping(error),
967
+ status: this.options.systemErrorStatus,
968
+ extra: this.options.systemErrorExtra
969
+ });
970
+ }
971
+ };
972
+ return new Promise((resolve) => {
973
+ execute(resolve);
974
+ });
975
+ }
976
+ };
977
+ //#endregion
978
+ //#region src/constants/http.constants.ts
979
+ var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
980
+ HttpMethods["GET"] = "GET";
981
+ HttpMethods["POST"] = "POST";
982
+ HttpMethods["PUT"] = "PUT";
983
+ HttpMethods["PATCH"] = "PATCH";
984
+ HttpMethods["DELETE"] = "DELETE";
985
+ /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */
986
+ HttpMethods["QUERY"] = "QUERY";
987
+ return HttpMethods;
988
+ }({});
989
+ /** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
990
+ var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
991
+ //#endregion
992
+ //#region src/utils/error.utils.ts
993
+ /**
994
+ * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
995
+ * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the
996
+ * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).
997
+ * @internal
998
+ * @param error value thrown by the user code
999
+ */
1000
+ var throwOutsideLifecycle = (error) => {
1001
+ setTimeout(() => {
1002
+ throw error;
1003
+ });
1004
+ };
1005
+ /**
1006
+ * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on
1007
+ * and the error is thrown outside of it.
1008
+ * @internal
1009
+ * @param callback code of the user to run
1010
+ * @returns `true` when the callback finished, `false` when it threw
1011
+ */
1012
+ var runUserCode = (callback) => {
1013
+ try {
1014
+ callback();
1015
+ return true;
1016
+ } catch (error) {
1017
+ throwOutsideLifecycle(error);
1018
+ return false;
1019
+ }
1020
+ };
1021
+ //#endregion
1022
+ //#region src/utils/uuid.utils.ts
1023
+ var getUniqueRequestId = (request) => {
1024
+ return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
1025
+ };
1026
+ //#endregion
1027
+ //#region src/utils/emitter.utils.ts
1028
+ var import_events = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1029
+ var R = typeof Reflect === "object" ? Reflect : null;
1030
+ var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
1031
+ return Function.prototype.apply.call(target, receiver, args);
1032
+ };
1033
+ var ReflectOwnKeys;
1034
+ if (R && typeof R.ownKeys === "function") ReflectOwnKeys = R.ownKeys;
1035
+ else if (Object.getOwnPropertySymbols) ReflectOwnKeys = function ReflectOwnKeys(target) {
1036
+ return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
1037
+ };
1038
+ else ReflectOwnKeys = function ReflectOwnKeys(target) {
1039
+ return Object.getOwnPropertyNames(target);
1040
+ };
1041
+ function ProcessEmitWarning(warning) {
1042
+ if (console && console.warn) console.warn(warning);
1043
+ }
1044
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
1045
+ return value !== value;
1046
+ };
1047
+ function EventEmitter() {
1048
+ EventEmitter.init.call(this);
1049
+ }
1050
+ module.exports = EventEmitter;
1051
+ module.exports.once = once;
1052
+ EventEmitter.EventEmitter = EventEmitter;
1053
+ EventEmitter.prototype._events = void 0;
1054
+ EventEmitter.prototype._eventsCount = 0;
1055
+ EventEmitter.prototype._maxListeners = void 0;
1056
+ var defaultMaxListeners = 10;
1057
+ function checkListener(listener) {
1058
+ if (typeof listener !== "function") throw new TypeError("The \"listener\" argument must be of type Function. Received type " + typeof listener);
1059
+ }
1060
+ Object.defineProperty(EventEmitter, "defaultMaxListeners", {
1061
+ enumerable: true,
1062
+ get: function() {
1063
+ return defaultMaxListeners;
1064
+ },
1065
+ set: function(arg) {
1066
+ if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received " + arg + ".");
1067
+ defaultMaxListeners = arg;
1068
+ }
1069
+ });
1070
+ EventEmitter.init = function() {
1071
+ if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
1072
+ this._events = Object.create(null);
1073
+ this._eventsCount = 0;
1074
+ }
1075
+ this._maxListeners = this._maxListeners || void 0;
1076
+ };
1077
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
1078
+ if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received " + n + ".");
1079
+ this._maxListeners = n;
1080
+ return this;
1081
+ };
1082
+ function _getMaxListeners(that) {
1083
+ if (that._maxListeners === void 0) return EventEmitter.defaultMaxListeners;
1084
+ return that._maxListeners;
1085
+ }
1086
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
1087
+ return _getMaxListeners(this);
1088
+ };
1089
+ EventEmitter.prototype.emit = function emit(type) {
1090
+ var args = [];
1091
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
1092
+ var doError = type === "error";
1093
+ var events = this._events;
1094
+ if (events !== void 0) doError = doError && events.error === void 0;
1095
+ else if (!doError) return false;
1096
+ if (doError) {
1097
+ var er;
1098
+ if (args.length > 0) er = args[0];
1099
+ if (er instanceof Error) throw er;
1100
+ var err = /* @__PURE__ */ new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
1101
+ err.context = er;
1102
+ throw err;
1103
+ }
1104
+ var handler = events[type];
1105
+ if (handler === void 0) return false;
1106
+ if (typeof handler === "function") ReflectApply(handler, this, args);
1107
+ else {
1108
+ var len = handler.length;
723
1109
  var listeners = arrayClone(handler, len);
724
1110
  for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
725
1111
  }
@@ -937,8 +1323,10 @@ var EventEmitter = class extends import_events.default {
937
1323
  emit(type, data, isTriggeredExternally) {
938
1324
  const params = [type, data];
939
1325
  if (isTriggeredExternally) params.push(isTriggeredExternally);
940
- this.emitCallbacks?.forEach((callback) => callback(...params));
941
- return super.emit(...params);
1326
+ this.emitCallbacks?.forEach((callback) => runUserCode(() => callback(...params)));
1327
+ const listeners = this.rawListeners(type);
1328
+ listeners.forEach((listener) => runUserCode(() => listener.call(this, ...params.slice(1))));
1329
+ return listeners.length > 0;
942
1330
  }
943
1331
  onEmit = (callback) => {
944
1332
  this.emitCallbacks?.push(callback);
@@ -966,1152 +1354,320 @@ var EventEmitter = class extends import_events.default {
966
1354
  removeListener = this.off;
967
1355
  };
968
1356
  //#endregion
969
- //#region src/managers/app/app.manager.ts
970
- /**
971
- * App manager handles main application states - focus and online. Those two values can answer questions:
972
- * - Is the tab or current view instance focused and visible for user?
973
- * - Is our application online or offline?
974
- * With the app manager it is not a problem to get the valid answer for this question.
975
- *
976
- * @caution
977
- * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
978
- */
979
- var AppManager = class {
980
- emitter = new EventEmitter();
981
- events = getAppManagerEvents(this.emitter);
982
- isBrowser;
983
- isOnline;
984
- isFocused;
985
- unmountCallbacks = [];
986
- constructor(options) {
987
- this.options = options;
988
- this.emitter?.setMaxListeners(1e3);
989
- const { initiallyFocused = appManagerInitialOptions.initiallyFocused, initiallyOnline = appManagerInitialOptions.initiallyOnline } = this.options || appManagerInitialOptions;
990
- this.setInitialFocus(initiallyFocused);
991
- this.setInitialOnline(initiallyOnline);
992
- this.isBrowser = hasDocument();
1357
+ //#region src/request/request.utils.ts
1358
+ var scopeKey = (key, scope) => {
1359
+ return scope ? `${scope}__${key}` : key;
1360
+ };
1361
+ var stringifyKey = (value) => {
1362
+ try {
1363
+ if (typeof value === "string") return value;
1364
+ if (value === void 0 || value === null) return "";
1365
+ const data = JSON.stringify(value);
1366
+ if (typeof data !== "string") throw new TypeError();
1367
+ return data;
1368
+ } catch {
1369
+ return "";
993
1370
  }
994
- /**
995
- * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,
996
- * so the listeners are never registered twice.
997
- */
998
- initialize = () => {
999
- const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } = this.options || appManagerInitialOptions;
1000
- this.unmount();
1001
- [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {
1002
- if (typeof unmount === "function") this.unmountCallbacks.push(unmount);
1003
- });
1004
- };
1005
- /**
1006
- * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.
1007
- */
1008
- unmount = () => {
1009
- const callbacks = this.unmountCallbacks;
1010
- this.unmountCallbacks = [];
1011
- callbacks.forEach((unmount) => unmount());
1012
- };
1013
- setInitialFocus = async (initValue) => {
1014
- if (typeof initValue !== "function") {
1015
- this.isFocused = initValue;
1016
- return;
1017
- }
1018
- const value = initValue();
1019
- if (typeof value === "boolean") this.isFocused = value;
1020
- else {
1021
- this.isFocused = false;
1022
- this.isFocused = await value;
1023
- }
1024
- };
1025
- setInitialOnline = async (initValue) => {
1026
- if (typeof initValue !== "function") {
1027
- this.isOnline = initValue;
1028
- return;
1029
- }
1030
- const value = initValue();
1031
- if (typeof value === "boolean") this.isOnline = value;
1032
- else {
1033
- this.isOnline = false;
1034
- this.isOnline = await value;
1035
- }
1371
+ };
1372
+ var getProgressValue = ({ loaded, total }) => {
1373
+ if (!loaded || !total) return 0;
1374
+ return Number((loaded * 100 / total).toFixed(0));
1375
+ };
1376
+ var getRequestEta = (startDate, progressDate, { total, loaded }) => {
1377
+ const uploadSpeed = loaded / (+progressDate - +startDate || 1);
1378
+ const totalValue = Math.max(total, loaded);
1379
+ const sizeLeft = totalValue - loaded;
1380
+ const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;
1381
+ return {
1382
+ timeLeft: totalValue === loaded ? 0 : estimatedTimeValue,
1383
+ sizeLeft
1036
1384
  };
1037
- setFocused = (isFocused) => {
1038
- this.isFocused = isFocused;
1039
- if (isFocused) this.events.emitFocus();
1040
- else this.events.emitBlur();
1385
+ };
1386
+ var getProgressData = (requestStartTime, progressDate, progressEvent) => {
1387
+ const { total, loaded } = progressEvent;
1388
+ if (Number.isNaN(total) || Number.isNaN(loaded)) return {
1389
+ progress: 0,
1390
+ timeLeft: 0,
1391
+ sizeLeft: 0,
1392
+ total: 0,
1393
+ loaded: 0,
1394
+ startTimestamp: +requestStartTime
1041
1395
  };
1042
- setOnline = (isOnline) => {
1043
- this.isOnline = isOnline;
1044
- if (isOnline) this.events.emitOnline();
1045
- else this.events.emitOffline();
1396
+ const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);
1397
+ return {
1398
+ progress: getProgressValue(progressEvent),
1399
+ timeLeft,
1400
+ sizeLeft,
1401
+ total,
1402
+ loaded,
1403
+ startTimestamp: +requestStartTime
1046
1404
  };
1047
1405
  };
1048
- //#endregion
1049
- //#region src/managers/app/app.manager.utils.ts
1050
- var hasWindow = () => {
1051
- try {
1052
- return Boolean(window && window.addEventListener);
1053
- } catch {
1054
- /* istanbul ignore next */
1055
- return false;
1056
- }
1406
+ var getSimpleKey = (request) => {
1407
+ return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;
1057
1408
  };
1058
- var hasDocument = () => {
1409
+ /**
1410
+ * Cache instance for individual request that collects individual requests responses from
1411
+ * the same endpoint (they may differ base on the custom key, endpoint params etc)
1412
+ * @param request
1413
+ * @param useInitialValues
1414
+ * @returns
1415
+ */
1416
+ var getRequestKey = (request, useInitialValues) => {
1417
+ return `${stringifyKey(request.method)}_${useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint)}_${useInitialValues ? "" : stringifyKey(request.queryParams)}`;
1418
+ };
1419
+ var getRequestDispatcher = (request, dispatcherType = "auto") => {
1420
+ const { fetchDispatcher, submitDispatcher } = request.client;
1421
+ const isSafeRead = SAFE_HTTP_METHODS.includes(request.method);
1422
+ const isFetchDispatcher = dispatcherType === "auto" && isSafeRead || dispatcherType === "fetch";
1423
+ return [isFetchDispatcher ? fetchDispatcher : submitDispatcher, isFetchDispatcher];
1424
+ };
1425
+ /**
1426
+ * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,
1427
+ * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.
1428
+ * Failures are always delivered through a promise, so sync and async mappers fail the same way.
1429
+ * @internal
1430
+ * @param request request with the optional response mapper
1431
+ * @param response response to be mapped
1432
+ * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper
1433
+ */
1434
+ var runResponseMapper = (request, response) => {
1435
+ const getFailedResponse = (error) => {
1436
+ request.client.logger.error({
1437
+ title: "Response mapper failed",
1438
+ type: "system",
1439
+ extra: {
1440
+ error,
1441
+ request,
1442
+ response
1443
+ }
1444
+ });
1445
+ return {
1446
+ ...response,
1447
+ data: null,
1448
+ error,
1449
+ success: false
1450
+ };
1451
+ };
1059
1452
  try {
1060
- return Boolean(hasWindow() && window.document && window.document.addEventListener);
1061
- } catch {
1062
- /* istanbul ignore next */
1063
- return false;
1453
+ const mapping = request.unstable_responseMapper?.(response);
1454
+ return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;
1455
+ } catch (error) {
1456
+ return Promise.resolve(getFailedResponse(error));
1064
1457
  }
1065
1458
  };
1459
+ var mapResponseForSend = async (request, response) => {
1460
+ const mapping = runResponseMapper(request, response);
1461
+ if (mapping instanceof Promise) return await mapping;
1462
+ return mapping || response;
1463
+ };
1066
1464
  /**
1067
- * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or
1068
- * React Native, where `navigator.onLine` is not available.
1465
+ * Rollback is user code running in the middle of the response handling, its failure can't affect the request
1069
1466
  */
1070
- var isNavigatorOnline = () => {
1467
+ var rollbackOptimistic = (optimistic, args) => {
1468
+ const logFailure = (error) => {
1469
+ args.request.client.logger.error({
1470
+ title: "Optimistic rollback failed",
1471
+ type: "system",
1472
+ extra: {
1473
+ error,
1474
+ reason: args.reason,
1475
+ request: args.request
1476
+ }
1477
+ });
1478
+ throwOutsideLifecycle(error);
1479
+ };
1071
1480
  try {
1072
- return typeof navigator.onLine === "boolean" ? navigator.onLine : true;
1073
- } catch {
1074
- /* istanbul ignore next */
1075
- return true;
1481
+ Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);
1482
+ } catch (error) {
1483
+ logFailure(error);
1076
1484
  }
1077
1485
  };
1078
- var onWindowEvent = (key, listener, options) => {
1079
- /* istanbul ignore next */
1080
- if (hasWindow()) {
1081
- window.addEventListener(key, listener, options);
1082
- return () => window.removeEventListener(key, listener, options);
1083
- }
1084
- /* istanbul ignore next */
1085
- return () => null;
1486
+ var invalidateOptimistic = (optimistic, request) => {
1487
+ optimistic.invalidate?.forEach((target) => {
1488
+ try {
1489
+ request.client.cache.invalidate(target);
1490
+ } catch (error) {
1491
+ request.client.logger.error({
1492
+ title: "Optimistic invalidation failed",
1493
+ type: "system",
1494
+ extra: {
1495
+ error,
1496
+ target,
1497
+ request
1498
+ }
1499
+ });
1500
+ throwOutsideLifecycle(error);
1501
+ }
1502
+ });
1086
1503
  };
1087
- var onDocumentEvent = (key, listener, options) => {
1088
- /* istanbul ignore next */
1089
- if (hasDocument()) {
1090
- window.document.addEventListener(key, listener, options);
1091
- return () => window.document.removeEventListener(key, listener, options);
1504
+ var sendRequest = async (request, options) => {
1505
+ const { client } = request;
1506
+ const { requestManager } = client;
1507
+ const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
1508
+ let mutationContext;
1509
+ if (request.optimistic) try {
1510
+ mutationContext = await request.optimistic({
1511
+ request,
1512
+ client: request.client,
1513
+ payload: request.payload
1514
+ });
1515
+ } catch (error) {
1516
+ return {
1517
+ data: null,
1518
+ error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
1519
+ status: null,
1520
+ success: false,
1521
+ extra: client.adapter.defaultExtra,
1522
+ requestTimestamp: Date.now(),
1523
+ responseTimestamp: Date.now()
1524
+ };
1092
1525
  }
1093
- /* istanbul ignore next */
1094
- return () => null;
1095
- };
1096
- //#endregion
1097
- //#region src/managers/app/app.manager.events.ts
1098
- /** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */
1099
- var getAppManagerEvents = (emitter) => ({
1100
- emitFocus: () => {
1101
- emitter.emit(AppEvents.FOCUS);
1102
- },
1103
- emitBlur: () => {
1104
- emitter.emit(AppEvents.BLUR);
1105
- },
1106
- emitOnline: () => {
1107
- emitter.emit(AppEvents.ONLINE);
1108
- },
1109
- emitOffline: () => {
1110
- emitter.emit(AppEvents.OFFLINE);
1111
- },
1112
- onFocus: (callback) => {
1113
- emitter.on(AppEvents.FOCUS, callback);
1114
- return () => emitter.removeListener(AppEvents.FOCUS, callback);
1115
- },
1116
- onBlur: (callback) => {
1117
- emitter.on(AppEvents.BLUR, callback);
1118
- return () => emitter.removeListener(AppEvents.BLUR, callback);
1119
- },
1120
- onOnline: (callback) => {
1121
- emitter.on(AppEvents.ONLINE, callback);
1122
- return () => emitter.removeListener(AppEvents.ONLINE, callback);
1123
- },
1124
- onOffline: (callback) => {
1125
- emitter.on(AppEvents.OFFLINE, callback);
1126
- return () => emitter.removeListener(AppEvents.OFFLINE, callback);
1127
- }
1128
- });
1129
- //#endregion
1130
- //#region src/managers/app/app.manager.constants.ts
1131
- var AppEvents = /* @__PURE__ */ function(AppEvents) {
1132
- AppEvents["FOCUS"] = "focus";
1133
- AppEvents["BLUR"] = "blur";
1134
- AppEvents["ONLINE"] = "online";
1135
- AppEvents["OFFLINE"] = "offline";
1136
- return AppEvents;
1137
- }({});
1138
- var appManagerInitialOptions = {
1139
- initiallyFocused: true,
1140
- initiallyOnline: isNavigatorOnline,
1141
- focusEvent: (setFocused) => {
1142
- const unmountVisibility = onDocumentEvent("visibilitychange", () => setFocused(true));
1143
- const unmountFocus = onWindowEvent("focus", () => setFocused(true));
1144
- const unmountBlur = onWindowEvent("blur", () => setFocused(false));
1145
- return () => {
1146
- unmountVisibility();
1147
- unmountFocus();
1148
- unmountBlur();
1526
+ return new Promise((resolve) => {
1527
+ let isResolved = false;
1528
+ let isDelivered = false;
1529
+ let isSettled = false;
1530
+ const requestId = dispatcher.add(request);
1531
+ const queryKey = scopeKey(request.queryKey, request.scope);
1532
+ const { $hooks } = request;
1533
+ const getWillBeResent = ({ response, details }) => {
1534
+ if (response.success || details.isCanceled) return false;
1535
+ if (!dispatcher.getRequest(queryKey, requestId)) return false;
1536
+ return details.willRetry || request.offline && details.isOffline;
1149
1537
  };
1150
- },
1151
- onlineEvent: (setOnline) => {
1152
- const unmountOnline = onWindowEvent("online", () => setOnline(true));
1153
- const unmountOffline = onWindowEvent("offline", () => setOnline(false));
1154
- return () => {
1155
- unmountOnline();
1156
- unmountOffline();
1538
+ const mappings = /* @__PURE__ */ new WeakMap();
1539
+ const getMapping = (values) => {
1540
+ if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
1541
+ return mappings.get(values);
1157
1542
  };
1158
- }
1159
- };
1160
- //#endregion
1161
- //#region src/managers/request/request.manager.ts
1162
- /**
1163
- * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.
1164
- * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.
1165
- */
1166
- var RequestManager = class {
1167
- emitter = new EventEmitter();
1168
- events = getRequestManagerEvents(this.emitter);
1169
- constructor() {
1170
- this.emitter?.setMaxListeners(1e3);
1171
- }
1172
- abortControllers = /* @__PURE__ */ new Map();
1173
- addAbortController = (abortKey, requestId) => {
1174
- let abortGroup = this.abortControllers.get(abortKey);
1175
- if (!abortGroup) {
1176
- const newAbortGroup = /* @__PURE__ */ new Map();
1177
- abortGroup = newAbortGroup;
1178
- this.abortControllers.set(abortKey, newAbortGroup);
1179
- }
1180
- const abortController = abortGroup.get(requestId);
1181
- if (!abortController || abortController.signal.aborted) abortGroup.set(requestId, new AbortController());
1182
- };
1183
- getAbortController = (abortKey, requestId) => {
1184
- return this.abortControllers.get(abortKey)?.get(requestId);
1185
- };
1186
- removeAbortController = (abortKey, requestId) => {
1187
- this.abortControllers.get(abortKey)?.delete(requestId);
1188
- };
1189
- useAbortController = (abortKey, requestId) => {
1190
- (this.abortControllers.get(abortKey)?.get(requestId))?.abort();
1191
- };
1192
- abortByKey = (abortKey) => {
1193
- const controllers = this.abortControllers.get(abortKey);
1194
- if (controllers) [...controllers.entries()].forEach(([key]) => {
1195
- this.useAbortController(abortKey, key);
1543
+ const unmountSettlement = mutationContext ? requestManager.events.onResponseById(requestId, (values) => {
1544
+ const optimistic = mutationContext;
1545
+ const willBeResent = getWillBeResent(values);
1546
+ const settle = (response) => {
1547
+ if (isSettled || !response.success && willBeResent) return;
1548
+ isSettled = true;
1549
+ if (values.details.isCanceled) rollbackOptimistic(optimistic, {
1550
+ reason: "abort",
1551
+ response,
1552
+ request
1553
+ });
1554
+ else if (response.success) invalidateOptimistic(optimistic, request);
1555
+ else rollbackOptimistic(optimistic, {
1556
+ reason: "error",
1557
+ response,
1558
+ request
1559
+ });
1560
+ };
1561
+ const mapping = getMapping(values);
1562
+ if (mapping instanceof Promise) mapping.then(settle);
1563
+ else settle(mapping || values.response);
1564
+ }) : void 0;
1565
+ const beforeSentData = {
1566
+ requestId,
1567
+ request,
1568
+ mutationContext
1569
+ };
1570
+ runUserCode(() => options?.onBeforeSent?.(beforeSentData));
1571
+ runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
1572
+ const unmountRequestStart = requestManager.events.onRequestStartById(requestId, (data) => {
1573
+ const enriched = {
1574
+ ...data,
1575
+ mutationContext
1576
+ };
1577
+ runUserCode(() => options?.onRequestStart?.(enriched));
1578
+ runUserCode(() => $hooks.__emit("onRequestStart", enriched));
1196
1579
  });
1197
- };
1198
- abortByRequestId = (abortKey, requestId) => {
1199
- this.useAbortController(abortKey, requestId);
1200
- };
1201
- abortAll = () => {
1202
- [...this.abortControllers.entries()].forEach(([abortKey, value]) => {
1203
- [...value.entries()].forEach(([requestId]) => {
1204
- this.useAbortController(abortKey, requestId);
1205
- });
1580
+ const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
1581
+ const enriched = {
1582
+ ...data,
1583
+ mutationContext
1584
+ };
1585
+ runUserCode(() => options?.onResponseStart?.(enriched));
1586
+ runUserCode(() => $hooks.__emit("onResponseStart", enriched));
1206
1587
  });
1207
- };
1208
- };
1209
- //#endregion
1210
- //#region src/managers/request/request.manager.utils.ts
1211
- var getLoadingKey = () => `loading-event-any`;
1212
- var getLoadingByQueryKey = (queryKey) => `${queryKey}-loading-event`;
1213
- var getLoadingByCacheKey = (cacheKey) => `${cacheKey}-loading-cache-event`;
1214
- var getLoadingByIdKey = (id) => `${id}-loading-event-by-id`;
1215
- var getRemoveKey = () => `remove-event-any`;
1216
- var getRemoveByQueryKey = (queryKey) => `${queryKey}-remove-event`;
1217
- var getRemoveByIdKey = (id) => `${id}-remove-event-by-id`;
1218
- var getAbortKey = () => `request-abort-any`;
1219
- var getAbortByAbortKey = (abortKey) => `${abortKey}-request-abort`;
1220
- var getAbortByIdKey = (id) => `${id}-request-abort-by-id`;
1221
- var getResponseKey = () => `response-any`;
1222
- var getResponseByCacheKey = (cacheKey) => `${cacheKey}-response`;
1223
- var getResponseByIdKey = (id) => `${id}-response-by-id`;
1224
- var getRequestStartKey = () => `request-start-any`;
1225
- var getRequestStarByQueryKey = (queryKey) => `${queryKey}-request-start`;
1226
- var getRequestStartByIdKey = (id) => `${id}-request-start-by-id`;
1227
- var getResponseStartKey = () => `response-start-any`;
1228
- var getResponseStartByQueryKey = (queryKey) => `${queryKey}-response-start`;
1229
- var getResponseStartByIdKey = (id) => `${id}-response-start-by-id`;
1230
- var getUploadProgressKey = () => `request-progress-any`;
1231
- var getUploadProgressByQueryKey = (queryKey) => `${queryKey}-request-progress`;
1232
- var getUploadProgressByIdKey = (id) => `${id}-request-progress-by-id`;
1233
- var getDownloadProgressKey = () => `response-progress-any`;
1234
- var getDownloadProgressByQueryKey = (queryKey) => `${queryKey}-response-progress`;
1235
- var getDownloadProgressByIdKey = (id) => `${id}-response-progress-by-id`;
1236
- var getRequestDeduplicatedKey = () => `request-deduplicated-any`;
1237
- var getRequestDeduplicatedByQueryKey = (queryKey) => `${queryKey}-query-request-deduplicated`;
1238
- var getRequestDeduplicatedByCacheKey = (cacheKey) => `${cacheKey}-cache-request-deduplicated`;
1239
- var getRequestDeduplicatedByIdKey = (id) => `${id}-request-deduplicated-by-id`;
1240
- //#endregion
1241
- //#region src/managers/request/request.manager.events.ts
1242
- /** Create event emitters and listeners for the request lifecycle: loading, progress, response, abort, deduplication, and removal. */
1243
- var getRequestManagerEvents = (emitter) => ({
1244
- emitDeduplicated: (data, isTriggeredExternally = false) => {
1245
- emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);
1246
- emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);
1247
- emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
1248
- emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1249
- },
1250
- emitLoading: (data, isTriggeredExternally = false) => {
1251
- emitter.emit(getLoadingKey(), data, isTriggeredExternally);
1252
- emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);
1253
- emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
1254
- emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1255
- },
1256
- emitRequestStart: (data, isTriggeredExternally = false) => {
1257
- emitter.emit(getRequestStartKey(), data, isTriggeredExternally);
1258
- emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);
1259
- emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1260
- },
1261
- emitResponseStart: (data, isTriggeredExternally = false) => {
1262
- emitter.emit(getResponseStartKey(), data, isTriggeredExternally);
1263
- emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);
1264
- emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1265
- },
1266
- emitUploadProgress: (data, isTriggeredExternally = false) => {
1267
- emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);
1268
- emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);
1269
- emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1270
- },
1271
- emitDownloadProgress: (data, isTriggeredExternally = false) => {
1272
- emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);
1273
- emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);
1274
- emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1275
- },
1276
- emitResponse: (data, isTriggeredExternally = false) => {
1277
- emitter.emit(getResponseKey(), data, isTriggeredExternally);
1278
- emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);
1279
- emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
1280
- },
1281
- emitAbort: (data, isTriggeredExternally = false) => {
1282
- emitter.emit(getAbortKey(), data, isTriggeredExternally);
1283
- emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);
1284
- emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);
1285
- },
1286
- emitRemove: (data, isTriggeredExternally = false) => {
1287
- emitter.emit(getRemoveKey(), data, isTriggeredExternally);
1288
- emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);
1289
- emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);
1290
- },
1291
- onDeduplicated: (callback) => {
1292
- emitter.on(getRequestDeduplicatedKey(), callback);
1293
- return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);
1294
- },
1295
- onDeduplicatedByQueue: (queryKey, callback) => {
1296
- emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);
1297
- return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);
1298
- },
1299
- onDeduplicatedByCache: (cacheKey, callback) => {
1300
- emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);
1301
- return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);
1302
- },
1303
- onDeduplicatedById: (requestId, callback) => {
1304
- emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);
1305
- return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);
1306
- },
1307
- onLoading: (callback) => {
1308
- emitter.on(getLoadingKey(), callback);
1309
- return () => emitter.removeListener(getLoadingKey(), callback);
1310
- },
1311
- onLoadingByQueue: (queryKey, callback) => {
1312
- emitter.on(getLoadingByQueryKey(queryKey), callback);
1313
- return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);
1314
- },
1315
- onLoadingByCache: (cacheKey, callback) => {
1316
- emitter.on(getLoadingByCacheKey(cacheKey), callback);
1317
- return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);
1318
- },
1319
- onLoadingById: (requestId, callback) => {
1320
- emitter.on(getLoadingByIdKey(requestId), callback);
1321
- return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);
1322
- },
1323
- onRequestStart: (callback) => {
1324
- emitter.on(getRequestStartKey(), callback);
1325
- return () => emitter.removeListener(getRequestStartKey(), callback);
1326
- },
1327
- onRequestStartByQueue: (queryKey, callback) => {
1328
- emitter.on(getRequestStarByQueryKey(queryKey), callback);
1329
- return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);
1330
- },
1331
- onRequestStartById: (requestId, callback) => {
1332
- emitter.on(getRequestStartByIdKey(requestId), callback);
1333
- return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);
1334
- },
1335
- onResponseStart: (callback) => {
1336
- emitter.on(getResponseStartKey(), callback);
1337
- return () => emitter.removeListener(getResponseStartKey(), callback);
1338
- },
1339
- onResponseStartByQueue: (queryKey, callback) => {
1340
- emitter.on(getResponseStartByQueryKey(queryKey), callback);
1341
- return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);
1342
- },
1343
- onResponseStartById: (requestId, callback) => {
1344
- emitter.on(getResponseStartByIdKey(requestId), callback);
1345
- return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);
1346
- },
1347
- onUploadProgress: (callback) => {
1348
- emitter.on(getUploadProgressKey(), callback);
1349
- return () => emitter.removeListener(getUploadProgressKey(), callback);
1350
- },
1351
- onUploadProgressByQueue: (queryKey, callback) => {
1352
- emitter.on(getUploadProgressByQueryKey(queryKey), callback);
1353
- return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);
1354
- },
1355
- onUploadProgressById: (requestId, callback) => {
1356
- emitter.on(getUploadProgressByIdKey(requestId), callback);
1357
- return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);
1358
- },
1359
- onDownloadProgress: (callback) => {
1360
- emitter.on(getDownloadProgressKey(), callback);
1361
- return () => emitter.removeListener(getDownloadProgressKey(), callback);
1362
- },
1363
- onDownloadProgressByQueue: (queryKey, callback) => {
1364
- emitter.on(getDownloadProgressByQueryKey(queryKey), callback);
1365
- return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);
1366
- },
1367
- onDownloadProgressById: (requestId, callback) => {
1368
- emitter.on(getDownloadProgressByIdKey(requestId), callback);
1369
- return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);
1370
- },
1371
- onResponse: (callback) => {
1372
- emitter.on(getResponseKey(), callback);
1373
- return () => emitter.removeListener(getResponseKey(), callback);
1374
- },
1375
- onResponseByCache: (cacheKey, callback) => {
1376
- emitter.on(getResponseByCacheKey(cacheKey), callback);
1377
- return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);
1378
- },
1379
- onResponseById: (requestId, callback) => {
1380
- emitter.on(getResponseByIdKey(requestId), callback);
1381
- return () => emitter.removeListener(getResponseByIdKey(requestId), callback);
1382
- },
1383
- onAbort: (callback) => {
1384
- emitter.on(getAbortKey(), callback);
1385
- return () => emitter.removeListener(getAbortKey(), callback);
1386
- },
1387
- onAbortByKey: (abortKey, callback) => {
1388
- emitter.on(getAbortByAbortKey(abortKey), callback);
1389
- return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);
1390
- },
1391
- onAbortById: (requestId, callback) => {
1392
- emitter.on(getAbortByIdKey(requestId), callback);
1393
- return () => emitter.removeListener(getAbortByIdKey(requestId), callback);
1394
- },
1395
- onRemove: (callback) => {
1396
- emitter.on(getRemoveKey(), callback);
1397
- return () => emitter.removeListener(getRemoveKey(), callback);
1398
- },
1399
- onRemoveByQueue: (queryKey, callback) => {
1400
- emitter.on(getRemoveByQueryKey(queryKey), callback);
1401
- return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);
1402
- },
1403
- onRemoveById: (requestId, callback) => {
1404
- emitter.on(getRemoveByIdKey(requestId), callback);
1405
- return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);
1406
- }
1407
- });
1408
- //#endregion
1409
- //#region src/managers/logger/logger.manager.ts
1410
- /**
1411
- * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.
1412
- * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module
1413
- * like Client, Request etc. Which can give you better feedback on the logging itself.
1414
- */
1415
- var LoggerManager = class {
1416
- logger;
1417
- level;
1418
- modules;
1419
- emitter = new import_events.default();
1420
- client;
1421
- constructor(options) {
1422
- this.options = options;
1423
- this.emitter?.setMaxListeners(1e3);
1424
- this.logger = this.options?.logger || logger;
1425
- this.level = this.options?.level || "warning";
1426
- this.modules = this.options?.modules;
1427
- }
1428
- setSeverity = (level) => {
1429
- this.level = level;
1430
- };
1431
- setModules = (modules) => {
1432
- this.modules = modules;
1433
- };
1434
- initialize = (client, module) => {
1435
- this.client = client;
1436
- return {
1437
- error: (data) => this.log({
1438
- ...data,
1439
- level: "error",
1440
- module
1441
- }),
1442
- warning: (data) => this.log({
1443
- ...data,
1444
- level: "warning",
1445
- module
1446
- }),
1447
- info: (data) => this.log({
1448
- ...data,
1449
- level: "info",
1450
- module
1451
- }),
1452
- debug: (data) => this.log({
1453
- ...data,
1454
- level: "debug",
1455
- module
1456
- })
1457
- };
1458
- };
1459
- log = (data) => {
1460
- if (!this.client.debug) return;
1461
- if (logLevelOrder.indexOf(this.level) <= logLevelOrder.indexOf(data.level)) return;
1462
- if (this.modules && !this.modules.includes(data.module)) return;
1463
- this.logger(data);
1464
- };
1465
- };
1466
- //#endregion
1467
- //#region src/managers/logger/logger.manager.utils.ts
1468
- var getTime = () => {
1469
- return `${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`;
1470
- };
1471
- var getModuleName = (data) => {
1472
- if (data.type === "request" || data.type === "response") return `${data.extra.request.endpoint}`;
1473
- return `[${data.module}]`;
1474
- };
1475
- var logger = (log) => {
1476
- const styles = loggerStyles[log.level];
1477
- const color = loggerColors[log.level];
1478
- const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;
1479
- const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;
1480
- const style2 = `${styles}${color}font-weight:600;`;
1481
- const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;
1482
- if (log.extra ? Object.keys(log.extra)?.length : false) {
1483
- console.groupCollapsed(message, style1, style2, style3);
1484
- console.log(log.extra);
1485
- console.groupEnd();
1486
- } else console.log(message, styles);
1487
- };
1488
- //#endregion
1489
- //#region src/managers/logger/logger.manager.constants.ts
1490
- var logLevelOrder = [
1491
- "error",
1492
- "warning",
1493
- "info",
1494
- "debug"
1495
- ];
1496
- var defaultStyles = "padding:2px 5px;";
1497
- var loggerStyles = {
1498
- error: `${defaultStyles};background:#db252520;`,
1499
- warning: `${defaultStyles};background:#e1941e20;`,
1500
- info: `${defaultStyles};background:#1e74e120;`,
1501
- debug: `${defaultStyles};background:#00000020;`
1502
- };
1503
- var loggerColors = {
1504
- error: "color:#ff3737;",
1505
- warning: "color:#ffc107;",
1506
- info: "color:#34a8ff;",
1507
- debug: "color:#cccccc;"
1508
- };
1509
- //#endregion
1510
- //#region src/adapter/adapter.utils.ts
1511
- var TimeoutError = class extends Error {
1512
- constructor() {
1513
- super("Request timeout");
1514
- this.name = "TimeoutError";
1515
- }
1516
- };
1517
- var AbortError = class extends Error {
1518
- constructor() {
1519
- super("Request aborted");
1520
- this.name = "AbortError";
1521
- }
1522
- };
1523
- var DeletedError = class extends Error {
1524
- constructor() {
1525
- super("Request deleted");
1526
- this.name = "DeletedError";
1527
- }
1528
- };
1529
- var RequestProcessingError = class extends Error {
1530
- description = void 0;
1531
- constructor(description) {
1532
- super("Request processing error");
1533
- this.description = description;
1534
- this.name = "RequestProcessingError";
1535
- }
1536
- };
1537
- var UnexpectedError = class extends Error {
1538
- description = void 0;
1539
- constructor(description) {
1540
- super("Unexpected error");
1541
- this.description = description;
1542
- this.name = "UnexpectedError";
1543
- }
1544
- };
1545
- var getErrorMessage = (errorCase) => {
1546
- if (errorCase === "timeout") return new TimeoutError();
1547
- if (errorCase === "abort") return new AbortError();
1548
- if (errorCase === "deleted") return new DeletedError();
1549
- if (errorCase === "processing") return new RequestProcessingError();
1550
- return new UnexpectedError();
1551
- };
1552
- var stringifyValue = (response) => {
1553
- try {
1554
- return JSON.stringify(response);
1555
- } catch {
1556
- return "";
1557
- }
1558
- };
1559
- var getAdapterHeaders = (request) => {
1560
- const isFormData = hasWindow() && request.payload instanceof FormData;
1561
- const isObject = typeof request.payload === "object" && request.payload !== null;
1562
- const headers = {};
1563
- if (!isFormData && isObject) headers["Content-Type"] = "application/json";
1564
- Object.assign(headers, request.headers);
1565
- return headers;
1566
- };
1567
- var getAdapterPayload = (data) => {
1568
- if (hasWindow() && data instanceof FormData) return data;
1569
- return stringifyValue(data);
1570
- };
1571
- //#endregion
1572
- //#region src/adapter/adapter.ts
1573
- var defaultMapper = (value) => value;
1574
- /**
1575
- * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,
1576
- * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class
1577
- * to integrate custom transport layers (e.g., axios, graphql, firebase).
1578
- */
1579
- var Adapter = class {
1580
- /** Fetching function */
1581
- unstable_fetcher;
1582
- /**
1583
- * ********************
1584
- * Defaults
1585
- * ********************
1586
- */
1587
- name;
1588
- defaultMethod;
1589
- defaultExtra;
1590
- systemErrorStatus;
1591
- systemErrorExtra;
1592
- defaultRequestOptions = void 0;
1593
- logger;
1594
- initialized = false;
1595
- client;
1596
- unstable_onInitializeCallback = void 0;
1597
- unstable_queryParamsMapperConfig;
1598
- unstable_headerMapperConfig;
1599
- unstable_payloadMapperConfig;
1600
- unstable_endpointMapperConfig;
1601
- /**
1602
- * Type-only carrier of the additional `createRequest` fields declared by this adapter.
1603
- * It has no runtime value - adapters read those fields from `request.requestOptions`.
1604
- */
1605
- unstable_requestOptionsType = void 0;
1606
- constructor(options) {
1607
- this.options = options;
1608
- this.name = options.name;
1609
- this.defaultMethod = options.defaultMethod;
1610
- this.defaultExtra = options.defaultExtra;
1611
- this.systemErrorStatus = options.systemErrorStatus;
1612
- this.systemErrorExtra = options.systemErrorExtra;
1613
- this.defaultRequestOptions = options.defaultRequestOptions;
1614
- }
1615
- /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */
1616
- initialize = (client) => {
1617
- this.logger = client.loggerManager.initialize(client, "Adapter");
1618
- this.initialized = true;
1619
- this.client = client;
1620
- this.unstable_onInitializeCallback?.({ client });
1621
- return this;
1622
- };
1623
- /** Register a callback invoked once the adapter is initialized with a client. */
1624
- onInitialize = (callback) => {
1625
- this.unstable_onInitializeCallback = callback;
1626
- return this;
1627
- };
1628
- /**
1629
- * ********************
1630
- * Options Setters
1631
- * ********************
1632
- */
1633
- unstable_internalErrorMapping = (error) => error;
1634
- /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
1635
- unstable_headerMapper = getAdapterHeaders;
1636
- /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
1637
- unstable_payloadMapper = getAdapterPayload;
1638
- /** Method to get the endpoint for the adapter request. */
1639
- unstable_endpointMapper = defaultMapper;
1640
- /** Method to get request data and transform them to the required format. */
1641
- unstable_queryParamsMapper = defaultMapper;
1642
- /** Get default adapter options for the request. */
1643
- unstable_getAdapterDefaults = void 0;
1644
- /** Get default request options for the request. */
1645
- unstable_getRequestDefaults = void 0;
1646
- /**
1647
- * Get formatted endpoint name of the request.
1648
- * Helpful in displaying long endpoints like in case of graphql schemas etc.
1649
- */
1650
- unstable_devtoolsEndpointGetter = (endpoint) => endpoint;
1651
- /**
1652
- * ********************
1653
- * Methods
1654
- * ********************
1655
- */
1656
- /** Set the default HTTP method used when a request does not specify one. */
1657
- setDefaultMethod = (method) => {
1658
- this.defaultMethod = method;
1659
- return this;
1660
- };
1661
- /** Set the default extra metadata attached to every request response (e.g., headers, status). */
1662
- setDefaultExtra = (extra) => {
1663
- this.defaultExtra = extra;
1664
- return this;
1665
- };
1666
- /** Set a function that formats the endpoint string for display in devtools. */
1667
- setDevtoolsEndpointGetter = (callback) => {
1668
- this.unstable_devtoolsEndpointGetter = callback;
1669
- return this;
1670
- };
1671
- /**
1672
- * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
1673
- */
1674
- setRequestDefaults = (callback) => {
1675
- this.unstable_getRequestDefaults = callback;
1676
- return this;
1677
- };
1678
- /**
1679
- * Set the adapter default options added to every sent request
1680
- */
1681
- setAdapterDefaults = (callback) => {
1682
- this.unstable_getAdapterDefaults = callback;
1683
- return this;
1684
- };
1685
- /** Set a custom mapping for internal adapter errors before they are returned in the response. */
1686
- setInternalErrorMapping = (callback) => {
1687
- this.unstable_internalErrorMapping = callback;
1688
- return this;
1689
- };
1690
- /**
1691
- * Set the custom header mapping function
1692
- */
1693
- setHeaderMapper = (headerMapper) => {
1694
- this.unstable_headerMapper = ((req) => headerMapper(req, this.unstable_headerMapperConfig));
1695
- return this;
1696
- };
1697
- /**
1698
- * Set the request payload mapping function which gets triggered before request is send
1699
- */
1700
- setPayloadMapper = (payloadMapper) => {
1701
- this.unstable_payloadMapper = ((req) => payloadMapper(req, this.unstable_payloadMapperConfig));
1702
- return this;
1703
- };
1704
- /**
1705
- * Set the endpoint mapping function which transforms the endpoint string before the request is sent
1706
- */
1707
- setEndpointMapper = (endpointMapper) => {
1708
- this.unstable_endpointMapper = ((endpoint) => endpointMapper(endpoint, this.unstable_endpointMapperConfig));
1709
- return this;
1710
- };
1711
- /**
1712
- * Set the query params mapping function which get triggered before request get sent
1713
- */
1714
- setQueryParamsMapper = (queryParamsMapper) => {
1715
- this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
1716
- return this;
1717
- };
1718
- /** Set the configuration object passed as the second argument to the query params mapper. */
1719
- setQueryParamsMapperConfig = (config) => {
1720
- this.unstable_queryParamsMapperConfig = config;
1721
- return this;
1722
- };
1723
- /** Set the configuration object passed as the second argument to the header mapper. */
1724
- setHeaderMapperConfig = (config) => {
1725
- this.unstable_headerMapperConfig = config;
1726
- return this;
1727
- };
1728
- /** Set the configuration object passed as the second argument to the endpoint mapper. */
1729
- setEndpointMapperConfig = (config) => {
1730
- this.unstable_endpointMapperConfig = config;
1731
- return this;
1732
- };
1733
- /** Set the configuration object passed as the second argument to the payload mapper. */
1734
- setPayloadMapperConfig = (config) => {
1735
- this.unstable_payloadMapperConfig = config;
1736
- return this;
1737
- };
1738
- /**
1739
- * ********************
1740
- * Fetching
1741
- * ********************
1742
- */
1743
- /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */
1744
- setFetcher(fetcher) {
1745
- this.unstable_fetcher = fetcher.bind(this);
1746
- return this;
1747
- }
1748
- /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
1749
- async fetch(request, requestId) {
1750
- let startTime;
1751
- const execute = async (resolve) => {
1752
- try {
1753
- if (!this.initialized) throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
1754
- if (!this.unstable_fetcher) throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
1755
- this.client.triggerPlugins("onAdapterFetch", {
1756
- adapter: this,
1757
- request,
1758
- requestId
1759
- });
1760
- const bindings = await getAdapterBindings({
1761
- request,
1762
- requestId,
1763
- resolve,
1764
- internalErrorMapping: this.unstable_internalErrorMapping,
1765
- onStartTime: (time) => {
1766
- startTime = time;
1767
- }
1768
- });
1769
- if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
1770
- return this.unstable_fetcher(bindings);
1771
- } catch (error) {
1772
- return getAdapterOnError({
1773
- request,
1774
- requestId,
1775
- startTime: startTime || Date.now(),
1776
- logger: this.logger,
1777
- resolve
1778
- })({
1779
- error: this.unstable_internalErrorMapping(error),
1780
- status: this.options.systemErrorStatus,
1781
- extra: this.options.systemErrorExtra
1782
- });
1783
- }
1784
- };
1785
- return new Promise((resolve) => {
1786
- execute(resolve);
1787
- });
1788
- }
1789
- };
1790
- //#endregion
1791
- //#region src/constants/http.constants.ts
1792
- var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
1793
- HttpMethods["GET"] = "GET";
1794
- HttpMethods["POST"] = "POST";
1795
- HttpMethods["PUT"] = "PUT";
1796
- HttpMethods["PATCH"] = "PATCH";
1797
- HttpMethods["DELETE"] = "DELETE";
1798
- /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */
1799
- HttpMethods["QUERY"] = "QUERY";
1800
- return HttpMethods;
1801
- }({});
1802
- /** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
1803
- var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
1804
- //#endregion
1805
- //#region src/request/request.utils.ts
1806
- var scopeKey = (key, scope) => {
1807
- return scope ? `${scope}__${key}` : key;
1808
- };
1809
- var stringifyKey = (value) => {
1810
- try {
1811
- if (typeof value === "string") return value;
1812
- if (value === void 0 || value === null) return "";
1813
- const data = JSON.stringify(value);
1814
- if (typeof data !== "string") throw new TypeError();
1815
- return data;
1816
- } catch {
1817
- return "";
1818
- }
1819
- };
1820
- var getProgressValue = ({ loaded, total }) => {
1821
- if (!loaded || !total) return 0;
1822
- return Number((loaded * 100 / total).toFixed(0));
1823
- };
1824
- var getRequestEta = (startDate, progressDate, { total, loaded }) => {
1825
- const uploadSpeed = loaded / (+progressDate - +startDate || 1);
1826
- const totalValue = Math.max(total, loaded);
1827
- const sizeLeft = totalValue - loaded;
1828
- const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;
1829
- return {
1830
- timeLeft: totalValue === loaded ? 0 : estimatedTimeValue,
1831
- sizeLeft
1832
- };
1833
- };
1834
- var getProgressData = (requestStartTime, progressDate, progressEvent) => {
1835
- const { total, loaded } = progressEvent;
1836
- if (Number.isNaN(total) || Number.isNaN(loaded)) return {
1837
- progress: 0,
1838
- timeLeft: 0,
1839
- sizeLeft: 0,
1840
- total: 0,
1841
- loaded: 0,
1842
- startTimestamp: +requestStartTime
1843
- };
1844
- const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);
1845
- return {
1846
- progress: getProgressValue(progressEvent),
1847
- timeLeft,
1848
- sizeLeft,
1849
- total,
1850
- loaded,
1851
- startTimestamp: +requestStartTime
1852
- };
1853
- };
1854
- var getSimpleKey = (request) => {
1855
- return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;
1856
- };
1857
- /**
1858
- * Cache instance for individual request that collects individual requests responses from
1859
- * the same endpoint (they may differ base on the custom key, endpoint params etc)
1860
- * @param request
1861
- * @param useInitialValues
1862
- * @returns
1863
- */
1864
- var getRequestKey = (request, useInitialValues) => {
1865
- return `${stringifyKey(request.method)}_${useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint)}_${useInitialValues ? "" : stringifyKey(request.queryParams)}`;
1866
- };
1867
- var getRequestDispatcher = (request, dispatcherType = "auto") => {
1868
- const { fetchDispatcher, submitDispatcher } = request.client;
1869
- const isSafeRead = SAFE_HTTP_METHODS.includes(request.method);
1870
- const isFetchDispatcher = dispatcherType === "auto" && isSafeRead || dispatcherType === "fetch";
1871
- return [isFetchDispatcher ? fetchDispatcher : submitDispatcher, isFetchDispatcher];
1872
- };
1873
- /**
1874
- * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,
1875
- * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.
1876
- * Failures are always delivered through a promise, so sync and async mappers fail the same way.
1877
- * @internal
1878
- * @param request request with the optional response mapper
1879
- * @param response response to be mapped
1880
- * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper
1881
- */
1882
- var runResponseMapper = (request, response) => {
1883
- const getFailedResponse = (error) => {
1884
- request.client.logger.error({
1885
- title: "Response mapper failed",
1886
- type: "system",
1887
- extra: {
1888
- error,
1889
- request,
1890
- response
1891
- }
1892
- });
1893
- return {
1894
- ...response,
1895
- data: null,
1896
- error,
1897
- success: false
1898
- };
1899
- };
1900
- try {
1901
- const mapping = request.unstable_responseMapper?.(response);
1902
- return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;
1903
- } catch (error) {
1904
- return Promise.resolve(getFailedResponse(error));
1905
- }
1906
- };
1907
- var mapResponseForSend = async (request, response) => {
1908
- const mapping = runResponseMapper(request, response);
1909
- if (mapping instanceof Promise) return await mapping;
1910
- return mapping || response;
1911
- };
1912
- /**
1913
- * Rollback is user code running in the middle of the response handling, its failure can't affect the request
1914
- */
1915
- var rollbackOptimistic = (optimistic, args) => {
1916
- const logFailure = (error) => {
1917
- args.request.client.logger.error({
1918
- title: "Optimistic rollback failed",
1919
- type: "system",
1920
- extra: {
1921
- error,
1922
- reason: args.reason,
1923
- request: args.request
1924
- }
1925
- });
1926
- };
1927
- try {
1928
- Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);
1929
- } catch (error) {
1930
- logFailure(error);
1931
- }
1932
- };
1933
- var invalidateOptimistic = (optimistic, request) => {
1934
- optimistic.invalidate?.forEach((target) => {
1935
- try {
1936
- request.client.cache.invalidate(target);
1937
- } catch (error) {
1938
- request.client.logger.error({
1939
- title: "Optimistic invalidation failed",
1940
- type: "system",
1941
- extra: {
1942
- error,
1943
- target,
1944
- request
1945
- }
1946
- });
1947
- }
1948
- });
1949
- };
1950
- var sendRequest = async (request, options) => {
1951
- const { client } = request;
1952
- const { requestManager } = client;
1953
- const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
1954
- let mutationContext;
1955
- if (request.optimistic) try {
1956
- mutationContext = await request.optimistic({
1957
- request,
1958
- client: request.client,
1959
- payload: request.payload
1960
- });
1961
- } catch (error) {
1962
- return {
1963
- data: null,
1964
- error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
1965
- status: null,
1966
- success: false,
1967
- extra: client.adapter.defaultExtra,
1968
- requestTimestamp: Date.now(),
1969
- responseTimestamp: Date.now()
1970
- };
1971
- }
1972
- return new Promise((resolve) => {
1973
- let isResolved = false;
1974
- let isDelivered = false;
1975
- let isSettled = false;
1976
- const requestId = dispatcher.add(request);
1977
- const { $hooks } = request;
1978
- const getWillBeResent = ({ response, details }) => {
1979
- if (response.success || details.isCanceled) return false;
1980
- return details.willRetry || request.offline && details.isOffline;
1981
- };
1982
- const mappings = /* @__PURE__ */ new WeakMap();
1983
- const getMapping = (values) => {
1984
- if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
1985
- return mappings.get(values);
1986
- };
1987
- const unmountSettlement = mutationContext ? requestManager.events.onResponseById(requestId, (values) => {
1988
- const optimistic = mutationContext;
1989
- const willBeResent = getWillBeResent(values);
1990
- const settle = (response) => {
1991
- if (isSettled || !response.success && willBeResent) return;
1992
- isSettled = true;
1993
- if (values.details.isCanceled) rollbackOptimistic(optimistic, {
1994
- reason: "abort",
1995
- response,
1996
- request
1997
- });
1998
- else if (response.success) invalidateOptimistic(optimistic, request);
1999
- else rollbackOptimistic(optimistic, {
2000
- reason: "error",
2001
- response,
2002
- request
2003
- });
2004
- };
2005
- const mapping = getMapping(values);
2006
- if (mapping instanceof Promise) mapping.then(settle);
2007
- else settle(mapping || values.response);
2008
- }) : void 0;
2009
- const beforeSentData = {
2010
- requestId,
2011
- request,
2012
- mutationContext
2013
- };
2014
- options?.onBeforeSent?.(beforeSentData);
2015
- $hooks.__emit("onBeforeSent", beforeSentData);
2016
- const unmountRequestStart = requestManager.events.onRequestStartById(requestId, (data) => {
2017
- const enriched = {
2018
- ...data,
2019
- mutationContext
2020
- };
2021
- options?.onRequestStart?.(enriched);
2022
- $hooks.__emit("onRequestStart", enriched);
2023
- });
2024
- const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
2025
- const enriched = {
2026
- ...data,
2027
- mutationContext
2028
- };
2029
- options?.onResponseStart?.(enriched);
2030
- $hooks.__emit("onResponseStart", enriched);
2031
- });
2032
- const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
2033
- const enriched = {
2034
- ...data,
2035
- mutationContext
2036
- };
2037
- options?.onUploadProgress?.(enriched);
2038
- $hooks.__emit("onUploadProgress", enriched);
2039
- });
2040
- const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
2041
- const enriched = {
2042
- ...data,
2043
- mutationContext
2044
- };
2045
- options?.onDownloadProgress?.(enriched);
2046
- $hooks.__emit("onDownloadProgress", enriched);
2047
- });
2048
- const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
2049
- const { response } = values;
2050
- const willBeResent = getWillBeResent(values);
2051
- isResolved = !willBeResent;
2052
- const enrichedValues = {
2053
- ...values,
2054
- mutationContext
2055
- };
2056
- const mapping = getMapping(values);
2057
- const handleResponse = (success, data) => {
2058
- if (isDelivered || !success && willBeResent) return;
2059
- isDelivered = true;
2060
- options?.onResponse?.(enrichedValues);
2061
- $hooks.__emit("onResponse", enrichedValues);
2062
- resolve(data);
2063
- umountAll();
2064
- };
2065
- if (mapping instanceof Promise) (async () => {
2066
- const responseData = await mapping;
2067
- const { success } = responseData;
2068
- handleResponse(success, responseData);
2069
- })();
2070
- else {
2071
- const data = mapping || response;
2072
- const { success } = data;
2073
- handleResponse(success, data);
2074
- }
2075
- });
2076
- const unmountRemoveQueueElement = requestManager.events.onRemoveById(requestId, (data) => {
2077
- if (!isResolved) {
2078
- isResolved = true;
2079
- isDelivered = true;
2080
- if (mutationContext && !isSettled) {
2081
- isSettled = true;
2082
- rollbackOptimistic(mutationContext, {
2083
- reason: "removed",
2084
- request
2085
- });
2086
- }
2087
- const enriched = {
2088
- ...data,
2089
- mutationContext
2090
- };
2091
- options?.onRemove?.(enriched);
2092
- $hooks.__emit("onRemove", enriched);
2093
- resolve({
2094
- data: null,
2095
- status: null,
2096
- success: false,
2097
- error: getErrorMessage("deleted"),
2098
- extra: request.client.adapter.defaultExtra,
2099
- requestTimestamp: Date.now(),
2100
- responseTimestamp: Date.now()
2101
- });
2102
- umountAll();
2103
- }
2104
- });
2105
- function umountAll() {
2106
- unmountSettlement?.();
2107
- unmountRequestStart();
2108
- unmountResponseStart();
2109
- unmountUpload();
2110
- unmountDownload();
2111
- unmountResponse();
2112
- unmountRemoveQueueElement();
2113
- }
2114
- });
1588
+ const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
1589
+ const enriched = {
1590
+ ...data,
1591
+ mutationContext
1592
+ };
1593
+ runUserCode(() => options?.onUploadProgress?.(enriched));
1594
+ runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
1595
+ });
1596
+ const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
1597
+ const enriched = {
1598
+ ...data,
1599
+ mutationContext
1600
+ };
1601
+ runUserCode(() => options?.onDownloadProgress?.(enriched));
1602
+ runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
1603
+ });
1604
+ const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
1605
+ const { response } = values;
1606
+ const willBeResent = getWillBeResent(values);
1607
+ isResolved = !willBeResent;
1608
+ const enrichedValues = {
1609
+ ...values,
1610
+ mutationContext
1611
+ };
1612
+ const mapping = getMapping(values);
1613
+ const handleResponse = (success, data) => {
1614
+ if (isDelivered || !success && willBeResent) return;
1615
+ isDelivered = true;
1616
+ runUserCode(() => options?.onResponse?.(enrichedValues));
1617
+ runUserCode(() => $hooks.__emit("onResponse", enrichedValues));
1618
+ resolve(data);
1619
+ umountAll();
1620
+ };
1621
+ if (mapping instanceof Promise) (async () => {
1622
+ const responseData = await mapping;
1623
+ const { success } = responseData;
1624
+ handleResponse(success, responseData);
1625
+ })();
1626
+ else {
1627
+ const data = mapping || response;
1628
+ const { success } = data;
1629
+ handleResponse(success, data);
1630
+ }
1631
+ });
1632
+ const unmountRemoveQueueElement = requestManager.events.onRemoveById(requestId, (data) => {
1633
+ if (!isResolved) {
1634
+ isResolved = true;
1635
+ isDelivered = true;
1636
+ if (mutationContext && !isSettled) {
1637
+ isSettled = true;
1638
+ rollbackOptimistic(mutationContext, {
1639
+ reason: "removed",
1640
+ request
1641
+ });
1642
+ }
1643
+ const enriched = {
1644
+ ...data,
1645
+ mutationContext
1646
+ };
1647
+ runUserCode(() => options?.onRemove?.(enriched));
1648
+ runUserCode(() => $hooks.__emit("onRemove", enriched));
1649
+ resolve({
1650
+ data: null,
1651
+ status: null,
1652
+ success: false,
1653
+ error: getErrorMessage("deleted"),
1654
+ extra: request.client.adapter.defaultExtra,
1655
+ requestTimestamp: Date.now(),
1656
+ responseTimestamp: Date.now()
1657
+ });
1658
+ umountAll();
1659
+ }
1660
+ });
1661
+ function umountAll() {
1662
+ unmountSettlement?.();
1663
+ unmountRequestStart();
1664
+ unmountResponseStart();
1665
+ unmountUpload();
1666
+ unmountDownload();
1667
+ unmountResponse();
1668
+ unmountRemoveQueueElement();
1669
+ }
1670
+ });
2115
1671
  };
2116
1672
  //#endregion
2117
1673
  //#region src/request/request.ts
@@ -2241,7 +1797,7 @@ var Request = class Request {
2241
1797
  setParams = (params) => {
2242
1798
  return this.clone({ params });
2243
1799
  };
2244
- /** Set the request body payload. */
1800
+ /** Set the request body payload. Passing `null` removes the payload set before. */
2245
1801
  setPayload = (payload) => {
2246
1802
  return this.clone({ payload });
2247
1803
  };
@@ -2316,18 +1872,24 @@ var Request = class Request {
2316
1872
  };
2317
1873
  /** Override the abort key used to cancel this request. */
2318
1874
  setAbortKey = (abortKey) => {
2319
- this.updatedAbortKey = true;
2320
- return this.clone({ abortKey });
1875
+ return this.clone({
1876
+ abortKey,
1877
+ updatedAbortKey: true
1878
+ });
2321
1879
  };
2322
1880
  /** Override the cache key used to store/retrieve the response. */
2323
1881
  setCacheKey = (cacheKey) => {
2324
- this.updatedCacheKey = true;
2325
- return this.clone({ cacheKey });
1882
+ return this.clone({
1883
+ cacheKey,
1884
+ updatedCacheKey: true
1885
+ });
2326
1886
  };
2327
1887
  /** Override the query key that identifies this request in the dispatcher queue. */
2328
1888
  setQueryKey = (queryKey) => {
2329
- this.updatedQueryKey = true;
2330
- return this.clone({ queryKey });
1889
+ return this.clone({
1890
+ queryKey,
1891
+ updatedQueryKey: true
1892
+ });
2331
1893
  };
2332
1894
  /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
2333
1895
  setDeduplicate = (deduplicate) => {
@@ -2401,11 +1963,14 @@ var Request = class Request {
2401
1963
  };
2402
1964
  paramsMapper = (params) => {
2403
1965
  const { endpoint } = this.requestOptions;
2404
- let stringEndpoint = String(endpoint);
2405
- if (params) Object.entries(params).forEach(([key, value]) => {
2406
- stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, "g"), String(value));
2407
- });
2408
- return stringEndpoint;
1966
+ const stringEndpoint = String(endpoint);
1967
+ const names = params ? Object.keys(params) : [];
1968
+ if (!params || names.length === 0) return stringEndpoint;
1969
+ const [start, ...segments] = stringEndpoint.split(":");
1970
+ return [start, ...segments.map((segment) => {
1971
+ const name = names.reduce((longest, current) => segment.startsWith(current) && current.length > longest.length ? current : longest, "");
1972
+ return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;
1973
+ })].join("");
2409
1974
  };
2410
1975
  /** Serialize the request configuration into a plain JSON object for persistence or transfer. */
2411
1976
  toJSON() {
@@ -2450,12 +2015,15 @@ var Request = class Request {
2450
2015
  ...this.toJSON(),
2451
2016
  ...configuration,
2452
2017
  options: configuration?.options || this.options,
2453
- abortKey: this.updatedAbortKey ? configuration?.abortKey || this.abortKey : void 0,
2454
- cacheKey: this.updatedCacheKey ? configuration?.cacheKey || this.cacheKey : void 0,
2455
- queryKey: this.updatedQueryKey ? configuration?.queryKey || this.queryKey : void 0,
2018
+ abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : void 0),
2019
+ cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : void 0),
2020
+ queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : void 0),
2021
+ updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,
2022
+ updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,
2023
+ updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,
2456
2024
  endpoint: this.paramsMapper(configuration?.params || this.params),
2457
2025
  queryParams: configuration?.queryParams || this.queryParams,
2458
- payload: configuration?.payload || this.payload,
2026
+ payload: configuration?.payload === null ? void 0 : configuration?.payload ?? this.payload,
2459
2027
  params: configuration?.params || this.params
2460
2028
  };
2461
2029
  const cloned = new Request(this.client, this.requestOptions, initialRequestConfiguration);
@@ -2546,8 +2114,7 @@ var Request = class Request {
2546
2114
  requestManager.addAbortController(scopedAbortKey, requestId);
2547
2115
  const response = await adapter.fetch(request, requestId);
2548
2116
  requestManager.removeAbortController(scopedAbortKey, requestId);
2549
- if (request.unstable_responseMapper) return request.unstable_responseMapper(response);
2550
- return response;
2117
+ return mapResponseForSend(request, response);
2551
2118
  };
2552
2119
  /**
2553
2120
  * Method used to perform requests with usage of cache and queues
@@ -2586,6 +2153,8 @@ var Request = class Request {
2586
2153
  };
2587
2154
  //#endregion
2588
2155
  //#region src/cache/cache.ts
2156
+ /** Timers can't wait longer than 2^31-1 ms (~24.8 days) - a longer delay overflows and fires immediately */
2157
+ var MAX_TIMER_DELAY = 2147483647;
2589
2158
  /**
2590
2159
  * Cache class handles the data exchange with the dispatchers.
2591
2160
  *
@@ -2663,7 +2232,7 @@ var Cache = class {
2663
2232
  }
2664
2233
  });
2665
2234
  this.storage.set(storageKey, newCacheData);
2666
- this.lazyStorage?.set(storageKey, newCacheData);
2235
+ this.runLazyStorage("set", storageKey, (lazyStorage) => lazyStorage.set(storageKey, newCacheData));
2667
2236
  this.client.triggerPlugins("onCacheItemChange", {
2668
2237
  cache: this,
2669
2238
  cacheKey,
@@ -2720,7 +2289,9 @@ var Cache = class {
2720
2289
  */
2721
2290
  get = (cacheKey) => {
2722
2291
  this.getLazyResource(cacheKey);
2723
- return this.storage.get(cacheKey);
2292
+ const cachedData = this.storage.get(cacheKey);
2293
+ if (cachedData && cachedData.version !== this.version) return;
2294
+ return cachedData;
2724
2295
  };
2725
2296
  /**
2726
2297
  * Get sync storage keys, lazyStorage keys will not be included
@@ -2739,13 +2310,16 @@ var Cache = class {
2739
2310
  type: "system",
2740
2311
  extra: { cacheKey }
2741
2312
  });
2313
+ clearTimeout(this.garbageCollectors.get(cacheKey));
2314
+ this.garbageCollectors.delete(cacheKey);
2315
+ const listenersKey = this.storage.get(cacheKey)?.cacheKey ?? cacheKey;
2742
2316
  this.storage.delete(cacheKey);
2743
- this.lazyStorage?.delete(cacheKey);
2317
+ this.runLazyStorage("delete", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));
2744
2318
  this.client.triggerPlugins("onCacheItemDelete", {
2745
2319
  cache: this,
2746
2320
  cacheKey
2747
2321
  });
2748
- this.events.emitDelete(cacheKey);
2322
+ this.events.emitDelete(cacheKey, false, listenersKey);
2749
2323
  };
2750
2324
  /**
2751
2325
  * Invalidate cache by cacheKey or partial matching with RegExp
@@ -2771,13 +2345,17 @@ var Cache = class {
2771
2345
  cache: this,
2772
2346
  cacheKey: notifyCacheKey
2773
2347
  });
2774
- this.events.emitInvalidation(notifyCacheKey);
2348
+ const listenersKey = notifyCacheKey === invalidateStorageKey ? value?.cacheKey ?? notifyCacheKey : notifyCacheKey;
2349
+ this.events.emitInvalidation(invalidateStorageKey, false, listenersKey);
2775
2350
  };
2776
2351
  if (key instanceof Request) handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);
2777
2352
  else if (typeof key === "string") handleInvalidation(key);
2778
- else if (keys.length > 0) keys.forEach((entityKey) => {
2779
- if (key.test(entityKey)) handleInvalidation(entityKey);
2780
- });
2353
+ else if (keys.length > 0) {
2354
+ const matcher = new RegExp(key.source, key.flags.replaceAll(/[gy]/g, ""));
2355
+ keys.forEach((entityKey) => {
2356
+ if (matcher.test(entityKey)) handleInvalidation(entityKey);
2357
+ });
2358
+ }
2781
2359
  };
2782
2360
  if (Array.isArray(cacheKeys)) cacheKeys.forEach(onInvalidate.bind(this));
2783
2361
  else onInvalidate.bind(this)(cacheKeys);
@@ -2787,26 +2365,31 @@ var Cache = class {
2787
2365
  * @param cacheKey
2788
2366
  */
2789
2367
  getLazyResource = async (cacheKey) => {
2790
- const data = await this.lazyStorage?.get(cacheKey);
2368
+ const data = await this.runLazyStorage("get", cacheKey, (lazyStorage) => lazyStorage.get(cacheKey));
2791
2369
  const syncData = this.storage.get(cacheKey);
2792
- if (this.lazyStorage && data) {
2370
+ if (data) {
2793
2371
  const now = Date.now();
2794
2372
  const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;
2795
- const isStaleData = data.staleTime <= now - data.responseTimestamp;
2373
+ const isStaleData = data.staleTime === null ? false : data.staleTime <= now - data.responseTimestamp;
2796
2374
  const isValidLazyData = data.version === this.version;
2797
- if (!isValidLazyData) this.lazyStorage?.delete(cacheKey);
2798
- if (isNewestData && !isStaleData && isValidLazyData) {
2375
+ const isExpiredData = this.client.appManager.isOnline && this.getTimeLeft(data, now) < 0;
2376
+ if (!isValidLazyData || isExpiredData) this.runLazyStorage("delete", cacheKey, (lazyStorage) => lazyStorage.delete(cacheKey));
2377
+ if (isNewestData && !isStaleData && isValidLazyData && !isExpiredData) {
2799
2378
  this.storage.set(cacheKey, data);
2379
+ this.scheduleGarbageCollector(cacheKey);
2800
2380
  this.events.emitCacheData({
2801
2381
  ...data,
2802
- cacheKey,
2382
+ cacheKey: typeof data.cacheKey === "string" ? data.cacheKey : cacheKey,
2803
2383
  cached: true
2804
2384
  });
2805
2385
  return data;
2806
2386
  }
2807
2387
  }
2808
2388
  const isValidData = syncData?.version === this.version;
2809
- if (syncData && !isValidData) this.delete(cacheKey);
2389
+ if (syncData && !isValidData) {
2390
+ this.delete(cacheKey);
2391
+ return;
2392
+ }
2810
2393
  return syncData;
2811
2394
  };
2812
2395
  /**
@@ -2832,29 +2415,34 @@ var Cache = class {
2832
2415
  scheduleGarbageCollector = (cacheKey) => {
2833
2416
  const cacheData = this.storage.get(cacheKey);
2834
2417
  clearTimeout(this.garbageCollectors.get(cacheKey));
2418
+ this.garbageCollectors.delete(cacheKey);
2835
2419
  if (cacheData) {
2836
- const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - Date.now();
2420
+ const timeLeft = this.getTimeLeft(cacheData, Date.now());
2837
2421
  if (cacheData.cacheTime === null) this.logger.debug({
2838
2422
  title: "Cache time is null",
2839
2423
  type: "system",
2840
2424
  extra: { cacheKey }
2841
2425
  });
2842
- else if (cacheData.cacheTime !== null && JSON.stringify(cacheData.cacheTime) === "null" || cacheData.cacheTime === Infinity) this.logger.debug({
2426
+ else if (timeLeft === Infinity) this.logger.debug({
2843
2427
  title: "Cache time is Infinite",
2844
2428
  type: "system",
2845
2429
  extra: { cacheKey }
2846
2430
  });
2847
- else if (timeLeft >= 0) this.garbageCollectors.set(cacheKey, setTimeout(() => {
2848
- if (this.client.appManager.isOnline) {
2849
- this.logger.info({
2850
- title: "Garbage collecting cache data",
2851
- type: "system",
2852
- extra: { cacheKey }
2853
- });
2854
- this.delete(cacheKey);
2855
- }
2856
- }, timeLeft));
2857
- else if (this.client.appManager.isOnline) {
2431
+ else if (timeLeft >= 0) {
2432
+ const delay = Math.min(timeLeft, MAX_TIMER_DELAY);
2433
+ this.garbageCollectors.set(cacheKey, setTimeout(() => {
2434
+ this.garbageCollectors.delete(cacheKey);
2435
+ if (delay < timeLeft) this.scheduleGarbageCollector(cacheKey);
2436
+ else if (this.client.appManager.isOnline) {
2437
+ this.logger.info({
2438
+ title: "Garbage collecting cache data",
2439
+ type: "system",
2440
+ extra: { cacheKey }
2441
+ });
2442
+ this.delete(cacheKey);
2443
+ }
2444
+ }, delay));
2445
+ } else if (this.client.appManager.isOnline) {
2858
2446
  this.logger.info({
2859
2447
  title: "Garbage collecting cache data",
2860
2448
  type: "system",
@@ -2865,11 +2453,48 @@ var Cache = class {
2865
2453
  }
2866
2454
  };
2867
2455
  /**
2868
- * Clear cache storages
2456
+ * Time left to the garbage collection of the cache element. Returns Infinity for elements stored forever
2457
+ * and a negative value for outdated elements or elements without valid times.
2458
+ */
2459
+ getTimeLeft = (cacheData, now) => {
2460
+ const { cacheTime, responseTimestamp } = cacheData;
2461
+ if (cacheTime === null || typeof cacheTime === "number" && !Number.isFinite(cacheTime)) return Infinity;
2462
+ const timeLeft = cacheTime + responseTimestamp - now;
2463
+ return Number.isNaN(timeLeft) ? -1 : timeLeft;
2464
+ };
2465
+ /**
2466
+ * Lazy storage is an external resource (IndexedDB, AsyncStorage etc.) - its failures are logged, they must not
2467
+ * break the cache flow nor end up as unhandled promise rejections.
2468
+ */
2469
+ runLazyStorage = async (action, cacheKey, callback) => {
2470
+ if (!this.lazyStorage) return;
2471
+ try {
2472
+ return await callback(this.lazyStorage);
2473
+ } catch (error) {
2474
+ this.logger?.error({
2475
+ title: `Lazy storage "${action}" failed`,
2476
+ type: "system",
2477
+ extra: {
2478
+ cacheKey,
2479
+ error
2480
+ }
2481
+ });
2482
+ return;
2483
+ }
2484
+ };
2485
+ /**
2486
+ * Clear cache storages - the memory and the lazy one. Data left in the lazy storage would be loaded back
2487
+ * by the next read, for example for the next user after a logout.
2869
2488
  */
2870
2489
  clear = async () => {
2871
2490
  this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));
2491
+ this.garbageCollectors.clear();
2872
2492
  this.storage.clear();
2493
+ await this.runLazyStorage("clear", "*", async (lazyStorage) => {
2494
+ const keys = [...await lazyStorage.keys()];
2495
+ const failed = (await Promise.allSettled(keys.map((key) => lazyStorage.delete(key)))).find((result) => result.status === "rejected");
2496
+ if (failed) throw failed.reason;
2497
+ });
2873
2498
  };
2874
2499
  };
2875
2500
  //#endregion
@@ -2877,7 +2502,7 @@ var Cache = class {
2877
2502
  var getCacheData = (previousResponse, response) => {
2878
2503
  const { data, success } = response;
2879
2504
  const previousData = !success && previousResponse ? previousResponse.data : null;
2880
- const computedData = data || previousData;
2505
+ const computedData = data ?? previousData;
2881
2506
  return {
2882
2507
  ...response,
2883
2508
  data: computedData
@@ -2914,17 +2539,19 @@ var isPlainArray = (value) => {
2914
2539
  return Array.isArray(value) && Object.keys(value).length === value.length;
2915
2540
  };
2916
2541
  /**
2917
- * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.
2918
- * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.
2919
- * Only plain objects and arrays are traversed, other values are compared with `Object.is`.
2920
- * @param prev previous value
2921
- * @param next incoming value
2922
- * @returns `next` sharing unchanged references with `prev`
2542
+ * Structures nested deeper than this are not compared - it keeps extremely deep data from overflowing the call stack.
2923
2543
  */
2924
- var replaceEqualDeep = (prev, next) => {
2544
+ var STRUCTURAL_SHARING_MAX_DEPTH = 500;
2545
+ /**
2546
+ * @param ancestors containers of `next` that are being compared right now - their number is the current depth
2547
+ * and meeting one of them again means a cycle
2548
+ */
2549
+ var shareEqualParts = (prev, next, ancestors) => {
2925
2550
  if (Object.is(prev, next)) return prev;
2926
2551
  const isArray = isPlainArray(prev) && isPlainArray(next);
2927
2552
  if (!isArray && !(isPlainObject(prev) && isPlainObject(next))) return next;
2553
+ if (ancestors.size > STRUCTURAL_SHARING_MAX_DEPTH || ancestors.has(next)) return next;
2554
+ ancestors.add(next);
2928
2555
  const prevItems = prev;
2929
2556
  const nextItems = next;
2930
2557
  const prevKeys = Object.keys(prevItems);
@@ -2934,12 +2561,25 @@ var replaceEqualDeep = (prev, next) => {
2934
2561
  nextKeys.forEach((key) => {
2935
2562
  const prevValue = prevItems[key];
2936
2563
  const nextValue = nextItems[key];
2937
- const value = replaceEqualDeep(prevValue, nextValue);
2564
+ const value = shareEqualParts(prevValue, nextValue, ancestors);
2938
2565
  copy[key] = value;
2939
- if (value === prevValue && (value !== void 0 || Object.prototype.hasOwnProperty.call(prevItems, key))) equalItems += 1;
2566
+ if (Object.is(value, prevValue) && (value !== void 0 || Object.prototype.hasOwnProperty.call(prevItems, key))) equalItems += 1;
2940
2567
  });
2568
+ ancestors.delete(next);
2941
2569
  return prevKeys.length === nextKeys.length && equalItems === prevKeys.length ? prev : copy;
2942
2570
  };
2571
+ /**
2572
+ * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.
2573
+ * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.
2574
+ * Only plain objects and arrays are traversed, other values are compared with `Object.is`.
2575
+ * Circular references and extremely deep structures are not traversed - such parts are taken from `next` as they are.
2576
+ * @param prev previous value
2577
+ * @param next incoming value
2578
+ * @returns `next` sharing unchanged references with `prev`
2579
+ */
2580
+ var replaceEqualDeep = (prev, next) => {
2581
+ return shareEqualParts(prev, next, /* @__PURE__ */ new Set());
2582
+ };
2943
2583
  //#endregion
2944
2584
  //#region src/cache/cache.events.ts
2945
2585
  /** Create the cache event emitters and listeners for data changes, invalidation, and deletion. */
@@ -2948,13 +2588,13 @@ var getCacheEvents = (emitter) => ({
2948
2588
  emitter.emit(getCacheKey(), data, isTriggeredExternally);
2949
2589
  emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);
2950
2590
  },
2951
- emitInvalidation: (cacheKey, isTriggeredExternally = false) => {
2591
+ emitInvalidation: (cacheKey, isTriggeredExternally = false, listenersKey = cacheKey) => {
2952
2592
  emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);
2953
- emitter.emit(getInvalidateByKey(cacheKey), isTriggeredExternally);
2593
+ emitter.emit(getInvalidateByKey(listenersKey), cacheKey, isTriggeredExternally);
2954
2594
  },
2955
- emitDelete: (cacheKey, isTriggeredExternally = false) => {
2595
+ emitDelete: (cacheKey, isTriggeredExternally = false, listenersKey = cacheKey) => {
2956
2596
  emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);
2957
- emitter.emit(getDeleteByKey(cacheKey), isTriggeredExternally);
2597
+ emitter.emit(getDeleteByKey(listenersKey), cacheKey, isTriggeredExternally);
2958
2598
  },
2959
2599
  onData: (callback) => {
2960
2600
  emitter.on(getCacheKey(), callback);
@@ -3055,7 +2695,14 @@ var Dispatcher = class {
3055
2695
  storage = /* @__PURE__ */ new Map();
3056
2696
  requestCount = /* @__PURE__ */ new Map();
3057
2697
  runningRequests = /* @__PURE__ */ new Map();
2698
+ /** Failed requests waiting for their next attempt, by requestId */
3058
2699
  retryTimers = /* @__PURE__ */ new Map();
2700
+ /** Requests which got their response and are still in the queue while their listeners run */
2701
+ answeredRequests = /* @__PURE__ */ new Set();
2702
+ /** Order in which the requests were sent - responses can come back in another one */
2703
+ sentCount = 0;
2704
+ /** Cache element (by its storage key) to the order number of the request whose data it holds */
2705
+ cachedOrder = /* @__PURE__ */ new Map();
3059
2706
  logger;
3060
2707
  client;
3061
2708
  constructor(options) {
@@ -3199,6 +2846,13 @@ var Dispatcher = class {
3199
2846
  * Clear requests from queue cache
3200
2847
  */
3201
2848
  clearQueue = (queryKey) => {
2849
+ return this.removeQueueItems(queryKey, this.getRunningRequests(queryKey).map((running) => running.requestId));
2850
+ };
2851
+ /**
2852
+ * Empty the queue. Requests listed in `answeredIds` are running or were just canceled, so they still report
2853
+ * their own response. All the others would never be heard of again - those are reported as removed.
2854
+ */
2855
+ removeQueueItems = (queryKey, answeredIds) => {
3202
2856
  const queue = this.getQueue(queryKey);
3203
2857
  const newQueue = {
3204
2858
  queryKey,
@@ -3211,10 +2865,28 @@ var Dispatcher = class {
3211
2865
  queue: newQueue
3212
2866
  });
3213
2867
  this.events.emitQueueChanged(newQueue);
2868
+ this.emitRemovedItems(queue.requests, answeredIds);
3214
2869
  this.events.emitDrained(newQueue);
3215
- this.removeWaitingRetries(queue);
3216
2870
  return newQueue;
3217
2871
  };
2872
+ emitRemovedItems = (items, answeredIds) => {
2873
+ items.forEach((item) => {
2874
+ this.cancelRetry(item.requestId);
2875
+ if (!answeredIds.includes(item.requestId)) this.client.requestManager.events.emitRemove({
2876
+ requestId: item.requestId,
2877
+ request: item.request,
2878
+ resolved: item.resolved
2879
+ });
2880
+ });
2881
+ };
2882
+ /**
2883
+ * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,
2884
+ * not just answered and - for the requests kept for later with the `offline` option - when there is a connection
2885
+ */
2886
+ canPerformRequest = (item, runningIds) => {
2887
+ const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;
2888
+ return !item.stopped && !isWaitingForNetwork && !this.retryTimers.has(item.requestId) && !this.answeredRequests.has(item.requestId) && !runningIds.has(item.requestId);
2889
+ };
3218
2890
  /**
3219
2891
  * Method used to flush the queue requests
3220
2892
  */
@@ -3227,7 +2899,7 @@ var Dispatcher = class {
3227
2899
  const isConcurrent = !queueItem?.request.queued;
3228
2900
  const isInactive = runningRequests.length === 0;
3229
2901
  const isEmpty = !queueItem;
3230
- if (isStopped || isOffline || isEmpty) this.logger.debug({
2902
+ if (isStopped || isEmpty) this.logger.debug({
3231
2903
  title: "Skipping queue trigger",
3232
2904
  type: "system",
3233
2905
  extra: {
@@ -3236,10 +2908,15 @@ var Dispatcher = class {
3236
2908
  isEmpty
3237
2909
  }
3238
2910
  });
3239
- else if (isConcurrent) queue.requests.forEach((element) => {
3240
- if (!this.hasRunningRequest(queryKey, element.requestId)) this.performRequest(element);
3241
- });
3242
- else if (isInactive) {
2911
+ else if (isConcurrent) {
2912
+ const runningIds = new Set(runningRequests.map((running) => running.requestId));
2913
+ queue.requests.forEach((element) => {
2914
+ if (this.canPerformRequest(element, runningIds)) {
2915
+ runningIds.add(element.requestId);
2916
+ this.performRequest(element);
2917
+ }
2918
+ });
2919
+ } else if (isInactive && this.canPerformRequest(queueItem, /* @__PURE__ */ new Set())) {
3243
2920
  await this.performRequest(queueItem);
3244
2921
  this.flushQueue(queryKey);
3245
2922
  }
@@ -3256,12 +2933,16 @@ var Dispatcher = class {
3256
2933
  */
3257
2934
  clear = () => {
3258
2935
  const keys = this.getQueuesKeys();
3259
- const queues = keys.map((queryKey) => this.getQueue(queryKey));
2936
+ const removed = keys.map((queryKey) => ({
2937
+ items: this.getQueue(queryKey).requests,
2938
+ answeredIds: this.getRunningRequests(queryKey).map((running) => running.requestId)
2939
+ }));
3260
2940
  keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));
3261
2941
  [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));
3262
2942
  this.runningRequests.clear();
2943
+ this.cachedOrder.clear();
3263
2944
  this.storage.clear();
3264
- queues.forEach((queue) => this.removeWaitingRetries(queue));
2945
+ removed.forEach(({ items, answeredIds }) => this.emitRemovedItems(items, answeredIds));
3265
2946
  this.client.triggerPlugins("onDispatcherCleared", { dispatcher: this });
3266
2947
  };
3267
2948
  /**
@@ -3274,19 +2955,6 @@ var Dispatcher = class {
3274
2955
  return this.retryTimers.delete(requestId);
3275
2956
  };
3276
2957
  /**
3277
- * Clearing does not announce removed items. Requests waiting for a retry have no attempt left to end with,
3278
- * so without this event their listeners would never be notified.
3279
- */
3280
- removeWaitingRetries = (queue) => {
3281
- queue.requests.forEach(({ requestId, request, resolved }) => {
3282
- if (this.cancelRetry(requestId)) this.client.requestManager.events.emitRemove({
3283
- requestId,
3284
- request,
3285
- resolved
3286
- });
3287
- });
3288
- };
3289
- /**
3290
2958
  * Start particular request
3291
2959
  */
3292
2960
  startRequest = (queryKey, requestId) => {
@@ -3335,7 +3003,8 @@ var Dispatcher = class {
3335
3003
  */
3336
3004
  setRunningRequests = (queryKey, runningRequests) => {
3337
3005
  const previousRequests = this.getRunningRequests(queryKey);
3338
- this.runningRequests.set(queryKey, runningRequests);
3006
+ if (runningRequests.length > 0) this.runningRequests.set(queryKey, runningRequests);
3007
+ else this.runningRequests.delete(queryKey);
3339
3008
  if (previousRequests.length !== runningRequests.length || previousRequests.some((req, i) => req !== runningRequests[i])) this.events.emitRunningRequestsChanged({
3340
3009
  queryKey,
3341
3010
  runningRequests
@@ -3451,12 +3120,14 @@ var Dispatcher = class {
3451
3120
  this.addQueueItem(queryKey, storageItem);
3452
3121
  this.flushQueue(queryKey);
3453
3122
  return requestId;
3454
- case DispatcherMode.PREVIOUS_CANCELED:
3123
+ case DispatcherMode.PREVIOUS_CANCELED: {
3124
+ const canceledIds = this.getRunningRequests(queryKey).map((running) => running.requestId);
3455
3125
  this.cancelRunningRequests(queryKey);
3456
- this.clearQueue(queryKey);
3126
+ this.removeQueueItems(queryKey, canceledIds);
3457
3127
  this.addQueueItem(queryKey, storageItem);
3458
3128
  this.flushQueue(queryKey);
3459
3129
  return requestId;
3130
+ }
3460
3131
  case DispatcherMode.DEDUPLICATED:
3461
3132
  this.client.requestManager.events.emitDeduplicated({
3462
3133
  request: latestRequest.request,
@@ -3486,9 +3157,9 @@ var Dispatcher = class {
3486
3157
  const queue = this.getQueue(queryKey);
3487
3158
  const queueItem = queue.requests.find((req) => req.requestId === requestId);
3488
3159
  if (!queueItem) return;
3489
- this.cancelRetry(requestId);
3490
3160
  queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
3491
3161
  this.storage.set(queryKey, queue);
3162
+ this.cancelRetry(requestId);
3492
3163
  if (this.hasRunningRequest(queryKey, requestId)) {
3493
3164
  this.deleteRunningRequest(queryKey, requestId);
3494
3165
  this.client.requestManager.abortByRequestId(abortKey, requestId);
@@ -3514,6 +3185,36 @@ var Dispatcher = class {
3514
3185
  return queue;
3515
3186
  };
3516
3187
  /**
3188
+ * Save the number of used attempts on the queued request
3189
+ */
3190
+ setQueueItemRetries = (queryKey, requestId, retries) => {
3191
+ const queue = this.getQueue(queryKey);
3192
+ const queueItem = queue.requests.find((item) => item.requestId === requestId);
3193
+ if (queueItem) {
3194
+ queueItem.retries = retries;
3195
+ this.storage.set(queryKey, queue);
3196
+ }
3197
+ };
3198
+ /**
3199
+ * The `retryOnError` callback belongs to the user - when it throws, the request is not retried
3200
+ */
3201
+ getShouldRetryOnError = (request, response) => {
3202
+ if (!request.retryOnError) return true;
3203
+ try {
3204
+ return !!request.retryOnError(response);
3205
+ } catch (error) {
3206
+ this.logger.error({
3207
+ title: "The retryOnError callback failed",
3208
+ type: "system",
3209
+ extra: {
3210
+ error,
3211
+ request
3212
+ }
3213
+ });
3214
+ return false;
3215
+ }
3216
+ };
3217
+ /**
3517
3218
  * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
3518
3219
  * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
3519
3220
  */
@@ -3545,6 +3246,8 @@ var Dispatcher = class {
3545
3246
  }
3546
3247
  });
3547
3248
  const runningRequest = this.addRunningRequest(queryKey, requestId, request);
3249
+ this.sentCount += 1;
3250
+ const sentOrder = this.sentCount;
3548
3251
  requestManager.events.emitLoading({
3549
3252
  request,
3550
3253
  requestId,
@@ -3561,447 +3264,1055 @@ var Dispatcher = class {
3561
3264
  const isCancelMessage = getErrorMessage("abort").message === response.error?.message;
3562
3265
  const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;
3563
3266
  this.deleteRunningRequest(queryKey, requestId);
3564
- const shouldRetryOnError = response.success || !canRetry || !request.retryOnError || request.retryOnError(response);
3565
- const willRetry = !response.success && canRetry && shouldRetryOnError && !isCanceled && !isOfflineResponseStatus;
3566
- const requestDetails = {
3567
- isCanceled,
3568
- isOffline: isOfflineResponseStatus,
3569
- retries: storageItem.retries,
3570
- willRetry,
3571
- addedTimestamp: storageItem.timestamp,
3572
- triggerTimestamp: runningRequest.timestamp,
3573
- requestTimestamp: response.requestTimestamp,
3574
- responseTimestamp: response.responseTimestamp
3575
- };
3576
- requestManager.events.emitResponse({
3577
- request,
3578
- requestId,
3579
- response,
3580
- details: requestDetails
3581
- });
3582
- requestManager.events.emitLoading({
3583
- request,
3584
- requestId,
3585
- loading: false,
3586
- isRetry: !!storageItem.retries,
3587
- isOffline
3588
- });
3589
- cache.set(request, {
3590
- ...response,
3591
- ...requestDetails
3592
- });
3593
- this.logger.debug({
3594
- title: "Dispatcher processing response",
3595
- type: "system",
3596
- extra: {
3597
- requestId,
3267
+ this.answeredRequests.add(requestId);
3268
+ try {
3269
+ const isQueued = !!this.getRequest(queryKey, requestId);
3270
+ const willRetry = !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus && this.getShouldRetryOnError(request, response);
3271
+ const requestDetails = {
3272
+ isCanceled,
3273
+ isOffline: isOfflineResponseStatus,
3274
+ retries: storageItem.retries,
3275
+ willRetry,
3276
+ addedTimestamp: storageItem.timestamp,
3277
+ triggerTimestamp: runningRequest.timestamp,
3278
+ requestTimestamp: response.requestTimestamp,
3279
+ responseTimestamp: response.responseTimestamp
3280
+ };
3281
+ const notify = (callback) => {
3282
+ try {
3283
+ callback();
3284
+ } catch (error) {
3285
+ this.logger.error({
3286
+ title: "Response listener failed",
3287
+ type: "system",
3288
+ extra: {
3289
+ error,
3290
+ request,
3291
+ requestId
3292
+ }
3293
+ });
3294
+ throwOutsideLifecycle(error);
3295
+ }
3296
+ };
3297
+ notify(() => requestManager.events.emitResponse({
3598
3298
  request,
3299
+ requestId,
3599
3300
  response,
3600
3301
  details: requestDetails
3302
+ }));
3303
+ notify(() => requestManager.events.emitLoading({
3304
+ request,
3305
+ requestId,
3306
+ loading: false,
3307
+ isRetry: !!storageItem.retries,
3308
+ isOffline
3309
+ }));
3310
+ const storageKey = scopeKey(request.cacheKey, scope);
3311
+ if ((this.cachedOrder.get(storageKey) ?? 0) > sentOrder) this.logger.debug({
3312
+ title: "Response of a request sent before the cached one, skipping the cache",
3313
+ type: "system",
3314
+ extra: {
3315
+ requestId,
3316
+ request,
3317
+ response
3318
+ }
3319
+ });
3320
+ else {
3321
+ if (response.success) this.cachedOrder.set(storageKey, sentOrder);
3322
+ notify(() => cache.set(request, {
3323
+ ...response,
3324
+ ...requestDetails
3325
+ }));
3326
+ }
3327
+ this.logger.debug({
3328
+ title: "Dispatcher processing response",
3329
+ type: "system",
3330
+ extra: {
3331
+ requestId,
3332
+ request,
3333
+ response,
3334
+ details: requestDetails
3335
+ }
3336
+ });
3337
+ if (isCanceled) {
3338
+ const queue = this.getQueue(queryKey);
3339
+ const queueItem = queue.requests.find((req) => req.requestId === requestId);
3340
+ if (!queue.stopped && !queueItem?.stopped) {
3341
+ this.logger.debug({
3342
+ title: "Request paused",
3343
+ type: "system",
3344
+ extra: {
3345
+ response,
3346
+ requestDetails,
3347
+ request
3348
+ }
3349
+ });
3350
+ return this.delete(queryKey, requestId, abortKey);
3351
+ }
3352
+ return this.logger.debug({
3353
+ title: "Request canceled",
3354
+ type: "system",
3355
+ extra: {
3356
+ response,
3357
+ requestDetails,
3358
+ request
3359
+ }
3360
+ });
3361
+ }
3362
+ if (!response.success && isOfflineResponseStatus) {
3363
+ if (!offline) {
3364
+ this.logger.warning({
3365
+ title: "Removing non-offline request",
3366
+ type: "system",
3367
+ extra: {
3368
+ response,
3369
+ requestDetails,
3370
+ request
3371
+ }
3372
+ });
3373
+ return this.delete(queryKey, requestId, abortKey);
3374
+ }
3375
+ return this.logger.debug({
3376
+ title: "Awaiting for network restoration",
3377
+ type: "system",
3378
+ extra: {
3379
+ response,
3380
+ requestDetails,
3381
+ request
3382
+ }
3383
+ });
3384
+ }
3385
+ if (response.success) {
3386
+ this.delete(queryKey, requestId, abortKey);
3387
+ return this.logger.debug({
3388
+ title: "Successful response, removing request from queue.",
3389
+ type: "system",
3390
+ extra: {
3391
+ response,
3392
+ requestDetails,
3393
+ request
3394
+ }
3395
+ });
3396
+ }
3397
+ if (willRetry) {
3398
+ this.logger.debug({
3399
+ title: "Waiting for retry",
3400
+ type: "system",
3401
+ extra: {
3402
+ response,
3403
+ requestDetails,
3404
+ request
3405
+ }
3406
+ });
3407
+ const retries = storageItem.retries + 1;
3408
+ this.setQueueItemRetries(queryKey, requestId, retries);
3409
+ this.cancelRetry(requestId);
3410
+ const retryTimer = setTimeout(async () => {
3411
+ this.retryTimers.delete(requestId);
3412
+ const queueItem = this.getRequest(queryKey, requestId);
3413
+ if (!queueItem) {
3414
+ this.logger.debug({
3415
+ title: "Request no longer in queue, skipping retry",
3416
+ type: "request",
3417
+ extra: {
3418
+ response,
3419
+ requestDetails,
3420
+ request,
3421
+ requestId
3422
+ }
3423
+ });
3424
+ requestManager.events.emitRemove({
3425
+ requestId,
3426
+ request,
3427
+ resolved: storageItem.resolved
3428
+ });
3429
+ return;
3430
+ }
3431
+ if (queueItem.stopped) return;
3432
+ this.logger.warning({
3433
+ title: "Error response, performing retry",
3434
+ type: "request",
3435
+ extra: {
3436
+ response,
3437
+ requestDetails,
3438
+ request,
3439
+ requestId
3440
+ }
3441
+ });
3442
+ await this.performRequest({
3443
+ ...storageItem,
3444
+ retries
3445
+ });
3446
+ this.flushQueue(queryKey);
3447
+ }, retryTime || 0);
3448
+ this.retryTimers.set(requestId, retryTimer);
3449
+ } else {
3450
+ if (request.retry) this.logger.error({
3451
+ title: "All retries have been used. Removing request from queue.",
3452
+ type: "request",
3453
+ extra: {
3454
+ response,
3455
+ requestDetails,
3456
+ request,
3457
+ requestId
3458
+ }
3459
+ });
3460
+ this.delete(queryKey, requestId, abortKey);
3461
+ }
3462
+ } finally {
3463
+ this.answeredRequests.delete(requestId);
3464
+ if (this.getRequest(queryKey, requestId)) this.flushQueue(queryKey);
3465
+ }
3466
+ };
3467
+ };
3468
+ //#endregion
3469
+ //#region src/dispatcher/dispatcher.utils.ts
3470
+ var getDispatcherDrainedKey = () => {
3471
+ return `drained-event`;
3472
+ };
3473
+ var getDispatcherDrainedByKey = (key) => {
3474
+ return `${key}-drained-event`;
3475
+ };
3476
+ var getDispatcherStatusKey = () => {
3477
+ return `status-event`;
3478
+ };
3479
+ var getDispatcherStatusByKey = (key) => {
3480
+ return `${key}-status-event`;
3481
+ };
3482
+ var getDispatcherChangeKey = () => {
3483
+ return `change-event`;
3484
+ };
3485
+ var getDispatcherChangeByKey = (key) => {
3486
+ return `${key}-change-event`;
3487
+ };
3488
+ var getDispatcherRunningKey = () => {
3489
+ return `running-event`;
3490
+ };
3491
+ var getDispatcherRunningByKey = (key) => {
3492
+ return `${key}-running-event`;
3493
+ };
3494
+ var getIsEqualTimestamp = (currentTimestamp, threshold, queueTimestamp) => {
3495
+ if (!queueTimestamp) return false;
3496
+ return queueTimestamp - currentTimestamp <= threshold;
3497
+ };
3498
+ var canRetryRequest = (currentRetries, retry) => {
3499
+ if (retry && currentRetries < retry) return true;
3500
+ return false;
3501
+ };
3502
+ var isInDeduplicateRange = (request, latestRequest) => {
3503
+ if (request.deduplicateTime) return Date.now() - latestRequest.timestamp <= request.deduplicateTime;
3504
+ return true;
3505
+ };
3506
+ var getRequestType = (request, latestRequest) => {
3507
+ const { queued, cancelable, deduplicate, used } = request;
3508
+ const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;
3509
+ const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;
3510
+ if (queued) return DispatcherMode.ONE_BY_ONE;
3511
+ if (cancelable) return DispatcherMode.PREVIOUS_CANCELED;
3512
+ if (canDeduplicate && isOngoing && deduplicate && !used) return DispatcherMode.DEDUPLICATED;
3513
+ return DispatcherMode.ALL_AT_ONCE;
3514
+ };
3515
+ //#endregion
3516
+ //#region src/http-adapter/http-adapter.constants.ts
3517
+ var defaultTimeout = Time.SEC * 5;
3518
+ var xhrExtra = { headers: {} };
3519
+ //#endregion
3520
+ //#region src/http-adapter/http-adapter.utils.ts
3521
+ var getResponseHeaders = (headersString) => {
3522
+ const arr = headersString.trim().split(/[\r\n]+/);
3523
+ const headers = {};
3524
+ arr.forEach((line) => {
3525
+ const parts = line.split(": ");
3526
+ const header = parts.shift();
3527
+ const value = parts.join(": ");
3528
+ if (header) headers[header] = value;
3529
+ });
3530
+ return headers;
3531
+ };
3532
+ var parseResponse = (response) => {
3533
+ try {
3534
+ return JSON.parse(response);
3535
+ } catch {
3536
+ return response;
3537
+ }
3538
+ };
3539
+ var handleResponse = (responseChunks, responseType, responseEncoding) => {
3540
+ const bufferedResponse = Buffer.concat(responseChunks);
3541
+ switch (responseType) {
3542
+ case "arraybuffer": return bufferedResponse;
3543
+ case "json": return parseResponse(bufferedResponse.toString(responseEncoding));
3544
+ default: return bufferedResponse.toString(responseEncoding);
3545
+ }
3546
+ };
3547
+ var parseErrorResponse = (response) => {
3548
+ return response ? parseResponse(response) : getErrorMessage();
3549
+ };
3550
+ var isValidValue = (options) => {
3551
+ return (value) => {
3552
+ const { skipNull, skipEmptyString } = options;
3553
+ if (skipEmptyString && value === void 0) return false;
3554
+ if (skipEmptyString && value === "") return false;
3555
+ if (skipNull && value === null) return false;
3556
+ return true;
3557
+ };
3558
+ };
3559
+ var encodeValue = (value, { encode, strict }) => {
3560
+ if (encode && strict) return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0).toString(16).toUpperCase()}`);
3561
+ if (encode) return encodeURIComponent(value);
3562
+ return value;
3563
+ };
3564
+ var parseValue = (value, options) => {
3565
+ if (value instanceof Date) return options.dateParser?.(value) || value.toISOString();
3566
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) return options.objectParser?.(value) || JSON.stringify(value);
3567
+ return String(value);
3568
+ };
3569
+ var encodeParams = (key, value, options) => {
3570
+ const shouldSkip = !isValidValue(options)(value);
3571
+ if (!key || shouldSkip) return "";
3572
+ return `${encodeValue(key, options)}=${encodeValue(parseValue(value, options), options)}`;
3573
+ };
3574
+ var encodeArray = (key, array, options) => {
3575
+ const { arrayFormat, arraySeparator } = options;
3576
+ const separator = arraySeparator || "|";
3577
+ const encodedKey = encodeValue(key, options);
3578
+ return array.filter(isValidValue(options)).reduce((acc, value, index) => {
3579
+ const encodedValue = encodeValue(parseValue(value, options), options);
3580
+ switch (arrayFormat) {
3581
+ case "index":
3582
+ acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);
3583
+ break;
3584
+ case "bracket":
3585
+ acc.push(`${encodedKey}[]=${encodedValue}`);
3586
+ break;
3587
+ case "comma": {
3588
+ const keyValue = acc.length === 0 && `${encodedKey}=` || "";
3589
+ return [[...acc, `${keyValue}${encodedValue}`].join(",")];
3601
3590
  }
3602
- });
3603
- if (isCanceled) {
3604
- const queue = this.getQueue(queryKey);
3605
- const queueItem = queue.requests.find((req) => req.requestId === requestId);
3606
- if (!queue.stopped && !queueItem?.stopped) {
3607
- this.logger.debug({
3608
- title: "Request paused",
3609
- type: "system",
3610
- extra: {
3611
- response,
3612
- requestDetails,
3613
- request
3614
- }
3615
- });
3616
- return this.delete(queryKey, requestId, abortKey);
3591
+ case "separator": {
3592
+ const keyValue = acc.length === 0 && `${encodedKey}=` || "";
3593
+ return [[...acc, `${keyValue}${encodedValue}`].join(separator)];
3617
3594
  }
3618
- return this.logger.debug({
3619
- title: "Request canceled",
3620
- type: "system",
3621
- extra: {
3622
- response,
3623
- requestDetails,
3624
- request
3625
- }
3626
- });
3595
+ case "bracket-separator": {
3596
+ const keyValue = acc.length === 0 && `${encodedKey}[]=` || "";
3597
+ return [[...acc, `${keyValue}${encodedValue}`].join(separator)];
3598
+ }
3599
+ default: acc.push(`${encodedKey}=${encodedValue}`);
3627
3600
  }
3628
- if (!response.success && isOfflineResponseStatus) {
3629
- if (!offline) {
3630
- this.logger.warning({
3631
- title: "Removing non-offline request",
3632
- type: "system",
3633
- extra: {
3634
- response,
3635
- requestDetails,
3636
- request
3637
- }
3601
+ return acc;
3602
+ }, []).join("&");
3603
+ };
3604
+ var stringifyQueryParams = (queryParams, options) => {
3605
+ const config = {
3606
+ ...stringifyDefaultOptions,
3607
+ ...options
3608
+ };
3609
+ if (!queryParams || Object.keys(queryParams).length === 0) return "";
3610
+ if (typeof queryParams === "string") return queryParams[0] === "?" ? queryParams : `?${queryParams}`;
3611
+ const stringified = Object.entries(queryParams).map(([key, value]) => {
3612
+ if (Array.isArray(value)) return encodeArray(key, value, config);
3613
+ return encodeParams(key, value, config);
3614
+ }).filter(Boolean).join("&");
3615
+ if (stringified) return `?${stringified}`;
3616
+ return "";
3617
+ };
3618
+ //#endregion
3619
+ //#region src/http-adapter/http-adapter.fetch.ts
3620
+ var defaultExtra = xhrExtra;
3621
+ var getAdapter = () => new Adapter({
3622
+ name: "http",
3623
+ defaultMethod: HttpMethods.GET,
3624
+ defaultExtra,
3625
+ systemErrorStatus: 0,
3626
+ systemErrorExtra: defaultExtra
3627
+ }).setQueryParamsMapper(stringifyQueryParams).setRequestDefaults((options) => {
3628
+ const method = options.method ?? HttpMethods.GET;
3629
+ if (SAFE_HTTP_METHODS.includes(method)) return { deduplicate: true };
3630
+ return {};
3631
+ }).setFetcher(async ({ request, url, endpoint, queryParams, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
3632
+ const { method } = request;
3633
+ const fullUrl = `${url}${endpoint}${queryParams}`;
3634
+ const controller = getAbortController();
3635
+ const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};
3636
+ let timedOut = false;
3637
+ let timeoutId;
3638
+ const unmountListener = createAbortListener({
3639
+ status: 0,
3640
+ extra: defaultExtra
3641
+ });
3642
+ if (timeoutMs > 0 && controller) timeoutId = setTimeout(() => {
3643
+ timedOut = true;
3644
+ unmountListener();
3645
+ controller.abort();
3646
+ }, timeoutMs);
3647
+ onBeforeRequest();
3648
+ onRequestStart();
3649
+ try {
3650
+ const init = {
3651
+ method,
3652
+ headers,
3653
+ signal: controller?.signal,
3654
+ ...restOptions
3655
+ };
3656
+ if (payload && method !== "GET" && method !== "HEAD") {
3657
+ init.body = payload;
3658
+ if (typeof payload === "string") {
3659
+ const total = new Blob([payload]).size;
3660
+ onRequestProgress({
3661
+ total,
3662
+ loaded: total
3638
3663
  });
3639
- return this.delete(queryKey, requestId, abortKey);
3640
3664
  }
3641
- return this.logger.debug({
3642
- title: "Awaiting for network restoration",
3643
- type: "system",
3644
- extra: {
3645
- response,
3646
- requestDetails,
3647
- request
3648
- }
3649
- });
3650
3665
  }
3651
- if (response.success) {
3652
- this.delete(queryKey, requestId, abortKey);
3653
- return this.logger.debug({
3654
- title: "Successful response, removing request from queue.",
3655
- type: "system",
3656
- extra: {
3657
- response,
3658
- requestDetails,
3659
- request
3660
- }
3666
+ onRequestEnd();
3667
+ const response = await fetch(fullUrl, init);
3668
+ if (timeoutId && streaming && response.body) clearTimeout(timeoutId);
3669
+ onResponseStart();
3670
+ const responseHeaders = {};
3671
+ response.headers.forEach((value, key) => {
3672
+ responseHeaders[key] = value;
3673
+ });
3674
+ const extra = { headers: responseHeaders };
3675
+ const { status } = response;
3676
+ if (streaming && response.body) {
3677
+ onResponseEnd();
3678
+ unmountListener();
3679
+ if (response.ok) onSuccess({
3680
+ data: response.body,
3681
+ status,
3682
+ extra
3661
3683
  });
3662
- }
3663
- if (willRetry) {
3664
- this.logger.debug({
3665
- title: "Waiting for retry",
3666
- type: "system",
3667
- extra: {
3668
- response,
3669
- requestDetails,
3670
- request
3671
- }
3684
+ else onError({
3685
+ error: parseErrorResponse(await response.text()),
3686
+ status,
3687
+ extra
3672
3688
  });
3673
- this.cancelRetry(requestId);
3674
- const retryTimer = setTimeout(() => {
3675
- this.retryTimers.delete(requestId);
3676
- if (!this.getRequest(queryKey, requestId)) {
3677
- this.logger.debug({
3678
- title: "Request no longer in queue, skipping retry",
3679
- type: "request",
3680
- extra: {
3681
- response,
3682
- requestDetails,
3683
- request,
3684
- requestId
3685
- }
3686
- });
3687
- requestManager.events.emitRemove({
3688
- requestId,
3689
- request,
3690
- resolved: storageItem.resolved
3689
+ } else {
3690
+ let body;
3691
+ if (response.body && typeof response.body.getReader === "function") {
3692
+ const reader = response.body.getReader();
3693
+ const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
3694
+ let receivedLength = 0;
3695
+ const chunks = [];
3696
+ while (true) {
3697
+ const { done, value } = await reader.read();
3698
+ if (done) break;
3699
+ chunks.push(value);
3700
+ receivedLength += value.length;
3701
+ onResponseProgress({
3702
+ total: contentLength || receivedLength,
3703
+ loaded: receivedLength
3691
3704
  });
3692
- return;
3693
3705
  }
3694
- this.logger.warning({
3695
- title: "Error response, performing retry",
3696
- type: "request",
3697
- extra: {
3698
- response,
3699
- requestDetails,
3700
- request,
3701
- requestId
3702
- }
3703
- });
3704
- this.performRequest({
3705
- ...storageItem,
3706
- retries: storageItem.retries + 1
3707
- });
3708
- }, retryTime || 0);
3709
- this.retryTimers.set(requestId, retryTimer);
3710
- } else {
3711
- if (request.retry) this.logger.error({
3712
- title: "All retries have been used. Removing request from queue.",
3713
- type: "request",
3714
- extra: {
3715
- response,
3716
- requestDetails,
3717
- request,
3718
- requestId
3706
+ const allChunks = new Uint8Array(receivedLength);
3707
+ let position = 0;
3708
+ for (const chunk of chunks) {
3709
+ allChunks.set(chunk, position);
3710
+ position += chunk.length;
3719
3711
  }
3712
+ body = new TextDecoder().decode(allChunks);
3713
+ } else body = await response.text();
3714
+ if (timeoutId) clearTimeout(timeoutId);
3715
+ onResponseEnd();
3716
+ unmountListener();
3717
+ if (response.ok) onSuccess({
3718
+ data: parseResponse(body),
3719
+ status,
3720
+ extra
3721
+ });
3722
+ else onError({
3723
+ error: parseErrorResponse(body),
3724
+ status,
3725
+ extra
3726
+ });
3727
+ }
3728
+ } catch (error) {
3729
+ if (timeoutId) clearTimeout(timeoutId);
3730
+ unmountListener();
3731
+ if (controller?.signal?.aborted) {
3732
+ if (timedOut) onTimeoutError({
3733
+ status: 0,
3734
+ extra: defaultExtra
3720
3735
  });
3721
- this.delete(queryKey, requestId, abortKey);
3736
+ return;
3737
+ }
3738
+ onError({
3739
+ error,
3740
+ status: 0,
3741
+ extra: defaultExtra
3742
+ });
3743
+ }
3744
+ });
3745
+ //#endregion
3746
+ //#region src/http-adapter/http-adapter.ts
3747
+ var HttpAdapter = () => {
3748
+ return getAdapter();
3749
+ };
3750
+ //#endregion
3751
+ //#region src/managers/app/app.manager.ts
3752
+ /**
3753
+ * App manager handles main application states - focus and online. Those two values can answer questions:
3754
+ * - Is the tab or current view instance focused and visible for user?
3755
+ * - Is our application online or offline?
3756
+ * With the app manager it is not a problem to get the valid answer for this question.
3757
+ *
3758
+ * @caution
3759
+ * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
3760
+ */
3761
+ var AppManager = class {
3762
+ emitter = new EventEmitter();
3763
+ events = getAppManagerEvents(this.emitter);
3764
+ isBrowser;
3765
+ isOnline;
3766
+ isFocused;
3767
+ unmountCallbacks = [];
3768
+ hasFocusUpdate = false;
3769
+ hasOnlineUpdate = false;
3770
+ constructor(options) {
3771
+ this.options = options;
3772
+ this.emitter?.setMaxListeners(1e3);
3773
+ const { initiallyFocused = appManagerInitialOptions.initiallyFocused, initiallyOnline = appManagerInitialOptions.initiallyOnline } = this.options || appManagerInitialOptions;
3774
+ this.setInitialFocus(initiallyFocused);
3775
+ this.setInitialOnline(initiallyOnline);
3776
+ this.isBrowser = hasDocument();
3777
+ }
3778
+ /**
3779
+ * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,
3780
+ * so the listeners are never registered twice.
3781
+ */
3782
+ initialize = () => {
3783
+ const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } = this.options || appManagerInitialOptions;
3784
+ this.unmount();
3785
+ [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {
3786
+ if (typeof unmount === "function") this.unmountCallbacks.push(unmount);
3787
+ });
3788
+ };
3789
+ /**
3790
+ * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.
3791
+ */
3792
+ unmount = () => {
3793
+ const callbacks = this.unmountCallbacks;
3794
+ this.unmountCallbacks = [];
3795
+ callbacks.forEach((unmount) => unmount());
3796
+ };
3797
+ setInitialFocus = (initValue) => {
3798
+ this.isFocused = this.readInitialValue(initValue, (isFocused) => {
3799
+ if (!this.hasFocusUpdate && isFocused !== this.isFocused) this.setFocused(isFocused);
3800
+ });
3801
+ };
3802
+ setInitialOnline = (initValue) => {
3803
+ this.isOnline = this.readInitialValue(initValue, (isOnline) => {
3804
+ if (!this.hasOnlineUpdate && isOnline !== this.isOnline) this.setOnline(isOnline);
3805
+ });
3806
+ };
3807
+ /**
3808
+ * Reads the initial state from a value or a getter. Synchronous getters apply right away, so there is no moment
3809
+ * with a wrong value. Asynchronous ones start with `false` and apply once resolved - the change is emitted like
3810
+ * any other, so the modules waiting for the focus or the network get notified.
3811
+ * A getter which throws or rejects leaves the state unknown, so it falls back to `true` - just like the defaults do.
3812
+ */
3813
+ readInitialValue = (initValue, onResolved) => {
3814
+ if (typeof initValue !== "function") return initValue;
3815
+ try {
3816
+ const value = initValue();
3817
+ if (typeof value === "boolean") return value;
3818
+ Promise.resolve(value).then((resolved) => onResolved(resolved), () => onResolved(true));
3819
+ return false;
3820
+ } catch {
3821
+ return true;
3722
3822
  }
3723
3823
  };
3824
+ setFocused = (isFocused) => {
3825
+ this.hasFocusUpdate = true;
3826
+ this.isFocused = isFocused;
3827
+ if (isFocused) this.events.emitFocus();
3828
+ else this.events.emitBlur();
3829
+ };
3830
+ setOnline = (isOnline) => {
3831
+ this.hasOnlineUpdate = true;
3832
+ this.isOnline = isOnline;
3833
+ if (isOnline) this.events.emitOnline();
3834
+ else this.events.emitOffline();
3835
+ };
3724
3836
  };
3725
3837
  //#endregion
3726
- //#region src/dispatcher/dispatcher.utils.ts
3727
- var getDispatcherDrainedKey = () => {
3728
- return `drained-event`;
3729
- };
3730
- var getDispatcherDrainedByKey = (key) => {
3731
- return `${key}-drained-event`;
3732
- };
3733
- var getDispatcherStatusKey = () => {
3734
- return `status-event`;
3735
- };
3736
- var getDispatcherStatusByKey = (key) => {
3737
- return `${key}-status-event`;
3738
- };
3739
- var getDispatcherChangeKey = () => {
3740
- return `change-event`;
3838
+ //#region src/managers/app/app.manager.utils.ts
3839
+ var hasWindow = () => {
3840
+ try {
3841
+ return Boolean(window && window.addEventListener);
3842
+ } catch {
3843
+ /* istanbul ignore next */
3844
+ return false;
3845
+ }
3741
3846
  };
3742
- var getDispatcherChangeByKey = (key) => {
3743
- return `${key}-change-event`;
3847
+ var hasDocument = () => {
3848
+ try {
3849
+ return Boolean(hasWindow() && window.document && window.document.addEventListener);
3850
+ } catch {
3851
+ /* istanbul ignore next */
3852
+ return false;
3853
+ }
3744
3854
  };
3745
- var getDispatcherRunningKey = () => {
3746
- return `running-event`;
3855
+ /**
3856
+ * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or
3857
+ * React Native, where `navigator.onLine` is not available.
3858
+ */
3859
+ var isNavigatorOnline = () => {
3860
+ try {
3861
+ return typeof navigator.onLine === "boolean" ? navigator.onLine : true;
3862
+ } catch {
3863
+ /* istanbul ignore next */
3864
+ return true;
3865
+ }
3747
3866
  };
3748
- var getDispatcherRunningByKey = (key) => {
3749
- return `${key}-running-event`;
3867
+ var onWindowEvent = (key, listener, options) => {
3868
+ /* istanbul ignore next */
3869
+ if (hasWindow()) {
3870
+ const target = window;
3871
+ target.addEventListener(key, listener, options);
3872
+ return () => target.removeEventListener(key, listener, options);
3873
+ }
3874
+ /* istanbul ignore next */
3875
+ return () => null;
3750
3876
  };
3751
- var getIsEqualTimestamp = (currentTimestamp, threshold, queueTimestamp) => {
3752
- if (!queueTimestamp) return false;
3753
- return queueTimestamp - currentTimestamp <= threshold;
3877
+ var onDocumentEvent = (key, listener, options) => {
3878
+ /* istanbul ignore next */
3879
+ if (hasDocument()) {
3880
+ const target = window.document;
3881
+ target.addEventListener(key, listener, options);
3882
+ return () => target.removeEventListener(key, listener, options);
3883
+ }
3884
+ /* istanbul ignore next */
3885
+ return () => null;
3754
3886
  };
3755
- var canRetryRequest = (currentRetries, retry) => {
3756
- if (retry && currentRetries < retry) return true;
3757
- return false;
3887
+ //#endregion
3888
+ //#region src/managers/app/app.manager.events.ts
3889
+ /** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */
3890
+ var getAppManagerEvents = (emitter) => ({
3891
+ emitFocus: () => {
3892
+ emitter.emit(AppEvents.FOCUS);
3893
+ },
3894
+ emitBlur: () => {
3895
+ emitter.emit(AppEvents.BLUR);
3896
+ },
3897
+ emitOnline: () => {
3898
+ emitter.emit(AppEvents.ONLINE);
3899
+ },
3900
+ emitOffline: () => {
3901
+ emitter.emit(AppEvents.OFFLINE);
3902
+ },
3903
+ onFocus: (callback) => {
3904
+ emitter.on(AppEvents.FOCUS, callback);
3905
+ return () => emitter.removeListener(AppEvents.FOCUS, callback);
3906
+ },
3907
+ onBlur: (callback) => {
3908
+ emitter.on(AppEvents.BLUR, callback);
3909
+ return () => emitter.removeListener(AppEvents.BLUR, callback);
3910
+ },
3911
+ onOnline: (callback) => {
3912
+ emitter.on(AppEvents.ONLINE, callback);
3913
+ return () => emitter.removeListener(AppEvents.ONLINE, callback);
3914
+ },
3915
+ onOffline: (callback) => {
3916
+ emitter.on(AppEvents.OFFLINE, callback);
3917
+ return () => emitter.removeListener(AppEvents.OFFLINE, callback);
3918
+ }
3919
+ });
3920
+ //#endregion
3921
+ //#region src/managers/app/app.manager.constants.ts
3922
+ /** Document is visible unless the browser reports it as hidden - when the state is unknown we assume it is visible */
3923
+ var isDocumentVisible = () => {
3924
+ try {
3925
+ return window.document.visibilityState !== "hidden";
3926
+ } catch {
3927
+ /* istanbul ignore next */
3928
+ return true;
3929
+ }
3758
3930
  };
3759
- var isInDeduplicateRange = (request, latestRequest) => {
3760
- if (request.deduplicateTime) return Date.now() - latestRequest.timestamp <= request.deduplicateTime;
3761
- return true;
3931
+ var AppEvents = /* @__PURE__ */ function(AppEvents) {
3932
+ AppEvents["FOCUS"] = "focus";
3933
+ AppEvents["BLUR"] = "blur";
3934
+ AppEvents["ONLINE"] = "online";
3935
+ AppEvents["OFFLINE"] = "offline";
3936
+ return AppEvents;
3937
+ }({});
3938
+ var appManagerInitialOptions = {
3939
+ initiallyFocused: true,
3940
+ initiallyOnline: isNavigatorOnline,
3941
+ focusEvent: (setFocused) => {
3942
+ const unmountVisibility = onDocumentEvent("visibilitychange", () => setFocused(isDocumentVisible()));
3943
+ const unmountFocus = onWindowEvent("focus", () => setFocused(true));
3944
+ const unmountBlur = onWindowEvent("blur", () => setFocused(false));
3945
+ return () => {
3946
+ unmountVisibility();
3947
+ unmountFocus();
3948
+ unmountBlur();
3949
+ };
3950
+ },
3951
+ onlineEvent: (setOnline) => {
3952
+ const unmountOnline = onWindowEvent("online", () => setOnline(true));
3953
+ const unmountOffline = onWindowEvent("offline", () => setOnline(false));
3954
+ return () => {
3955
+ unmountOnline();
3956
+ unmountOffline();
3957
+ };
3958
+ }
3762
3959
  };
3763
- var getRequestType = (request, latestRequest) => {
3764
- const { queued, cancelable, deduplicate, used } = request;
3765
- const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;
3766
- const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;
3767
- if (queued) return DispatcherMode.ONE_BY_ONE;
3768
- if (cancelable) return DispatcherMode.PREVIOUS_CANCELED;
3769
- if (canDeduplicate && isOngoing && deduplicate && !used) return DispatcherMode.DEDUPLICATED;
3770
- return DispatcherMode.ALL_AT_ONCE;
3960
+ //#endregion
3961
+ //#region src/managers/request/request.manager.ts
3962
+ /**
3963
+ * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.
3964
+ * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.
3965
+ */
3966
+ var RequestManager = class {
3967
+ emitter = new EventEmitter();
3968
+ events = getRequestManagerEvents(this.emitter);
3969
+ constructor() {
3970
+ this.emitter?.setMaxListeners(1e3);
3971
+ }
3972
+ abortControllers = /* @__PURE__ */ new Map();
3973
+ addAbortController = (abortKey, requestId) => {
3974
+ let abortGroup = this.abortControllers.get(abortKey);
3975
+ if (!abortGroup) {
3976
+ const newAbortGroup = /* @__PURE__ */ new Map();
3977
+ abortGroup = newAbortGroup;
3978
+ this.abortControllers.set(abortKey, newAbortGroup);
3979
+ }
3980
+ const abortController = abortGroup.get(requestId);
3981
+ if (!abortController || abortController.signal.aborted) abortGroup.set(requestId, new AbortController());
3982
+ };
3983
+ getAbortController = (abortKey, requestId) => {
3984
+ return this.abortControllers.get(abortKey)?.get(requestId);
3985
+ };
3986
+ removeAbortController = (abortKey, requestId) => {
3987
+ const abortGroup = this.abortControllers.get(abortKey);
3988
+ abortGroup?.delete(requestId);
3989
+ if (abortGroup?.size === 0) this.abortControllers.delete(abortKey);
3990
+ };
3991
+ useAbortController = (abortKey, requestId) => {
3992
+ (this.abortControllers.get(abortKey)?.get(requestId))?.abort();
3993
+ };
3994
+ abortByKey = (abortKey) => {
3995
+ const controllers = this.abortControllers.get(abortKey);
3996
+ if (controllers) [...controllers.entries()].forEach(([key]) => {
3997
+ this.useAbortController(abortKey, key);
3998
+ });
3999
+ };
4000
+ abortByRequestId = (abortKey, requestId) => {
4001
+ this.useAbortController(abortKey, requestId);
4002
+ };
4003
+ abortAll = () => {
4004
+ [...this.abortControllers.entries()].forEach(([abortKey, value]) => {
4005
+ [...value.entries()].forEach(([requestId]) => {
4006
+ this.useAbortController(abortKey, requestId);
4007
+ });
4008
+ });
4009
+ };
3771
4010
  };
3772
4011
  //#endregion
3773
- //#region src/http-adapter/http-adapter.constants.ts
3774
- var defaultTimeout = Time.SEC * 5;
3775
- var xhrExtra = { headers: {} };
4012
+ //#region src/managers/request/request.manager.utils.ts
4013
+ var getLoadingKey = () => `loading-event-any`;
4014
+ var getLoadingByQueryKey = (queryKey) => `${queryKey}-loading-event`;
4015
+ var getLoadingByCacheKey = (cacheKey) => `${cacheKey}-loading-cache-event`;
4016
+ var getLoadingByIdKey = (id) => `${id}-loading-event-by-id`;
4017
+ var getRemoveKey = () => `remove-event-any`;
4018
+ var getRemoveByQueryKey = (queryKey) => `${queryKey}-remove-event`;
4019
+ var getRemoveByIdKey = (id) => `${id}-remove-event-by-id`;
4020
+ var getAbortKey = () => `request-abort-any`;
4021
+ var getAbortByAbortKey = (abortKey) => `${abortKey}-request-abort`;
4022
+ var getAbortByIdKey = (id) => `${id}-request-abort-by-id`;
4023
+ var getResponseKey = () => `response-any`;
4024
+ var getResponseByCacheKey = (cacheKey) => `${cacheKey}-response`;
4025
+ var getResponseByIdKey = (id) => `${id}-response-by-id`;
4026
+ var getRequestStartKey = () => `request-start-any`;
4027
+ var getRequestStarByQueryKey = (queryKey) => `${queryKey}-request-start`;
4028
+ var getRequestStartByIdKey = (id) => `${id}-request-start-by-id`;
4029
+ var getResponseStartKey = () => `response-start-any`;
4030
+ var getResponseStartByQueryKey = (queryKey) => `${queryKey}-response-start`;
4031
+ var getResponseStartByIdKey = (id) => `${id}-response-start-by-id`;
4032
+ var getUploadProgressKey = () => `request-progress-any`;
4033
+ var getUploadProgressByQueryKey = (queryKey) => `${queryKey}-request-progress`;
4034
+ var getUploadProgressByIdKey = (id) => `${id}-request-progress-by-id`;
4035
+ var getDownloadProgressKey = () => `response-progress-any`;
4036
+ var getDownloadProgressByQueryKey = (queryKey) => `${queryKey}-response-progress`;
4037
+ var getDownloadProgressByIdKey = (id) => `${id}-response-progress-by-id`;
4038
+ var getRequestDeduplicatedKey = () => `request-deduplicated-any`;
4039
+ var getRequestDeduplicatedByQueryKey = (queryKey) => `${queryKey}-query-request-deduplicated`;
4040
+ var getRequestDeduplicatedByCacheKey = (cacheKey) => `${cacheKey}-cache-request-deduplicated`;
4041
+ var getRequestDeduplicatedByIdKey = (id) => `${id}-request-deduplicated-by-id`;
3776
4042
  //#endregion
3777
- //#region src/http-adapter/http-adapter.utils.ts
3778
- var getResponseHeaders = (headersString) => {
3779
- const arr = headersString.trim().split(/[\r\n]+/);
3780
- const headers = {};
3781
- arr.forEach((line) => {
3782
- const parts = line.split(": ");
3783
- const header = parts.shift();
3784
- const value = parts.join(": ");
3785
- if (header) headers[header] = value;
3786
- });
3787
- return headers;
3788
- };
3789
- var parseResponse = (response) => {
3790
- try {
3791
- return JSON.parse(response);
3792
- } catch {
3793
- return response;
4043
+ //#region src/managers/request/request.manager.events.ts
4044
+ /** Create event emitters and listeners for the request lifecycle: loading, progress, response, abort, deduplication, and removal. */
4045
+ var getRequestManagerEvents = (emitter) => ({
4046
+ emitDeduplicated: (data, isTriggeredExternally = false) => {
4047
+ emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);
4048
+ emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);
4049
+ emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
4050
+ emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4051
+ },
4052
+ emitLoading: (data, isTriggeredExternally = false) => {
4053
+ emitter.emit(getLoadingKey(), data, isTriggeredExternally);
4054
+ emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);
4055
+ emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
4056
+ emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4057
+ },
4058
+ emitRequestStart: (data, isTriggeredExternally = false) => {
4059
+ emitter.emit(getRequestStartKey(), data, isTriggeredExternally);
4060
+ emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);
4061
+ emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4062
+ },
4063
+ emitResponseStart: (data, isTriggeredExternally = false) => {
4064
+ emitter.emit(getResponseStartKey(), data, isTriggeredExternally);
4065
+ emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);
4066
+ emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4067
+ },
4068
+ emitUploadProgress: (data, isTriggeredExternally = false) => {
4069
+ emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);
4070
+ emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);
4071
+ emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4072
+ },
4073
+ emitDownloadProgress: (data, isTriggeredExternally = false) => {
4074
+ emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);
4075
+ emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);
4076
+ emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4077
+ },
4078
+ emitResponse: (data, isTriggeredExternally = false) => {
4079
+ emitter.emit(getResponseKey(), data, isTriggeredExternally);
4080
+ emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);
4081
+ emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
4082
+ },
4083
+ emitAbort: (data, isTriggeredExternally = false) => {
4084
+ emitter.emit(getAbortKey(), data, isTriggeredExternally);
4085
+ emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);
4086
+ emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);
4087
+ },
4088
+ emitRemove: (data, isTriggeredExternally = false) => {
4089
+ emitter.emit(getRemoveKey(), data, isTriggeredExternally);
4090
+ emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);
4091
+ emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);
4092
+ },
4093
+ onDeduplicated: (callback) => {
4094
+ emitter.on(getRequestDeduplicatedKey(), callback);
4095
+ return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);
4096
+ },
4097
+ onDeduplicatedByQueue: (queryKey, callback) => {
4098
+ emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);
4099
+ return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);
4100
+ },
4101
+ onDeduplicatedByCache: (cacheKey, callback) => {
4102
+ emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);
4103
+ return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);
4104
+ },
4105
+ onDeduplicatedById: (requestId, callback) => {
4106
+ emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);
4107
+ return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);
4108
+ },
4109
+ onLoading: (callback) => {
4110
+ emitter.on(getLoadingKey(), callback);
4111
+ return () => emitter.removeListener(getLoadingKey(), callback);
4112
+ },
4113
+ onLoadingByQueue: (queryKey, callback) => {
4114
+ emitter.on(getLoadingByQueryKey(queryKey), callback);
4115
+ return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);
4116
+ },
4117
+ onLoadingByCache: (cacheKey, callback) => {
4118
+ emitter.on(getLoadingByCacheKey(cacheKey), callback);
4119
+ return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);
4120
+ },
4121
+ onLoadingById: (requestId, callback) => {
4122
+ emitter.on(getLoadingByIdKey(requestId), callback);
4123
+ return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);
4124
+ },
4125
+ onRequestStart: (callback) => {
4126
+ emitter.on(getRequestStartKey(), callback);
4127
+ return () => emitter.removeListener(getRequestStartKey(), callback);
4128
+ },
4129
+ onRequestStartByQueue: (queryKey, callback) => {
4130
+ emitter.on(getRequestStarByQueryKey(queryKey), callback);
4131
+ return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);
4132
+ },
4133
+ onRequestStartById: (requestId, callback) => {
4134
+ emitter.on(getRequestStartByIdKey(requestId), callback);
4135
+ return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);
4136
+ },
4137
+ onResponseStart: (callback) => {
4138
+ emitter.on(getResponseStartKey(), callback);
4139
+ return () => emitter.removeListener(getResponseStartKey(), callback);
4140
+ },
4141
+ onResponseStartByQueue: (queryKey, callback) => {
4142
+ emitter.on(getResponseStartByQueryKey(queryKey), callback);
4143
+ return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);
4144
+ },
4145
+ onResponseStartById: (requestId, callback) => {
4146
+ emitter.on(getResponseStartByIdKey(requestId), callback);
4147
+ return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);
4148
+ },
4149
+ onUploadProgress: (callback) => {
4150
+ emitter.on(getUploadProgressKey(), callback);
4151
+ return () => emitter.removeListener(getUploadProgressKey(), callback);
4152
+ },
4153
+ onUploadProgressByQueue: (queryKey, callback) => {
4154
+ emitter.on(getUploadProgressByQueryKey(queryKey), callback);
4155
+ return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);
4156
+ },
4157
+ onUploadProgressById: (requestId, callback) => {
4158
+ emitter.on(getUploadProgressByIdKey(requestId), callback);
4159
+ return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);
4160
+ },
4161
+ onDownloadProgress: (callback) => {
4162
+ emitter.on(getDownloadProgressKey(), callback);
4163
+ return () => emitter.removeListener(getDownloadProgressKey(), callback);
4164
+ },
4165
+ onDownloadProgressByQueue: (queryKey, callback) => {
4166
+ emitter.on(getDownloadProgressByQueryKey(queryKey), callback);
4167
+ return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);
4168
+ },
4169
+ onDownloadProgressById: (requestId, callback) => {
4170
+ emitter.on(getDownloadProgressByIdKey(requestId), callback);
4171
+ return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);
4172
+ },
4173
+ onResponse: (callback) => {
4174
+ emitter.on(getResponseKey(), callback);
4175
+ return () => emitter.removeListener(getResponseKey(), callback);
4176
+ },
4177
+ onResponseByCache: (cacheKey, callback) => {
4178
+ emitter.on(getResponseByCacheKey(cacheKey), callback);
4179
+ return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);
4180
+ },
4181
+ onResponseById: (requestId, callback) => {
4182
+ emitter.on(getResponseByIdKey(requestId), callback);
4183
+ return () => emitter.removeListener(getResponseByIdKey(requestId), callback);
4184
+ },
4185
+ onAbort: (callback) => {
4186
+ emitter.on(getAbortKey(), callback);
4187
+ return () => emitter.removeListener(getAbortKey(), callback);
4188
+ },
4189
+ onAbortByKey: (abortKey, callback) => {
4190
+ emitter.on(getAbortByAbortKey(abortKey), callback);
4191
+ return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);
4192
+ },
4193
+ onAbortById: (requestId, callback) => {
4194
+ emitter.on(getAbortByIdKey(requestId), callback);
4195
+ return () => emitter.removeListener(getAbortByIdKey(requestId), callback);
4196
+ },
4197
+ onRemove: (callback) => {
4198
+ emitter.on(getRemoveKey(), callback);
4199
+ return () => emitter.removeListener(getRemoveKey(), callback);
4200
+ },
4201
+ onRemoveByQueue: (queryKey, callback) => {
4202
+ emitter.on(getRemoveByQueryKey(queryKey), callback);
4203
+ return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);
4204
+ },
4205
+ onRemoveById: (requestId, callback) => {
4206
+ emitter.on(getRemoveByIdKey(requestId), callback);
4207
+ return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);
3794
4208
  }
3795
- };
3796
- var handleResponse = (responseChunks, responseType, responseEncoding) => {
3797
- const bufferedResponse = Buffer.concat(responseChunks);
3798
- switch (responseType) {
3799
- case "arraybuffer": return bufferedResponse;
3800
- case "json": return parseResponse(bufferedResponse.toString(responseEncoding));
3801
- default: return bufferedResponse.toString(responseEncoding);
4209
+ });
4210
+ //#endregion
4211
+ //#region src/managers/logger/logger.manager.ts
4212
+ /**
4213
+ * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.
4214
+ * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module
4215
+ * like Client, Request etc. Which can give you better feedback on the logging itself.
4216
+ */
4217
+ var LoggerManager = class LoggerManager {
4218
+ logger;
4219
+ level;
4220
+ modules;
4221
+ emitter = new import_events.default();
4222
+ client;
4223
+ constructor(options) {
4224
+ this.options = options;
4225
+ this.emitter?.setMaxListeners(1e3);
4226
+ this.logger = this.options?.logger || logger;
4227
+ this.level = this.options?.level || "warning";
4228
+ this.modules = this.options?.modules;
3802
4229
  }
3803
- };
3804
- var parseErrorResponse = (response) => {
3805
- return response ? parseResponse(response) : getErrorMessage();
3806
- };
3807
- var isValidValue = (options) => {
3808
- return (value) => {
3809
- const { skipNull, skipEmptyString } = options;
3810
- if (skipEmptyString && value === void 0) return false;
3811
- if (skipEmptyString && value === "") return false;
3812
- if (skipNull && value === null) return false;
3813
- return true;
4230
+ setSeverity = (level) => {
4231
+ this.level = level;
4232
+ };
4233
+ setModules = (modules) => {
4234
+ this.modules = modules;
4235
+ };
4236
+ initialize = (client, module) => {
4237
+ this.client = client;
4238
+ const getClientManager = () => client.loggerManager;
4239
+ const isClientManager = getClientManager() === this;
4240
+ const log = (data) => {
4241
+ const clientManager = getClientManager();
4242
+ (isClientManager && clientManager instanceof LoggerManager ? clientManager : this).log(data, client);
4243
+ };
4244
+ return {
4245
+ error: (data) => log({
4246
+ ...data,
4247
+ level: "error",
4248
+ module
4249
+ }),
4250
+ warning: (data) => log({
4251
+ ...data,
4252
+ level: "warning",
4253
+ module
4254
+ }),
4255
+ info: (data) => log({
4256
+ ...data,
4257
+ level: "info",
4258
+ module
4259
+ }),
4260
+ debug: (data) => log({
4261
+ ...data,
4262
+ level: "debug",
4263
+ module
4264
+ })
4265
+ };
4266
+ };
4267
+ log = (data, client = this.client) => {
4268
+ if (!client.debug) return;
4269
+ if (logLevelOrder.indexOf(this.level) < logLevelOrder.indexOf(data.level)) return;
4270
+ if (this.modules && !this.modules.includes(data.module)) return;
4271
+ this.logger(data);
3814
4272
  };
3815
4273
  };
3816
- var encodeValue = (value, { encode, strict }) => {
3817
- if (encode && strict) return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0).toString(16).toUpperCase()}`);
3818
- if (encode) return encodeURIComponent(value);
3819
- return value;
3820
- };
3821
- var parseValue = (value, options) => {
3822
- if (value instanceof Date) return options.dateParser?.(value) || value.toISOString();
3823
- if (value !== null && typeof value === "object" && !Array.isArray(value)) return options.objectParser?.(value) || JSON.stringify(value);
3824
- return String(value);
3825
- };
3826
- var encodeParams = (key, value, options) => {
3827
- const shouldSkip = !isValidValue(options)(value);
3828
- if (!key || shouldSkip) return "";
3829
- return `${encodeValue(key, options)}=${encodeValue(parseValue(value, options), options)}`;
4274
+ //#endregion
4275
+ //#region src/managers/logger/logger.manager.utils.ts
4276
+ var getTime = () => {
4277
+ return `${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`;
3830
4278
  };
3831
- var encodeArray = (key, array, options) => {
3832
- const { arrayFormat, arraySeparator } = options;
3833
- const separator = arraySeparator || "|";
3834
- const encodedKey = encodeValue(key, options);
3835
- return array.filter(isValidValue(options)).reduce((acc, value, index) => {
3836
- const encodedValue = encodeValue(parseValue(value, options), options);
3837
- switch (arrayFormat) {
3838
- case "index":
3839
- acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);
3840
- break;
3841
- case "bracket":
3842
- acc.push(`${encodedKey}[]=${encodedValue}`);
3843
- break;
3844
- case "comma": {
3845
- const keyValue = acc.length === 0 && `${encodedKey}=` || "";
3846
- return [[...acc, `${keyValue}${encodedValue}`].join(",")];
3847
- }
3848
- case "separator": {
3849
- const keyValue = acc.length === 0 && `${encodedKey}=` || "";
3850
- return [[...acc, `${keyValue}${encodedValue}`].join(separator)];
3851
- }
3852
- case "bracket-separator": {
3853
- const keyValue = acc.length === 0 && `${encodedKey}[]=` || "";
3854
- return [[...acc, `${keyValue}${encodedValue}`].join(separator)];
3855
- }
3856
- default: acc.push(`${encodedKey}=${encodedValue}`);
3857
- }
3858
- return acc;
3859
- }, []).join("&");
4279
+ var getModuleName = (data) => {
4280
+ if (data.type === "request" || data.type === "response") return `${data.extra.request.endpoint}`;
4281
+ return `[${data.module}]`;
3860
4282
  };
3861
- var stringifyQueryParams = (queryParams, options) => {
3862
- const config = {
3863
- ...stringifyDefaultOptions,
3864
- ...options
3865
- };
3866
- if (!queryParams || Object.keys(queryParams).length === 0) return "";
3867
- if (typeof queryParams === "string") return queryParams[0] === "?" ? queryParams : `?${queryParams}`;
3868
- const stringified = Object.entries(queryParams).map(([key, value]) => {
3869
- if (Array.isArray(value)) return encodeArray(key, value, config);
3870
- return encodeParams(key, value, config);
3871
- }).filter(Boolean).join("&");
3872
- if (stringified) return `?${stringified}`;
3873
- return "";
4283
+ var logger = (log) => {
4284
+ const styles = loggerStyles[log.level];
4285
+ const color = loggerColors[log.level];
4286
+ const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;
4287
+ const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;
4288
+ const style2 = `${styles}${color}font-weight:600;`;
4289
+ const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;
4290
+ if (log.extra ? Object.keys(log.extra)?.length : false) {
4291
+ console.groupCollapsed(message, style1, style2, style3);
4292
+ console.log(log.extra);
4293
+ console.groupEnd();
4294
+ } else console.log(message, styles);
3874
4295
  };
3875
4296
  //#endregion
3876
- //#region src/http-adapter/http-adapter.fetch.ts
3877
- var defaultExtra = xhrExtra;
3878
- var getAdapter = () => new Adapter({
3879
- name: "http",
3880
- defaultMethod: HttpMethods.GET,
3881
- defaultExtra,
3882
- systemErrorStatus: 0,
3883
- systemErrorExtra: defaultExtra
3884
- }).setQueryParamsMapper(stringifyQueryParams).setRequestDefaults((options) => {
3885
- const method = options.method ?? HttpMethods.GET;
3886
- if (SAFE_HTTP_METHODS.includes(method)) return { deduplicate: true };
3887
- return {};
3888
- }).setFetcher(async ({ request, url, endpoint, queryParams, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
3889
- const { method } = request;
3890
- const fullUrl = `${url}${endpoint}${queryParams}`;
3891
- const controller = getAbortController();
3892
- const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};
3893
- let timedOut = false;
3894
- let timeoutId;
3895
- const unmountListener = createAbortListener({
3896
- status: 0,
3897
- extra: defaultExtra
3898
- });
3899
- if (timeoutMs > 0 && controller) timeoutId = setTimeout(() => {
3900
- timedOut = true;
3901
- unmountListener();
3902
- controller.abort();
3903
- }, timeoutMs);
3904
- onBeforeRequest();
3905
- onRequestStart();
3906
- try {
3907
- const init = {
3908
- method,
3909
- headers,
3910
- signal: controller?.signal,
3911
- ...restOptions
3912
- };
3913
- if (payload && method !== "GET" && method !== "HEAD") {
3914
- init.body = payload;
3915
- if (typeof payload === "string") {
3916
- const total = new Blob([payload]).size;
3917
- onRequestProgress({
3918
- total,
3919
- loaded: total
3920
- });
3921
- }
3922
- }
3923
- onRequestEnd();
3924
- const response = await fetch(fullUrl, init);
3925
- if (timeoutId) clearTimeout(timeoutId);
3926
- onResponseStart();
3927
- const responseHeaders = {};
3928
- response.headers.forEach((value, key) => {
3929
- responseHeaders[key] = value;
3930
- });
3931
- const extra = { headers: responseHeaders };
3932
- const { status } = response;
3933
- if (streaming && response.body) {
3934
- onResponseEnd();
3935
- unmountListener();
3936
- if (response.ok) onSuccess({
3937
- data: response.body,
3938
- status,
3939
- extra
3940
- });
3941
- else onError({
3942
- error: parseErrorResponse(await response.text()),
3943
- status,
3944
- extra
3945
- });
3946
- } else {
3947
- let body;
3948
- if (response.body && typeof response.body.getReader === "function") {
3949
- const reader = response.body.getReader();
3950
- const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
3951
- let receivedLength = 0;
3952
- const chunks = [];
3953
- while (true) {
3954
- const { done, value } = await reader.read();
3955
- if (done) break;
3956
- chunks.push(value);
3957
- receivedLength += value.length;
3958
- onResponseProgress({
3959
- total: contentLength || receivedLength,
3960
- loaded: receivedLength
3961
- });
3962
- }
3963
- const allChunks = new Uint8Array(receivedLength);
3964
- let position = 0;
3965
- for (const chunk of chunks) {
3966
- allChunks.set(chunk, position);
3967
- position += chunk.length;
3968
- }
3969
- body = new TextDecoder().decode(allChunks);
3970
- } else body = await response.text();
3971
- onResponseEnd();
3972
- unmountListener();
3973
- if (response.ok) onSuccess({
3974
- data: parseResponse(body),
3975
- status,
3976
- extra
3977
- });
3978
- else onError({
3979
- error: parseErrorResponse(body),
3980
- status,
3981
- extra
3982
- });
3983
- }
3984
- } catch (error) {
3985
- if (timeoutId) clearTimeout(timeoutId);
3986
- unmountListener();
3987
- if (controller?.signal?.aborted) {
3988
- if (timedOut) onTimeoutError({
3989
- status: 0,
3990
- extra: defaultExtra
3991
- });
3992
- return;
3993
- }
3994
- onError({
3995
- error,
3996
- status: 0,
3997
- extra: defaultExtra
3998
- });
3999
- }
4000
- });
4001
- //#endregion
4002
- //#region src/http-adapter/http-adapter.ts
4003
- var HttpAdapter = () => {
4004
- return getAdapter();
4297
+ //#region src/managers/logger/logger.manager.constants.ts
4298
+ var logLevelOrder = [
4299
+ "error",
4300
+ "warning",
4301
+ "info",
4302
+ "debug"
4303
+ ];
4304
+ var defaultStyles = "padding:2px 5px;";
4305
+ var loggerStyles = {
4306
+ error: `${defaultStyles};background:#db252520;`,
4307
+ warning: `${defaultStyles};background:#e1941e20;`,
4308
+ info: `${defaultStyles};background:#1e74e120;`,
4309
+ debug: `${defaultStyles};background:#00000020;`
4310
+ };
4311
+ var loggerColors = {
4312
+ error: "color:#ff3737;",
4313
+ warning: "color:#ffc107;",
4314
+ info: "color:#34a8ff;",
4315
+ debug: "color:#cccccc;"
4005
4316
  };
4006
4317
  //#endregion
4007
4318
  //#region src/client/client.utils.ts
@@ -4014,7 +4325,7 @@ function resolveClientMode(modeOption) {
4014
4325
  var interceptRequest = async (interceptors, request) => {
4015
4326
  let newRequest = request;
4016
4327
  if (!request.requestOptions.disableRequestInterceptors) for (const interceptor of interceptors) {
4017
- newRequest = await interceptor(request);
4328
+ newRequest = await interceptor(newRequest);
4018
4329
  if (!newRequest) throw new Error("Request modifier must return request");
4019
4330
  }
4020
4331
  return newRequest;
@@ -4022,7 +4333,7 @@ var interceptRequest = async (interceptors, request) => {
4022
4333
  var interceptResponse = async (interceptors, response, request) => {
4023
4334
  let newResponse = response;
4024
4335
  if (!request.requestOptions.disableResponseInterceptors) for (const interceptor of interceptors) {
4025
- newResponse = await interceptor(response, request);
4336
+ newResponse = await interceptor(newResponse, request);
4026
4337
  if (!newResponse) throw new Error("Response modifier must return data");
4027
4338
  }
4028
4339
  return newResponse;
@@ -4030,6 +4341,35 @@ var interceptResponse = async (interceptors, response, request) => {
4030
4341
  //#endregion
4031
4342
  //#region src/client/client.ts
4032
4343
  /**
4344
+ * Response interceptors run when the adapter is already done, so nothing else can handle their failure.
4345
+ * A throwing or rejecting interceptor ends the request with the error response - the same way as failing request
4346
+ * interceptors do - instead of leaving it pending forever.
4347
+ */
4348
+ var interceptResponseSafely = async ({ client, interceptors, response, request }) => {
4349
+ try {
4350
+ return await interceptResponse(interceptors, response, request);
4351
+ } catch (error) {
4352
+ const { adapter } = client;
4353
+ client.logger.error({
4354
+ title: "Response interceptor failed",
4355
+ type: "system",
4356
+ extra: {
4357
+ error,
4358
+ request
4359
+ }
4360
+ });
4361
+ return {
4362
+ data: null,
4363
+ error: adapter.unstable_internalErrorMapping(error),
4364
+ status: adapter.systemErrorStatus,
4365
+ success: false,
4366
+ extra: adapter.systemErrorExtra,
4367
+ requestTimestamp: response.requestTimestamp,
4368
+ responseTimestamp: response.responseTimestamp
4369
+ };
4370
+ }
4371
+ };
4372
+ /**
4033
4373
  * **Client** is a class that allows you to configure the connection with the server and then use it to create
4034
4374
  * requests. It allows you to set global defaults for the requests configuration, query params configuration.
4035
4375
  * It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,
@@ -4117,7 +4457,7 @@ var Client = class {
4117
4457
  */
4118
4458
  setLogger = (callback) => {
4119
4459
  this.loggerManager = callback(this);
4120
- this.loggerManager.initialize(this, "Client");
4460
+ this.logger = this.loggerManager.initialize(this, "Client");
4121
4461
  return this;
4122
4462
  };
4123
4463
  /**
@@ -4227,7 +4567,20 @@ var Client = class {
4227
4567
  triggerPlugins = (key, data) => {
4228
4568
  if (this.plugins.length === 0) return this;
4229
4569
  this.plugins.forEach((plugin) => {
4230
- plugin.trigger(key, data);
4570
+ try {
4571
+ plugin.trigger(key, data);
4572
+ } catch (error) {
4573
+ this.logger.error({
4574
+ title: `Plugin "${plugin.name}" failed`,
4575
+ type: "system",
4576
+ extra: {
4577
+ plugin: plugin.name,
4578
+ method: key,
4579
+ error
4580
+ }
4581
+ });
4582
+ throwOutsideLifecycle(error);
4583
+ }
4231
4584
  });
4232
4585
  return this;
4233
4586
  };
@@ -4268,17 +4621,32 @@ var Client = class {
4268
4621
  * Private helper to run async on-error response processing
4269
4622
  * @private
4270
4623
  */
4271
- unstable_modifyErrorResponse = async (response, request) => interceptResponse(this.unstable_onErrorCallbacks, response, request);
4624
+ unstable_modifyErrorResponse = async (response, request) => interceptResponseSafely({
4625
+ client: this,
4626
+ interceptors: this.unstable_onErrorCallbacks,
4627
+ response,
4628
+ request
4629
+ });
4272
4630
  /**
4273
4631
  * Private helper to run async on-success response processing
4274
4632
  * @private
4275
4633
  */
4276
- unstable_modifySuccessResponse = async (response, request) => interceptResponse(this.unstable_onSuccessCallbacks, response, request);
4634
+ unstable_modifySuccessResponse = async (response, request) => interceptResponseSafely({
4635
+ client: this,
4636
+ interceptors: this.unstable_onSuccessCallbacks,
4637
+ response,
4638
+ request
4639
+ });
4277
4640
  /**
4278
4641
  * Private helper to run async response processing
4279
4642
  * @private
4280
4643
  */
4281
- unstable_modifyResponse = async (response, request) => interceptResponse(this.unstable_onResponseCallbacks, response, request);
4644
+ unstable_modifyResponse = async (response, request) => interceptResponseSafely({
4645
+ client: this,
4646
+ interceptors: this.unstable_onResponseCallbacks,
4647
+ response,
4648
+ request
4649
+ });
4282
4650
  /**
4283
4651
  * Reconstruct a Request class instance from its serialized JSON form.
4284
4652
  * Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage)
@@ -4292,6 +4660,14 @@ var Client = class {
4292
4660
  */
4293
4661
  clear = () => {
4294
4662
  const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
4663
+ [this.fetchDispatcher, this.submitDispatcher].forEach((dispatcher) => {
4664
+ dispatcher.getQueuesKeys().forEach((queryKey) => {
4665
+ dispatcher.getQueue(queryKey).requests.forEach(({ request, requestId }) => {
4666
+ dispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
4667
+ });
4668
+ });
4669
+ });
4670
+ this.requestManager.abortAll();
4295
4671
  this.requestManager.abortControllers.clear();
4296
4672
  this.fetchDispatcher.clear();
4297
4673
  this.submitDispatcher.clear();
@@ -4301,6 +4677,7 @@ var Client = class {
4301
4677
  this.submitDispatcher.emitter.removeAllListeners();
4302
4678
  this.cache.emitter.removeAllListeners();
4303
4679
  this.appManager.unmount();
4680
+ this.appManager.emitter.removeAllListeners();
4304
4681
  this.cache = cache?.() || new Cache();
4305
4682
  this.appManager = appManager?.() || new AppManager();
4306
4683
  this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();
@@ -4340,7 +4717,16 @@ var Client = class {
4340
4717
  ...config,
4341
4718
  cacheKey,
4342
4719
  scope
4343
- }, parsedData);
4720
+ }, {
4721
+ retries: 0,
4722
+ isCanceled: false,
4723
+ isOffline: false,
4724
+ willRetry: false,
4725
+ addedTimestamp: parsedData?.requestTimestamp,
4726
+ triggerTimestamp: parsedData?.requestTimestamp,
4727
+ ...parsedData,
4728
+ hydrated: true
4729
+ });
4344
4730
  });
4345
4731
  };
4346
4732
  /**
@@ -4780,6 +5166,6 @@ var fetchInfinite = async (request, options) => {
4780
5166
  return result;
4781
5167
  };
4782
5168
  //#endregion
4783
- export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, runResponseMapper, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
5169
+ export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, runResponseMapper, runUserCode, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, xhrExtra };
4784
5170
 
4785
5171
  //# sourceMappingURL=index.mjs.map