@hyper-fetch/core 9.5.1 → 9.5.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.
package/dist/index.mjs CHANGED
@@ -1870,8 +1870,42 @@ var getRequestDispatcher = (request, dispatcherType = "auto") => {
1870
1870
  const isFetchDispatcher = dispatcherType === "auto" && isSafeRead || dispatcherType === "fetch";
1871
1871
  return [isFetchDispatcher ? fetchDispatcher : submitDispatcher, isFetchDispatcher];
1872
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
+ };
1873
1907
  var mapResponseForSend = async (request, response) => {
1874
- const mapping = request.unstable_responseMapper?.(response);
1908
+ const mapping = runResponseMapper(request, response);
1875
1909
  if (mapping instanceof Promise) return await mapping;
1876
1910
  return mapping || response;
1877
1911
  };
@@ -1947,7 +1981,7 @@ var sendRequest = async (request, options) => {
1947
1981
  };
1948
1982
  const mappings = /* @__PURE__ */ new WeakMap();
1949
1983
  const getMapping = (values) => {
1950
- if (!mappings.has(values)) mappings.set(values, request.unstable_responseMapper?.(values.response));
1984
+ if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
1951
1985
  return mappings.get(values);
1952
1986
  };
1953
1987
  const unmountSettlement = mutationContext ? requestManager.events.onResponseById(requestId, (values) => {
@@ -3021,6 +3055,7 @@ var Dispatcher = class {
3021
3055
  storage = /* @__PURE__ */ new Map();
3022
3056
  requestCount = /* @__PURE__ */ new Map();
3023
3057
  runningRequests = /* @__PURE__ */ new Map();
3058
+ retryTimers = /* @__PURE__ */ new Map();
3024
3059
  logger;
3025
3060
  client;
3026
3061
  constructor(options) {
@@ -3164,10 +3199,11 @@ var Dispatcher = class {
3164
3199
  * Clear requests from queue cache
3165
3200
  */
3166
3201
  clearQueue = (queryKey) => {
3202
+ const queue = this.getQueue(queryKey);
3167
3203
  const newQueue = {
3168
3204
  queryKey,
3169
3205
  requests: [],
3170
- stopped: this.getQueue(queryKey).stopped
3206
+ stopped: queue.stopped
3171
3207
  };
3172
3208
  this.storage.set(queryKey, newQueue);
3173
3209
  this.client.triggerPlugins("onDispatcherQueueCleared", {
@@ -3176,6 +3212,7 @@ var Dispatcher = class {
3176
3212
  });
3177
3213
  this.events.emitQueueChanged(newQueue);
3178
3214
  this.events.emitDrained(newQueue);
3215
+ this.removeWaitingRetries(queue);
3179
3216
  return newQueue;
3180
3217
  };
3181
3218
  /**
@@ -3218,13 +3255,38 @@ var Dispatcher = class {
3218
3255
  * Clear all running requests and storage
3219
3256
  */
3220
3257
  clear = () => {
3221
- this.getQueuesKeys().forEach((queryKey) => this.cancelRunningRequests(queryKey));
3258
+ const keys = this.getQueuesKeys();
3259
+ const queues = keys.map((queryKey) => this.getQueue(queryKey));
3260
+ keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));
3222
3261
  [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));
3223
3262
  this.runningRequests.clear();
3224
3263
  this.storage.clear();
3264
+ queues.forEach((queue) => this.removeWaitingRetries(queue));
3225
3265
  this.client.triggerPlugins("onDispatcherCleared", { dispatcher: this });
3226
3266
  };
3227
3267
  /**
3268
+ * Drop the scheduled retry of the request
3269
+ */
3270
+ cancelRetry = (requestId) => {
3271
+ const timer = this.retryTimers.get(requestId);
3272
+ if (timer === void 0) return false;
3273
+ clearTimeout(timer);
3274
+ return this.retryTimers.delete(requestId);
3275
+ };
3276
+ /**
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
+ /**
3228
3290
  * Start particular request
3229
3291
  */
3230
3292
  startRequest = (queryKey, requestId) => {
@@ -3424,6 +3486,7 @@ var Dispatcher = class {
3424
3486
  const queue = this.getQueue(queryKey);
3425
3487
  const queueItem = queue.requests.find((req) => req.requestId === requestId);
3426
3488
  if (!queueItem) return;
3489
+ this.cancelRetry(requestId);
3427
3490
  queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
3428
3491
  this.storage.set(queryKey, queue);
3429
3492
  if (this.hasRunningRequest(queryKey, requestId)) {
@@ -3607,7 +3670,27 @@ var Dispatcher = class {
3607
3670
  request
3608
3671
  }
3609
3672
  });
3610
- setTimeout(() => {
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
3691
+ });
3692
+ return;
3693
+ }
3611
3694
  this.logger.warning({
3612
3695
  title: "Error response, performing retry",
3613
3696
  type: "request",
@@ -3623,6 +3706,7 @@ var Dispatcher = class {
3623
3706
  retries: storageItem.retries + 1
3624
3707
  });
3625
3708
  }, retryTime || 0);
3709
+ this.retryTimers.set(requestId, retryTimer);
3626
3710
  } else {
3627
3711
  if (request.retry) this.logger.error({
3628
3712
  title: "All retries have been used. Removing request from queue.",
@@ -4432,6 +4516,6 @@ var createConfiguration = () => {
4432
4516
  return (defaults) => defaults;
4433
4517
  };
4434
4518
  //#endregion
4435
- 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, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, 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, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
4519
+ 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, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, 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 };
4436
4520
 
4437
4521
  //# sourceMappingURL=index.mjs.map