@hyper-fetch/core 10.0.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +126 -86
  2. package/__tests__/features/adapter/adapter.base.spec.ts +32 -0
  3. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +14 -0
  4. package/__tests__/features/adapter/adapter.bindings.spec.ts +17 -0
  5. package/__tests__/features/adapter/adapter.query-params-resolver.spec.ts +93 -0
  6. package/__tests__/features/adapter/adapter.server.spec.ts +46 -0
  7. package/__tests__/features/cache/cache.timing.spec.ts +34 -12
  8. package/__tests__/features/dispatcher/dispatcher.cancel.spec.ts +72 -0
  9. package/__tests__/features/dispatcher/dispatcher.lazy-storage.spec.ts +237 -0
  10. package/__tests__/features/dispatcher/dispatcher.persistence.spec.ts +187 -0
  11. package/__tests__/features/dispatcher/dispatcher.retry-time.spec.ts +142 -0
  12. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +146 -0
  13. package/__tests__/features/managers/app/app.manager.events.spec.ts +46 -1
  14. package/__tests__/features/request/request.inference.spec.ts +78 -0
  15. package/__tests__/features/sdk/sdk.base.spec.ts +39 -0
  16. package/__tests__/features/sdk/sdk.request-fields.spec.ts +23 -0
  17. package/__tests__/features/sdk/sdk.types.spec.ts +28 -1
  18. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  19. package/dist/adapter/adapter.d.ts +18 -0
  20. package/dist/adapter/adapter.d.ts.map +1 -1
  21. package/dist/cache/cache.d.ts +2 -1
  22. package/dist/cache/cache.d.ts.map +1 -1
  23. package/dist/client/client.d.ts +2 -2
  24. package/dist/client/client.d.ts.map +1 -1
  25. package/dist/dispatcher/dispatcher.d.ts +28 -1
  26. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  27. package/dist/dispatcher/dispatcher.types.d.ts +17 -0
  28. package/dist/dispatcher/dispatcher.types.d.ts.map +1 -1
  29. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  30. package/dist/http-adapter/http-adapter.types.d.ts +12 -0
  31. package/dist/http-adapter/http-adapter.types.d.ts.map +1 -1
  32. package/dist/index.mjs +280 -42
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/managers/app/app.manager.d.ts +5 -0
  35. package/dist/managers/app/app.manager.d.ts.map +1 -1
  36. package/dist/managers/request/request.manager.d.ts +7 -0
  37. package/dist/managers/request/request.manager.d.ts.map +1 -1
  38. package/dist/request/request.d.ts +3 -3
  39. package/dist/request/request.d.ts.map +1 -1
  40. package/dist/request/request.types.d.ts +45 -7
  41. package/dist/request/request.types.d.ts.map +1 -1
  42. package/dist/request/request.utils.d.ts +26 -1
  43. package/dist/request/request.utils.d.ts.map +1 -1
  44. package/dist/sdk/sdk.d.ts +22 -3
  45. package/dist/sdk/sdk.d.ts.map +1 -1
  46. package/package.json +1 -1
  47. package/src/adapter/adapter.bindings.ts +5 -3
  48. package/src/adapter/adapter.ts +24 -1
  49. package/src/cache/cache.ts +5 -2
  50. package/src/client/client.ts +10 -3
  51. package/src/dispatcher/dispatcher.ts +161 -6
  52. package/src/dispatcher/dispatcher.types.ts +18 -0
  53. package/src/http-adapter/http-adapter.fetch.ts +76 -19
  54. package/src/http-adapter/http-adapter.types.ts +13 -0
  55. package/src/managers/app/app.manager.ts +17 -2
  56. package/src/managers/request/request.manager.ts +15 -1
  57. package/src/request/request.ts +5 -4
  58. package/src/request/request.types.ts +71 -11
  59. package/src/request/request.utils.ts +55 -0
  60. package/src/sdk/sdk.ts +33 -3
package/dist/index.mjs CHANGED
@@ -455,7 +455,7 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
455
455
  const progressTimestamp = Date.now();
456
456
  responseTotal = getTotal(responseTotal, progress);
457
457
  handleResponseProgress(responseStartTimestamp, progressTimestamp, {
458
- total: progress.total || responseTotal,
458
+ total: responseTotal,
459
459
  loaded: progress.loaded || 0
460
460
  });
461
461
  return progressTimestamp;
@@ -545,7 +545,7 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
545
545
  }
546
546
  });
547
547
  return onError({
548
- error: getErrorMessage("timeout"),
548
+ error: internalErrorMapping(getErrorMessage("timeout")),
549
549
  status,
550
550
  extra
551
551
  });
@@ -560,7 +560,7 @@ var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onSt
560
560
  }
561
561
  });
562
562
  return onError({
563
- error: getErrorMessage(),
563
+ error: internalErrorMapping(getErrorMessage()),
564
564
  status,
565
565
  extra
566
566
  });
@@ -826,6 +826,11 @@ var Adapter = class {
826
826
  unstable_endpointMapper = defaultMapper;
827
827
  /** Method to get request data and transform them to the required format. */
828
828
  unstable_queryParamsMapper = defaultMapper;
829
+ /**
830
+ * Turns query params given as a callback into data, at the moment they are set on a request. Unset by default, so
831
+ * adapters without it store query params as given. See {@link Adapter.setQueryParamsResolver}.
832
+ */
833
+ unstable_queryParamsResolver = void 0;
829
834
  /** Get default adapter options for the request. */
830
835
  unstable_getAdapterDefaults = void 0;
831
836
  /** Get default request options for the request. */
@@ -902,6 +907,22 @@ var Adapter = class {
902
907
  this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
903
908
  return this;
904
909
  };
910
+ /**
911
+ * Let requests take query params as a callback. When a request gets a function as its query params (in
912
+ * `createRequest`, `setQueryParams` or `send`), the resolver runs right away and the request stores what it returns,
913
+ * so cache keys, query keys and `toJSON()` only ever see data. The resolver decides what the callback receives.
914
+ *
915
+ * Opt-in: adapters without a resolver store query params as given. Declare the callback in the adapter's query params
916
+ * type so requests accept it.
917
+ *
918
+ * @example
919
+ * // The Firebase adapter passes a constraints builder and stores the constraints it collected
920
+ * adapter.setQueryParamsResolver((callback) => callback(createConstraints()).toJSON());
921
+ */
922
+ setQueryParamsResolver = (resolver) => {
923
+ this.unstable_queryParamsResolver = resolver;
924
+ return this;
925
+ };
905
926
  /** Set the configuration object passed as the second argument to the query params mapper. */
906
927
  setQueryParamsMapperConfig = (config) => {
907
928
  this.unstable_queryParamsMapperConfig = config;
@@ -954,7 +975,7 @@ var Adapter = class {
954
975
  }
955
976
  });
956
977
  if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
957
- return this.unstable_fetcher(bindings);
978
+ return await this.unstable_fetcher(bindings);
958
979
  } catch (error) {
959
980
  return getAdapterOnError({
960
981
  request,
@@ -1864,6 +1885,15 @@ var resetOptimisticState = (client) => {
1864
1885
  };
1865
1886
  //#endregion
1866
1887
  //#region src/request/request.utils.ts
1888
+ /**
1889
+ * Turns query params given as a callback into data with the adapter's resolver, so a request never stores a function.
1890
+ * Without a resolver the value is kept as given.
1891
+ */
1892
+ var resolveQueryParams = (client, queryParams) => {
1893
+ const resolver = client.adapter.unstable_queryParamsResolver;
1894
+ if (typeof queryParams === "function" && resolver) return resolver(queryParams);
1895
+ return queryParams;
1896
+ };
1867
1897
  var scopeKey = (key, scope) => {
1868
1898
  return scope ? `${scope}__${key}` : key;
1869
1899
  };
@@ -2154,6 +2184,25 @@ var sendRequest = async (request, options) => {
2154
2184
  }
2155
2185
  });
2156
2186
  };
2187
+ /** Above this exponent `min * 2 ** attempt` is past any sane maximum, and a larger one only risks Infinity */
2188
+ var MAX_BACKOFF_EXPONENT = 30;
2189
+ /**
2190
+ * Retry time that grows exponentially with every attempt: `min * 2 ** attempt`, never above `max`. With `jitter` (the
2191
+ * default) the delay is a random value from `min` up to that window, so the clients that failed together do not all
2192
+ * retry at the same moment.
2193
+ *
2194
+ * @example
2195
+ * client.createRequest()({ endpoint: "/users", retry: 5, retryTime: exponentialBackoff({ min: 500, max: 10_000 }) });
2196
+ */
2197
+ var exponentialBackoff = ({ min = 500, max = 3e4, jitter = true, random = Math.random } = {}) => {
2198
+ return ({ attempt }) => {
2199
+ const floor = Math.max(0, min);
2200
+ const exponential = floor * 2 ** Math.min(Math.max(0, attempt), MAX_BACKOFF_EXPONENT);
2201
+ if (!jitter) return Math.min(max, exponential);
2202
+ const window = Math.max(0, Math.min(max - floor, exponential));
2203
+ return Math.round(floor + random() * window);
2204
+ };
2205
+ };
2157
2206
  //#endregion
2158
2207
  //#region src/request/request.ts
2159
2208
  /**
@@ -2248,7 +2297,7 @@ var Request = class Request {
2248
2297
  this.method = method;
2249
2298
  this.params = initialRequestConfiguration?.params;
2250
2299
  this.payload = initialRequestConfiguration?.payload;
2251
- this.queryParams = initialRequestConfiguration?.queryParams;
2300
+ this.queryParams = resolveQueryParams(client, initialRequestConfiguration?.queryParams);
2252
2301
  this.options = initialRequestConfiguration?.options ?? options;
2253
2302
  this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;
2254
2303
  this.retry = initialRequestConfiguration?.retry ?? retry;
@@ -2313,7 +2362,7 @@ var Request = class Request {
2313
2362
  setRetry = (retry) => {
2314
2363
  return this.clone({ retry });
2315
2364
  };
2316
- /** Set the delay in milliseconds between retry attempts. */
2365
+ /** Set the delay in milliseconds between retry attempts, or a function that returns it for each attempt. */
2317
2366
  setRetryTime = (retryTime) => {
2318
2367
  return this.clone({ retryTime });
2319
2368
  };
@@ -2752,7 +2801,8 @@ var Cache = class {
2752
2801
  this.events.emitCacheData(newCacheData);
2753
2802
  };
2754
2803
  /**
2755
- * Update the cache data with partial response data
2804
+ * Update the cache data with partial response data. The `responseTimestamp` is set to the time of the update, so
2805
+ * the `cacheTime` and `staleTime` count from the update. Use `set` to store the data with another timestamp.
2756
2806
  * @param request
2757
2807
  * @param partialResponse
2758
2808
  * @returns
@@ -2772,7 +2822,8 @@ var Cache = class {
2772
2822
  const processedResponse = typeof partialResponse === "function" ? partialResponse(cachedData || null) : partialResponse;
2773
2823
  if (cachedData) this.set(request, {
2774
2824
  ...cachedData,
2775
- ...processedResponse
2825
+ ...processedResponse,
2826
+ responseTimestamp: Date.now()
2776
2827
  });
2777
2828
  };
2778
2829
  /**
@@ -3196,13 +3247,98 @@ var Dispatcher = class {
3196
3247
  sentCount = 0;
3197
3248
  /** Cache element (by its storage key) to the order number of the request whose data it holds */
3198
3249
  cachedOrder = /* @__PURE__ */ new Map();
3250
+ /** Sends the queue restored from the storage once the client is configured */
3251
+ startTimer;
3252
+ /** Operations of the lazy storage run one after another, so it always ends with the latest state of the queues */
3253
+ lazyOperations = Promise.resolve();
3199
3254
  logger;
3200
3255
  client;
3201
3256
  constructor(options) {
3202
3257
  this.options = options;
3203
3258
  this.emitter?.setMaxListeners(1e3);
3204
3259
  if (this.options?.storage) this.storage = this.options.storage;
3260
+ if (this.options?.lazyStorage) this.storage = this.withLazyStorage(this.storage, this.options.lazyStorage);
3205
3261
  }
3262
+ /**
3263
+ * Lazy storage is an external resource - its failures are logged, they must not take the requests down
3264
+ */
3265
+ runLazyOperation = (action, queryKey, operation) => {
3266
+ this.lazyOperations = this.lazyOperations.then(async () => {
3267
+ try {
3268
+ await operation();
3269
+ } catch (error) {
3270
+ this.logger?.error({
3271
+ title: `Lazy storage "${action}" failed`,
3272
+ type: "system",
3273
+ extra: {
3274
+ queryKey,
3275
+ error
3276
+ }
3277
+ });
3278
+ }
3279
+ });
3280
+ };
3281
+ /**
3282
+ * Snapshot of the queue as JSON data - taken right away, as the queue objects change after the write is scheduled
3283
+ */
3284
+ getLazyQueueData = (queue) => {
3285
+ return JSON.parse(JSON.stringify({
3286
+ ...queue,
3287
+ requests: queue.requests.map((item) => ({
3288
+ ...item,
3289
+ request: this.isRequestJSON(item.request) ? item.request : item.request.toJSON()
3290
+ }))
3291
+ }));
3292
+ };
3293
+ /**
3294
+ * The sync storage stays the source of truth, its changes are written through to the lazy storage
3295
+ */
3296
+ withLazyStorage = (storage, lazyStorage) => ({
3297
+ get: (key) => storage.get(key),
3298
+ keys: () => storage.keys(),
3299
+ entries: () => storage.entries(),
3300
+ set: (key, data) => {
3301
+ storage.set(key, data);
3302
+ const snapshot = this.getLazyQueueData(data);
3303
+ this.runLazyOperation("set", key, () => lazyStorage.set(key, snapshot));
3304
+ },
3305
+ delete: (key) => {
3306
+ storage.delete(key);
3307
+ this.runLazyOperation("delete", key, () => lazyStorage.delete(key));
3308
+ },
3309
+ clear: () => {
3310
+ storage.clear();
3311
+ this.runLazyOperation("clear", null, async () => {
3312
+ const keys = [...await lazyStorage.keys()];
3313
+ await Promise.all(keys.map((key) => lazyStorage.delete(key)));
3314
+ });
3315
+ }
3316
+ });
3317
+ /**
3318
+ * Reads the queues persisted by the previous run. Persisted requests are older than the ones added since the start,
3319
+ * so they go first. Requests already in the queue are not added twice.
3320
+ */
3321
+ restoreLazyQueues = (lazyStorage) => {
3322
+ this.runLazyOperation("restore", null, async () => {
3323
+ const keys = [...await lazyStorage.keys()];
3324
+ (await Promise.all(keys.map(async (key) => [key, await lazyStorage.get(key)]))).forEach(([queryKey, persisted]) => {
3325
+ if (!persisted?.requests.length) return;
3326
+ const queue = this.getQueue(queryKey);
3327
+ const knownIds = new Set(queue.requests.map((item) => item.requestId));
3328
+ const restored = persisted.requests.filter((item) => !knownIds.has(item.requestId)).map((item) => ({
3329
+ ...item,
3330
+ request: this.isRequestJSON(item.request) ? this.client.fromJSON(item.request) : item.request
3331
+ }));
3332
+ if (restored.length) {
3333
+ this.setQueue(queryKey, {
3334
+ ...queue,
3335
+ requests: [...restored, ...queue.requests]
3336
+ });
3337
+ this.flushQueue(queryKey);
3338
+ }
3339
+ });
3340
+ });
3341
+ };
3206
3342
  isRequestJSON = (request) => {
3207
3343
  return !(request instanceof Request);
3208
3344
  };
@@ -3212,6 +3348,12 @@ var Dispatcher = class {
3212
3348
  this.client.appManager.events.onOnline(() => {
3213
3349
  this.flush();
3214
3350
  });
3351
+ if (this.options?.lazyStorage) this.restoreLazyQueues(this.options.lazyStorage);
3352
+ clearTimeout(this.startTimer);
3353
+ if (this.getQueuesKeys().length) this.startTimer = setTimeout(() => {
3354
+ this.startTimer = void 0;
3355
+ this.flush();
3356
+ });
3215
3357
  return this;
3216
3358
  };
3217
3359
  /**
@@ -3374,11 +3516,12 @@ var Dispatcher = class {
3374
3516
  };
3375
3517
  /**
3376
3518
  * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,
3377
- * not just answered and - for the requests kept for later with the `offline` option - when there is a connection
3519
+ * not just answered and - for the requests kept for later with the `offline` option - when there is a connection.
3520
+ * Nothing is sent while the page unloads - the browser would cancel it right away.
3378
3521
  */
3379
3522
  canPerformRequest = (item, runningIds) => {
3380
3523
  const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;
3381
- return !item.stopped && !isWaitingForNetwork && !this.retryTimers.has(item.requestId) && !this.answeredRequests.has(item.requestId) && !runningIds.has(item.requestId);
3524
+ return !this.client.appManager.isUnloading && !item.stopped && !isWaitingForNetwork && !this.retryTimers.has(item.requestId) && !this.answeredRequests.has(item.requestId) && !runningIds.has(item.requestId);
3382
3525
  };
3383
3526
  /**
3384
3527
  * Method used to flush the queue requests
@@ -3425,6 +3568,8 @@ var Dispatcher = class {
3425
3568
  * Clear all running requests and storage
3426
3569
  */
3427
3570
  clear = () => {
3571
+ clearTimeout(this.startTimer);
3572
+ this.startTimer = void 0;
3428
3573
  const keys = this.getQueuesKeys();
3429
3574
  const removed = keys.map((queryKey) => ({
3430
3575
  items: this.getQueue(queryKey).requests,
@@ -3708,6 +3853,31 @@ var Dispatcher = class {
3708
3853
  }
3709
3854
  };
3710
3855
  /**
3856
+ * Delay of the next attempt from the `retryTime` of the request. The function form belongs to the user - when it
3857
+ * throws, the request is not retried (`null`). Anything but a positive finite delay retries right away.
3858
+ */
3859
+ getRetryDelay = (request, attempt, response) => {
3860
+ const { retryTime } = request;
3861
+ let delay = retryTime;
3862
+ if (typeof retryTime === "function") try {
3863
+ delay = retryTime({
3864
+ attempt,
3865
+ response
3866
+ });
3867
+ } catch (error) {
3868
+ this.logger.error({
3869
+ title: "The retryTime callback failed",
3870
+ type: "system",
3871
+ extra: {
3872
+ error,
3873
+ request
3874
+ }
3875
+ });
3876
+ return null;
3877
+ }
3878
+ return typeof delay === "number" && Number.isFinite(delay) && delay > 0 ? delay : 0;
3879
+ };
3880
+ /**
3711
3881
  * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
3712
3882
  * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
3713
3883
  */
@@ -3721,7 +3891,7 @@ var Dispatcher = class {
3721
3891
  requestId
3722
3892
  }
3723
3893
  });
3724
- const { retry, retryTime, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;
3894
+ const { retry, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;
3725
3895
  const queryKey = scopeKey(rawQueryKey, scope);
3726
3896
  const abortKey = scopeKey(rawAbortKey, scope);
3727
3897
  const { adapter, requestManager, cache, appManager } = this.client;
@@ -3752,15 +3922,18 @@ var Dispatcher = class {
3752
3922
  requestManager.addAbortController(abortKey, requestId);
3753
3923
  const response = await adapter.fetch(request, requestId);
3754
3924
  storageItem.resolved = true;
3925
+ const isAbortedByUser = requestManager.isCanceled(abortKey, requestId);
3755
3926
  requestManager.removeAbortController(abortKey, requestId);
3756
3927
  const isOfflineResponseStatus = !appManager.isOnline;
3757
3928
  const isCancelMessage = getErrorMessage("abort").message === response.error?.message;
3758
- const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;
3929
+ const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isAbortedByUser || isCancelMessage;
3930
+ const isUnloadFailure = !response.success && appManager.isUnloading;
3759
3931
  this.deleteRunningRequest(queryKey, requestId);
3760
3932
  this.answeredRequests.add(requestId);
3761
3933
  try {
3762
3934
  const isQueued = !!this.getRequest(queryKey, requestId);
3763
- const willRetry = !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus && this.getShouldRetryOnError(request, response);
3935
+ const retryDelay = !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus && !isUnloadFailure && this.getShouldRetryOnError(request, response) ? this.getRetryDelay(request, storageItem.retries, response) : null;
3936
+ const willRetry = retryDelay !== null;
3764
3937
  const requestDetails = {
3765
3938
  isCanceled,
3766
3939
  isOffline: isOfflineResponseStatus,
@@ -3866,6 +4039,15 @@ var Dispatcher = class {
3866
4039
  }
3867
4040
  });
3868
4041
  }
4042
+ if (isUnloadFailure) return this.logger.debug({
4043
+ title: "Page is unloading, keeping the request for the next start",
4044
+ type: "system",
4045
+ extra: {
4046
+ response,
4047
+ requestDetails,
4048
+ request
4049
+ }
4050
+ });
3869
4051
  if (!response.success && isOfflineResponseStatus) {
3870
4052
  if (!offline) {
3871
4053
  this.logger.warning({
@@ -3951,7 +4133,7 @@ var Dispatcher = class {
3951
4133
  retries
3952
4134
  });
3953
4135
  this.flushQueue(queryKey);
3954
- }, retryTime || 0);
4136
+ }, retryDelay);
3955
4137
  this.retryTimers.set(requestId, retryTimer);
3956
4138
  } else {
3957
4139
  if (request.retry) this.logger.error({
@@ -4125,6 +4307,28 @@ var stringifyQueryParams = (queryParams, options) => {
4125
4307
  //#endregion
4126
4308
  //#region src/http-adapter/http-adapter.fetch.ts
4127
4309
  var defaultExtra = xhrExtra;
4310
+ /**
4311
+ * Size in bytes of a body that fetch sends as it is. Form data and streams get their size from the browser while they
4312
+ * are sent, so it is unknown up front.
4313
+ */
4314
+ var getBodySize = (body) => {
4315
+ if (typeof body === "string") return new Blob([body]).size;
4316
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
4317
+ if (body instanceof ArrayBuffer) return body.byteLength;
4318
+ if (ArrayBuffer.isView(body)) return body.byteLength;
4319
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return new Blob([body.toString()]).size;
4320
+ };
4321
+ /**
4322
+ * Body of a successful response in the shape picked with the `responseType` option
4323
+ */
4324
+ var readResponseBody = (bytes, responseType, contentType) => {
4325
+ switch (responseType) {
4326
+ case "arrayBuffer": return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
4327
+ case "blob": return new Blob([bytes], { type: contentType ?? "" });
4328
+ case "text": return new TextDecoder().decode(bytes);
4329
+ default: return parseResponse(new TextDecoder().decode(bytes));
4330
+ }
4331
+ };
4128
4332
  var getAdapter = () => new Adapter({
4129
4333
  name: "http",
4130
4334
  defaultMethod: HttpMethods.GET,
@@ -4135,11 +4339,11 @@ var getAdapter = () => new Adapter({
4135
4339
  const method = options.method ?? HttpMethods.GET;
4136
4340
  if (SAFE_HTTP_METHODS.includes(method)) return { deduplicate: true };
4137
4341
  return {};
4138
- }).setFetcher(async ({ request, url, endpoint, queryParams, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
4342
+ }).setFetcher(async ({ request, url, endpoint, queryParams, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess }) => {
4139
4343
  const { method } = request;
4140
4344
  const fullUrl = `${url}${endpoint}${queryParams}`;
4141
4345
  const controller = getAbortController();
4142
- const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};
4346
+ const { timeout: timeoutMs = defaultTimeout, streaming = false, responseType, ...restOptions } = adapterOptions || {};
4143
4347
  let timedOut = false;
4144
4348
  let timeoutId;
4145
4349
  const unmountListener = createAbortListener({
@@ -4151,8 +4355,13 @@ var getAdapter = () => new Adapter({
4151
4355
  unmountListener();
4152
4356
  controller.abort();
4153
4357
  }, timeoutMs);
4358
+ const body = payload && method !== "GET" && method !== "HEAD" ? payload : void 0;
4359
+ const bodySize = getBodySize(body);
4154
4360
  onBeforeRequest();
4155
- onRequestStart();
4361
+ onRequestStart(bodySize ? {
4362
+ total: bodySize,
4363
+ loaded: 0
4364
+ } : void 0);
4156
4365
  try {
4157
4366
  const init = {
4158
4367
  method,
@@ -4160,18 +4369,9 @@ var getAdapter = () => new Adapter({
4160
4369
  signal: controller?.signal,
4161
4370
  ...restOptions
4162
4371
  };
4163
- if (payload && method !== "GET" && method !== "HEAD") {
4164
- init.body = payload;
4165
- if (typeof payload === "string") {
4166
- const total = new Blob([payload]).size;
4167
- onRequestProgress({
4168
- total,
4169
- loaded: total
4170
- });
4171
- }
4172
- }
4173
- onRequestEnd();
4372
+ if (body) init.body = body;
4174
4373
  const response = await fetch(fullUrl, init);
4374
+ onRequestEnd();
4175
4375
  if (timeoutId && streaming && response.body) clearTimeout(timeoutId);
4176
4376
  onResponseStart();
4177
4377
  const responseHeaders = {};
@@ -4197,7 +4397,8 @@ var getAdapter = () => new Adapter({
4197
4397
  let body;
4198
4398
  if (response.body && typeof response.body.getReader === "function") {
4199
4399
  const reader = response.body.getReader();
4200
- const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
4400
+ const contentEncoding = response.headers.get("content-encoding");
4401
+ const contentLength = !!contentEncoding && contentEncoding !== "identity" ? 0 : parseInt(response.headers.get("content-length") || "0", 10);
4201
4402
  let receivedLength = 0;
4202
4403
  const chunks = [];
4203
4404
  while (true) {
@@ -4216,18 +4417,26 @@ var getAdapter = () => new Adapter({
4216
4417
  allChunks.set(chunk, position);
4217
4418
  position += chunk.length;
4218
4419
  }
4219
- body = new TextDecoder().decode(allChunks);
4220
- } else body = await response.text();
4420
+ body = { bytes: allChunks };
4421
+ } else if (response.ok && responseType === "blob") body = { data: await response.blob() };
4422
+ else if (response.ok && responseType === "arrayBuffer") body = { data: await response.arrayBuffer() };
4423
+ else body = { text: await response.text() };
4221
4424
  if (timeoutId) clearTimeout(timeoutId);
4222
4425
  onResponseEnd();
4223
4426
  unmountListener();
4224
- if (response.ok) onSuccess({
4225
- data: parseResponse(body),
4226
- status,
4227
- extra
4228
- });
4229
- else onError({
4230
- error: parseErrorResponse(body),
4427
+ const getText = () => "text" in body ? body.text : new TextDecoder().decode("bytes" in body ? body.bytes : void 0);
4428
+ if (response.ok) {
4429
+ let data;
4430
+ if ("data" in body) data = body.data;
4431
+ else if ("bytes" in body) data = readResponseBody(body.bytes, responseType, response.headers.get("content-type"));
4432
+ else data = responseType === "text" ? body.text : parseResponse(body.text);
4433
+ onSuccess({
4434
+ data,
4435
+ status,
4436
+ extra
4437
+ });
4438
+ } else onError({
4439
+ error: parseErrorResponse(getText()),
4231
4440
  status,
4232
4441
  extra
4233
4442
  });
@@ -4271,6 +4480,11 @@ var AppManager = class {
4271
4480
  isBrowser;
4272
4481
  isOnline;
4273
4482
  isFocused;
4483
+ /**
4484
+ * True while the browser page is being unloaded (closed, reloaded or navigated away). The browser cancels the
4485
+ * requests in flight then - their failures are not real answers, so the dispatcher keeps them for the next start.
4486
+ */
4487
+ isUnloading = false;
4274
4488
  unmountCallbacks = [];
4275
4489
  hasFocusUpdate = false;
4276
4490
  hasOnlineUpdate = false;
@@ -4289,7 +4503,16 @@ var AppManager = class {
4289
4503
  initialize = () => {
4290
4504
  const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } = this.options || appManagerInitialOptions;
4291
4505
  this.unmount();
4292
- [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {
4506
+ [
4507
+ focusEvent(this.setFocused),
4508
+ onlineEvent(this.setOnline),
4509
+ onWindowEvent("pagehide", () => {
4510
+ this.isUnloading = true;
4511
+ }),
4512
+ onWindowEvent("pageshow", () => {
4513
+ this.isUnloading = false;
4514
+ })
4515
+ ].forEach((unmount) => {
4293
4516
  if (typeof unmount === "function") this.unmountCallbacks.push(unmount);
4294
4517
  });
4295
4518
  };
@@ -4477,6 +4700,8 @@ var RequestManager = class {
4477
4700
  this.emitter?.setMaxListeners(1e3);
4478
4701
  }
4479
4702
  abortControllers = /* @__PURE__ */ new Map();
4703
+ /** Controllers aborted through this manager, i.e. by the user and not by an adapter's own timeout */
4704
+ canceledControllers = /* @__PURE__ */ new WeakSet();
4480
4705
  addAbortController = (abortKey, requestId) => {
4481
4706
  let abortGroup = this.abortControllers.get(abortKey);
4482
4707
  if (!abortGroup) {
@@ -4496,7 +4721,19 @@ var RequestManager = class {
4496
4721
  if (abortGroup?.size === 0) this.abortControllers.delete(abortKey);
4497
4722
  };
4498
4723
  useAbortController = (abortKey, requestId) => {
4499
- (this.abortControllers.get(abortKey)?.get(requestId))?.abort();
4724
+ const controller = this.abortControllers.get(abortKey)?.get(requestId);
4725
+ if (controller) {
4726
+ this.canceledControllers.add(controller);
4727
+ controller.abort();
4728
+ }
4729
+ };
4730
+ /**
4731
+ * Whether the request was aborted on purpose (`request.abort()`, `abortByKey`...). Tells canceled requests apart
4732
+ * from failed ones whatever shape the adapter gives its errors.
4733
+ */
4734
+ isCanceled = (abortKey, requestId) => {
4735
+ const controller = this.abortControllers.get(abortKey)?.get(requestId);
4736
+ return !!controller && this.canceledControllers.has(controller);
4500
4737
  };
4501
4738
  abortByKey = (abortKey) => {
4502
4739
  const controllers = this.abortControllers.get(abortKey);
@@ -5349,7 +5586,8 @@ var createRecursiveProxy = (client, context) => {
5349
5586
  isMethod = true;
5350
5587
  methodName = key.slice(1);
5351
5588
  pathSegment = `:${key.slice(1)}`;
5352
- } else if (options?.camelCaseToKebabCase) pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
5589
+ } else if (options?.pathSegments && Object.prototype.hasOwnProperty.call(options.pathSegments, key)) pathSegment = options.pathSegments[key];
5590
+ else if (options?.camelCaseToKebabCase) pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
5353
5591
  const currentSdkKeys = [...sdkKeys, key];
5354
5592
  const sdkPath = currentSdkKeys.join(".");
5355
5593
  const endpoint = `/${path.join("/")}`;
@@ -5674,6 +5912,6 @@ var fetchInfinite = async (request, options) => {
5674
5912
  return result;
5675
5913
  };
5676
5914
  //#endregion
5677
- export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, OptimisticOperation, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, applyOptimistic, 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, getOptimisticResult, 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, incrementField, incrementItems, insertItem, interceptRequest, interceptResponse, isNavigatorOnline, isOptimisticMatch, isPlainObject, isStaleOptimisticResponse, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, optimistic, parseErrorResponse, parseResponse, patchItems, removeItems, replaceEqualDeep, resetOptimisticState, resolveClientMode, runResponseMapper, runUserCode, scopeKey, sendRequest, settleOptimistic, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, updateListField, xhrExtra };
5915
+ export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, OptimisticOperation, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, applyOptimistic, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, exponentialBackoff, 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, getOptimisticResult, 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, incrementField, incrementItems, insertItem, interceptRequest, interceptResponse, isNavigatorOnline, isOptimisticMatch, isPlainObject, isStaleOptimisticResponse, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, optimistic, parseErrorResponse, parseResponse, patchItems, removeItems, replaceEqualDeep, resetOptimisticState, resolveClientMode, resolveQueryParams, runResponseMapper, runUserCode, scopeKey, sendRequest, settleOptimistic, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, updateListField, xhrExtra };
5678
5916
 
5679
5917
  //# sourceMappingURL=index.mjs.map