@hyper-fetch/core 9.9.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
@@ -4,6 +4,7 @@ import { getErrorMessage } from "adapter";
4
4
  import type { ClientInstance } from "client";
5
5
  import type {
6
6
  QueueDataType,
7
+ DispatcherAsyncStorageType,
7
8
  DispatcherOptionsType,
8
9
  DispatcherStorageType,
9
10
  ResolvedQueueDataType,
@@ -38,6 +39,11 @@ export class Dispatcher<Adapter extends AdapterInstance> {
38
39
  /** Cache element (by its storage key) to the order number of the request whose data it holds */
39
40
  private cachedOrder = new Map<string, number>();
40
41
 
42
+ /** Sends the queue restored from the storage once the client is configured */
43
+ private startTimer: ReturnType<typeof setTimeout> | undefined;
44
+ /** Operations of the lazy storage run one after another, so it always ends with the latest state of the queues */
45
+ private lazyOperations: Promise<void> = Promise.resolve();
46
+
41
47
  private logger: LoggerMethods;
42
48
  private client: ClientInstance<{ adapter: Adapter }>;
43
49
 
@@ -47,8 +53,103 @@ export class Dispatcher<Adapter extends AdapterInstance> {
47
53
  if (this.options?.storage) {
48
54
  this.storage = this.options.storage;
49
55
  }
56
+ if (this.options?.lazyStorage) {
57
+ this.storage = this.withLazyStorage(this.storage, this.options.lazyStorage);
58
+ }
50
59
  }
51
60
 
61
+ // *********************************************************************
62
+ // *********************************************************************
63
+ // Lazy storage
64
+ // *********************************************************************
65
+ // *********************************************************************
66
+
67
+ /**
68
+ * Lazy storage is an external resource - its failures are logged, they must not take the requests down
69
+ */
70
+ private runLazyOperation = (action: string, queryKey: string | null, operation: () => Promise<void> | void) => {
71
+ this.lazyOperations = this.lazyOperations.then(async () => {
72
+ try {
73
+ await operation();
74
+ } catch (error) {
75
+ this.logger?.error({ title: `Lazy storage "${action}" failed`, type: "system", extra: { queryKey, error } });
76
+ }
77
+ });
78
+ };
79
+
80
+ /**
81
+ * Snapshot of the queue as JSON data - taken right away, as the queue objects change after the write is scheduled
82
+ */
83
+ private getLazyQueueData = (queue: QueueDataType): QueueDataType => {
84
+ return JSON.parse(
85
+ JSON.stringify({
86
+ ...queue,
87
+ requests: queue.requests.map((item) => ({
88
+ ...item,
89
+ request: this.isRequestJSON(item.request) ? item.request : item.request.toJSON(),
90
+ })),
91
+ }),
92
+ );
93
+ };
94
+
95
+ /**
96
+ * The sync storage stays the source of truth, its changes are written through to the lazy storage
97
+ */
98
+ private withLazyStorage = (
99
+ storage: DispatcherStorageType,
100
+ lazyStorage: DispatcherAsyncStorageType,
101
+ ): DispatcherStorageType => ({
102
+ get: (key) => storage.get(key),
103
+ keys: () => storage.keys(),
104
+ entries: () => storage.entries(),
105
+ set: (key, data) => {
106
+ storage.set(key, data);
107
+ const snapshot = this.getLazyQueueData(data as QueueDataType);
108
+ this.runLazyOperation("set", key, () => lazyStorage.set(key, snapshot));
109
+ },
110
+ delete: (key) => {
111
+ storage.delete(key);
112
+ this.runLazyOperation("delete", key, () => lazyStorage.delete(key));
113
+ },
114
+ clear: () => {
115
+ storage.clear();
116
+ this.runLazyOperation("clear", null, async () => {
117
+ const keys = [...(await lazyStorage.keys())];
118
+ await Promise.all(keys.map((key) => lazyStorage.delete(key)));
119
+ });
120
+ },
121
+ });
122
+
123
+ /**
124
+ * Reads the queues persisted by the previous run. Persisted requests are older than the ones added since the start,
125
+ * so they go first. Requests already in the queue are not added twice.
126
+ */
127
+ private restoreLazyQueues = (lazyStorage: DispatcherAsyncStorageType) => {
128
+ this.runLazyOperation("restore", null, async () => {
129
+ const keys = [...(await lazyStorage.keys())];
130
+ const persistedQueues = await Promise.all(keys.map(async (key) => [key, await lazyStorage.get(key)] as const));
131
+
132
+ persistedQueues.forEach(([queryKey, persisted]) => {
133
+ if (!persisted?.requests.length) {
134
+ return;
135
+ }
136
+ const queue = this.getQueue(queryKey);
137
+ const knownIds = new Set(queue.requests.map((item) => item.requestId));
138
+ const restored = persisted.requests
139
+ .filter((item) => !knownIds.has(item.requestId))
140
+ .map((item) => ({
141
+ ...item,
142
+ request: this.isRequestJSON(item.request) ? this.client.fromJSON(item.request) : item.request,
143
+ }));
144
+
145
+ if (restored.length) {
146
+ this.setQueue(queryKey, { ...queue, requests: [...restored, ...queue.requests] });
147
+ this.flushQueue(queryKey);
148
+ }
149
+ });
150
+ });
151
+ };
152
+
52
153
  // eslint-disable-next-line class-methods-use-this
53
154
  private isRequestJSON = (
54
155
  request: RequestInstance | RequestJSON<RequestInstance>,
@@ -65,6 +166,21 @@ export class Dispatcher<Adapter extends AdapterInstance> {
65
166
  this.flush();
66
167
  });
67
168
 
169
+ // A queue restored from a persistent storage (e.g. the requests left by the previous page load) has to be sent
170
+ // on start. It waits for the next task, so the configuration chained after the client constructor - adapter,
171
+ // interceptors, plugins - applies to the restored requests too.
172
+ if (this.options?.lazyStorage) {
173
+ this.restoreLazyQueues(this.options.lazyStorage);
174
+ }
175
+
176
+ clearTimeout(this.startTimer);
177
+ if (this.getQueuesKeys().length) {
178
+ this.startTimer = setTimeout(() => {
179
+ this.startTimer = undefined;
180
+ this.flush();
181
+ });
182
+ }
183
+
68
184
  return this;
69
185
  };
70
186
 
@@ -244,12 +360,14 @@ export class Dispatcher<Adapter extends AdapterInstance> {
244
360
 
245
361
  /**
246
362
  * A request can be sent when it is not in flight, not held by `stopRequest`, not waiting for its retry,
247
- * not just answered and - for the requests kept for later with the `offline` option - when there is a connection
363
+ * not just answered and - for the requests kept for later with the `offline` option - when there is a connection.
364
+ * Nothing is sent while the page unloads - the browser would cancel it right away.
248
365
  */
249
366
  private canPerformRequest = (item: ResolvedQueueItemType, runningIds: Set<string>) => {
250
367
  const isWaitingForNetwork = !this.client.appManager.isOnline && item.request.offline;
251
368
 
252
369
  return (
370
+ !this.client.appManager.isUnloading &&
253
371
  !item.stopped &&
254
372
  !isWaitingForNetwork &&
255
373
  !this.retryTimers.has(item.requestId) &&
@@ -313,6 +431,8 @@ export class Dispatcher<Adapter extends AdapterInstance> {
313
431
  * Clear all running requests and storage
314
432
  */
315
433
  clear = () => {
434
+ clearTimeout(this.startTimer);
435
+ this.startTimer = undefined;
316
436
  const keys = this.getQueuesKeys();
317
437
  // Running requests are canceled and report it on their own, the waiting ones are reported as removed
318
438
  const removed = keys.map((queryKey) => ({
@@ -647,6 +767,24 @@ export class Dispatcher<Adapter extends AdapterInstance> {
647
767
  }
648
768
  };
649
769
 
770
+ /**
771
+ * Delay of the next attempt from the `retryTime` of the request. The function form belongs to the user - when it
772
+ * throws, the request is not retried (`null`). Anything but a positive finite delay retries right away.
773
+ */
774
+ private getRetryDelay = (request: RequestInstance, attempt: number, response: RequestResponseType<any>) => {
775
+ const { retryTime } = request;
776
+ let delay: unknown = retryTime;
777
+ if (typeof retryTime === "function") {
778
+ try {
779
+ delay = retryTime({ attempt, response });
780
+ } catch (error) {
781
+ this.logger.error({ title: "The retryTime callback failed", type: "system", extra: { error, request } });
782
+ return null;
783
+ }
784
+ }
785
+ return typeof delay === "number" && Number.isFinite(delay) && delay > 0 ? delay : 0;
786
+ };
787
+
650
788
  /**
651
789
  * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
652
790
  * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
@@ -655,7 +793,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
655
793
  const { request, requestId } = storageItem;
656
794
  this.logger.debug({ title: "Performing request", type: "system", extra: { request, requestId } });
657
795
 
658
- const { retry, retryTime, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;
796
+ const { retry, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;
659
797
  const queryKey = scopeKey(rawQueryKey, scope);
660
798
  const abortKey = scopeKey(rawAbortKey, scope);
661
799
  const { adapter, requestManager, cache, appManager } = this.client;
@@ -699,6 +837,8 @@ export class Dispatcher<Adapter extends AdapterInstance> {
699
837
  // TODO: improve this
700
838
  // eslint-disable-next-line no-param-reassign
701
839
  storageItem.resolved = true;
840
+ // Read before the controller is dropped - adapters may map the abort error into any shape (GraphQL uses arrays)
841
+ const isAbortedByUser = requestManager.isCanceled(abortKey, requestId);
702
842
  // Stop listening for aborting
703
843
  requestManager.removeAbortController(abortKey, requestId);
704
844
  // Do not continue the request handling when it got stopped and request was unsuccessful
@@ -706,7 +846,9 @@ export class Dispatcher<Adapter extends AdapterInstance> {
706
846
  const isOfflineResponseStatus = !appManager.isOnline;
707
847
  // If there is no running request with this id, it means it was cancelled and removed during send
708
848
  const isCancelMessage = getErrorMessage("abort").message === response.error?.message;
709
- const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;
849
+ const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isAbortedByUser || isCancelMessage;
850
+ // The browser cancels the requests of an unloading page - the failure says nothing about the request itself
851
+ const isUnloadFailure = !response.success && appManager.isUnloading;
710
852
 
711
853
  // Remove running request, must be called after isCancelled
712
854
  this.deleteRunningRequest(queryKey, requestId);
@@ -717,8 +859,13 @@ export class Dispatcher<Adapter extends AdapterInstance> {
717
859
  try {
718
860
  // A request removed from the queue while it was running (cleared queue) has nothing left to retry
719
861
  const isQueued = !!this.getRequest(queryKey, requestId);
720
- const canRetryResponse = !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus;
721
- const willRetry = canRetryResponse && this.getShouldRetryOnError(request, response);
862
+ const canRetryResponse =
863
+ !response.success && canRetry && isQueued && !isCanceled && !isOfflineResponseStatus && !isUnloadFailure;
864
+ const retryDelay =
865
+ canRetryResponse && this.getShouldRetryOnError(request, response)
866
+ ? this.getRetryDelay(request, storageItem.retries, response)
867
+ : null;
868
+ const willRetry = retryDelay !== null;
722
869
 
723
870
  const requestDetails: ResponseDetailsType = {
724
871
  isCanceled,
@@ -812,6 +959,14 @@ export class Dispatcher<Adapter extends AdapterInstance> {
812
959
  extra: { response, requestDetails, request },
813
960
  });
814
961
  }
962
+ // On page unload - the request stays in the queue, a persistent storage sends it again on the next start
963
+ if (isUnloadFailure) {
964
+ return this.logger.debug({
965
+ title: "Page is unloading, keeping the request for the next start",
966
+ type: "system",
967
+ extra: { response, requestDetails, request },
968
+ });
969
+ }
815
970
  // On offline
816
971
  if (!response.success && isOfflineResponseStatus) {
817
972
  // if we don't want to keep offline request - just delete them
@@ -883,7 +1038,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
883
1038
  });
884
1039
  // Let the queue go on when it was held by this request
885
1040
  this.flushQueue(queryKey);
886
- }, retryTime || 0);
1041
+ }, retryDelay);
887
1042
  this.retryTimers.set(requestId, retryTimer);
888
1043
  } else {
889
1044
  if (request.retry) {
@@ -1,7 +1,14 @@
1
1
  import type { RequestInstance, RequestJSON } from "request";
2
2
 
3
3
  export type DispatcherOptionsType = {
4
+ /** Synchronous storage of the queues - the in-memory `Map` by default */
4
5
  storage?: DispatcherStorageType;
6
+ /**
7
+ * Asynchronous persistent storage of the queues - IndexedDB, AsyncStorage and similar. Every change of the queues is
8
+ * written to it as JSON data, in order. On start the dispatcher reads it, puts the persisted requests in front of the
9
+ * ones added meanwhile and sends them.
10
+ */
11
+ lazyStorage?: DispatcherAsyncStorageType;
5
12
  };
6
13
 
7
14
  // Values
@@ -47,6 +54,17 @@ export type DispatcherStorageType = {
47
54
  clear: () => void;
48
55
  };
49
56
 
57
+ /**
58
+ * Asynchronous storage of the queues. It receives plain JSON data - requests are saved with `request.toJSON()`, so
59
+ * their functions (mappers, a function `retryTime`) are not kept.
60
+ */
61
+ export type DispatcherAsyncStorageType = {
62
+ set: (key: string, data: QueueDataType) => Promise<void>;
63
+ get: (key: string) => Promise<QueueDataType | undefined>;
64
+ keys: () => Promise<string[] | IterableIterator<string>>;
65
+ delete: (key: string) => Promise<void>;
66
+ };
67
+
50
68
  // Running
51
69
 
52
70
  export type RunningRequestValueType = {
@@ -4,11 +4,46 @@ import type { HttpMethodsType, HttpStatusType } from "types";
4
4
 
5
5
  import { Adapter } from "../adapter/adapter";
6
6
  import { defaultTimeout, xhrExtra } from "./http-adapter.constants";
7
- import type { HttpAdapterExtraType, FetchAdapterOptionsType } from "./http-adapter.types";
7
+ import type { HttpAdapterExtraType, FetchAdapterOptionsType, FetchResponseType } from "./http-adapter.types";
8
8
  import { parseErrorResponse, parseResponse, stringifyQueryParams } from "./http-adapter.utils";
9
9
 
10
10
  const defaultExtra = xhrExtra;
11
11
 
12
+ /**
13
+ * Size in bytes of a body that fetch sends as it is. Form data and streams get their size from the browser while they
14
+ * are sent, so it is unknown up front.
15
+ */
16
+ const getBodySize = (body: unknown): number | undefined => {
17
+ if (typeof body === "string") return new Blob([body]).size;
18
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
19
+ if (body instanceof ArrayBuffer) return body.byteLength;
20
+ if (ArrayBuffer.isView(body)) return body.byteLength;
21
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) {
22
+ return new Blob([body.toString()]).size;
23
+ }
24
+ return undefined;
25
+ };
26
+
27
+ /**
28
+ * Body of a successful response in the shape picked with the `responseType` option
29
+ */
30
+ const readResponseBody = (bytes: Uint8Array, responseType: FetchResponseType | undefined, contentType: string | null) => {
31
+ switch (responseType) {
32
+ case "arrayBuffer": {
33
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
34
+ }
35
+ case "blob": {
36
+ return new Blob([bytes as BlobPart], { type: contentType ?? "" });
37
+ }
38
+ case "text": {
39
+ return new TextDecoder().decode(bytes);
40
+ }
41
+ default: {
42
+ return parseResponse(new TextDecoder().decode(bytes));
43
+ }
44
+ }
45
+ };
46
+
12
47
  export const getAdapter = () =>
13
48
  new Adapter<
14
49
  FetchAdapterOptionsType,
@@ -54,14 +89,18 @@ export const getAdapter = () =>
54
89
  onResponseStart,
55
90
  onBeforeRequest,
56
91
  onRequestStart,
57
- onRequestProgress,
58
92
  onSuccess,
59
93
  }) => {
60
94
  const { method } = request;
61
95
  const fullUrl = `${url}${endpoint}${queryParams}`;
62
96
 
63
97
  const controller = getAbortController();
64
- const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};
98
+ const {
99
+ timeout: timeoutMs = defaultTimeout,
100
+ streaming = false,
101
+ responseType,
102
+ ...restOptions
103
+ } = adapterOptions || {};
65
104
 
66
105
  let timedOut = false;
67
106
  let timeoutId: ReturnType<typeof setTimeout> | undefined;
@@ -81,8 +120,11 @@ export const getAdapter = () =>
81
120
  }, timeoutMs);
82
121
  }
83
122
 
123
+ const body = payload && method !== "GET" && method !== "HEAD" ? (payload as BodyInit) : undefined;
124
+ const bodySize = getBodySize(body);
125
+
84
126
  onBeforeRequest();
85
- onRequestStart();
127
+ onRequestStart(bodySize ? { total: bodySize, loaded: 0 } : undefined);
86
128
 
87
129
  try {
88
130
  const init: RequestInit = {
@@ -92,19 +134,15 @@ export const getAdapter = () =>
92
134
  ...restOptions,
93
135
  };
94
136
 
95
- if (payload && method !== "GET" && method !== "HEAD") {
96
- init.body = payload as BodyInit;
97
-
98
- if (typeof payload === "string") {
99
- const total = new Blob([payload]).size;
100
- onRequestProgress({ total, loaded: total } as ProgressEvent);
101
- }
137
+ if (body) {
138
+ init.body = body;
102
139
  }
103
140
 
104
- onRequestEnd();
105
-
106
141
  const response = await fetch(fullUrl, init);
107
142
 
143
+ // Fetch has no upload events. The response is the first sign that the whole body was sent.
144
+ onRequestEnd();
145
+
108
146
  // The timeout covers the whole exchange - a body that stops arriving has to end with the timeout error.
109
147
  // Only a streamed body is handed over to the user as soon as the headers arrive.
110
148
  if (timeoutId && streaming && response.body) {
@@ -132,11 +170,17 @@ export const getAdapter = () =>
132
170
  onError({ error, status, extra });
133
171
  }
134
172
  } else {
135
- let body: string;
173
+ // The body is read as bytes from the stream. Without a stream reader (e.g. React Native) it is read with
174
+ // the method matching the response type - text for the default one, so nothing more than text is needed.
175
+ let body: { bytes: Uint8Array } | { text: string } | { data: Blob | ArrayBuffer };
136
176
 
137
177
  if (response.body && typeof response.body.getReader === "function") {
138
178
  const reader = response.body.getReader();
139
- const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
179
+ // Fetch gives the decompressed body, while Content-Length tells the size of the encoded one - the total
180
+ // of an encoded body is unknown
181
+ const contentEncoding = response.headers.get("content-encoding");
182
+ const isEncoded = !!contentEncoding && contentEncoding !== "identity";
183
+ const contentLength = isEncoded ? 0 : parseInt(response.headers.get("content-length") || "0", 10);
140
184
  let receivedLength = 0;
141
185
  const chunks: Uint8Array[] = [];
142
186
 
@@ -159,9 +203,13 @@ export const getAdapter = () =>
159
203
  allChunks.set(chunk, position);
160
204
  position += chunk.length;
161
205
  }
162
- body = new TextDecoder().decode(allChunks);
206
+ body = { bytes: allChunks };
207
+ } else if (response.ok && responseType === "blob") {
208
+ body = { data: await response.blob() };
209
+ } else if (response.ok && responseType === "arrayBuffer") {
210
+ body = { data: await response.arrayBuffer() };
163
211
  } else {
164
- body = await response.text();
212
+ body = { text: await response.text() };
165
213
  }
166
214
 
167
215
  if (timeoutId) {
@@ -171,11 +219,20 @@ export const getAdapter = () =>
171
219
  onResponseEnd();
172
220
  unmountListener();
173
221
 
222
+ const getText = () => ("text" in body ? body.text : new TextDecoder().decode("bytes" in body ? body.bytes : undefined));
223
+
174
224
  if (response.ok) {
175
- const data = parseResponse(body);
225
+ let data: unknown;
226
+ if ("data" in body) {
227
+ data = body.data;
228
+ } else if ("bytes" in body) {
229
+ data = readResponseBody(body.bytes, responseType, response.headers.get("content-type"));
230
+ } else {
231
+ data = responseType === "text" ? body.text : parseResponse(body.text);
232
+ }
176
233
  onSuccess({ data, status, extra });
177
234
  } else {
178
- const error = parseErrorResponse(body);
235
+ const error = parseErrorResponse(getText());
179
236
  onError({ error, status, extra });
180
237
  }
181
238
  }
@@ -30,8 +30,21 @@ export type FetchAdapterOptionsType = Omit<RequestInit, "method" | "headers" | "
30
30
  * or real-time text generation from LLMs).
31
31
  */
32
32
  streaming?: boolean;
33
+ /**
34
+ * How the body of a successful response is read. The error body is always parsed like the default.
35
+ * - not set: decoded as text and parsed as JSON when it is valid JSON
36
+ * - `"json"`: the same as not set
37
+ * - `"text"`: decoded as text, never parsed
38
+ * - `"blob"`: a `Blob` with the content type of the response - for images, files and other binary data
39
+ * - `"arrayBuffer"`: the raw bytes as an `ArrayBuffer`
40
+ *
41
+ * Ignored when `streaming` is true.
42
+ */
43
+ responseType?: FetchResponseType;
33
44
  };
34
45
 
46
+ export type FetchResponseType = "json" | "text" | "blob" | "arrayBuffer";
47
+
35
48
  export type HttpAdapterExtraType = {
36
49
  headers: Record<string, string>;
37
50
  };
@@ -1,5 +1,5 @@
1
1
  import type { AppManagerOptionsType } from "managers";
2
- import { appManagerInitialOptions, getAppManagerEvents, hasDocument } from "managers";
2
+ import { appManagerInitialOptions, getAppManagerEvents, hasDocument, onWindowEvent } from "managers";
3
3
  import { EventEmitter } from "utils";
4
4
 
5
5
  /**
@@ -18,6 +18,11 @@ export class AppManager {
18
18
  isBrowser: boolean;
19
19
  isOnline: boolean;
20
20
  isFocused: boolean;
21
+ /**
22
+ * True while the browser page is being unloaded (closed, reloaded or navigated away). The browser cancels the
23
+ * requests in flight then - their failures are not real answers, so the dispatcher keeps them for the next start.
24
+ */
25
+ isUnloading = false;
21
26
 
22
27
  private unmountCallbacks: VoidFunction[] = [];
23
28
  private hasFocusUpdate = false;
@@ -46,7 +51,17 @@ export class AppManager {
46
51
 
47
52
  this.unmount();
48
53
 
49
- [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {
54
+ [
55
+ focusEvent(this.setFocused),
56
+ onlineEvent(this.setOnline),
57
+ onWindowEvent("pagehide", () => {
58
+ this.isUnloading = true;
59
+ }),
60
+ // The page can come back from the back-forward cache
61
+ onWindowEvent("pageshow", () => {
62
+ this.isUnloading = false;
63
+ }),
64
+ ].forEach((unmount) => {
50
65
  if (typeof unmount === "function") {
51
66
  this.unmountCallbacks.push(unmount);
52
67
  }
@@ -14,6 +14,8 @@ export class RequestManager {
14
14
  }
15
15
 
16
16
  abortControllers = new Map<string, Map<string, AbortController>>();
17
+ /** Controllers aborted through this manager, i.e. by the user and not by an adapter's own timeout */
18
+ private canceledControllers = new WeakSet<AbortController>();
17
19
 
18
20
  addAbortController = (abortKey: string, requestId: string) => {
19
21
  let abortGroup = this.abortControllers.get(abortKey);
@@ -47,7 +49,19 @@ export class RequestManager {
47
49
 
48
50
  useAbortController = (abortKey: string, requestId: string) => {
49
51
  const controller = this.abortControllers.get(abortKey)?.get(requestId);
50
- controller?.abort();
52
+ if (controller) {
53
+ this.canceledControllers.add(controller);
54
+ controller.abort();
55
+ }
56
+ };
57
+
58
+ /**
59
+ * Whether the request was aborted on purpose (`request.abort()`, `abortByKey`...). Tells canceled requests apart
60
+ * from failed ones whatever shape the adapter gives its errors.
61
+ */
62
+ isCanceled = (abortKey: string, requestId: string) => {
63
+ const controller = this.abortControllers.get(abortKey)?.get(requestId);
64
+ return !!controller && this.canceledControllers.has(controller);
51
65
  };
52
66
 
53
67
  abortByKey = (abortKey: string) => {
@@ -27,6 +27,7 @@ import type {
27
27
  PayloadType,
28
28
  RequestJSON,
29
29
  RequestOptionsType,
30
+ RetryTimeType,
30
31
  RequestConfigurationType,
31
32
  PayloadMapperType,
32
33
  RequestInstance,
@@ -36,7 +37,7 @@ import type {
36
37
  RetryOnErrorCallbackType,
37
38
  OptimisticCallback,
38
39
  } from "./request.types";
39
- import { mapResponseForSend, sendRequest, scopeKey } from "./request.utils";
40
+ import { mapResponseForSend, resolveQueryParams, sendRequest, scopeKey } from "./request.utils";
40
41
 
41
42
  type ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;
42
43
  type ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;
@@ -86,7 +87,7 @@ export class Request<
86
87
  options?: ClientAdapterOptions<Client> | undefined = undefined;
87
88
  cancelable: boolean;
88
89
  retry: number;
89
- retryTime: number;
90
+ retryTime: RetryTimeType;
90
91
  cacheTime: number;
91
92
  cache: boolean;
92
93
  staleTime: number;
@@ -199,7 +200,7 @@ export class Request<
199
200
  this.method = method as ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;
200
201
  this.params = initialRequestConfiguration?.params;
201
202
  this.payload = initialRequestConfiguration?.payload;
202
- this.queryParams = initialRequestConfiguration?.queryParams;
203
+ this.queryParams = resolveQueryParams(client, initialRequestConfiguration?.queryParams);
203
204
  this.options = initialRequestConfiguration?.options ?? options;
204
205
  this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;
205
206
  this.retry = initialRequestConfiguration?.retry ?? retry;
@@ -276,7 +277,7 @@ export class Request<
276
277
  return this.clone({ retry });
277
278
  };
278
279
 
279
- /** Set the delay in milliseconds between retry attempts. */
280
+ /** Set the delay in milliseconds between retry attempts, or a function that returns it for each attempt. */
280
281
  public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>["retryTime"]) => {
281
282
  return this.clone({ retryTime });
282
283
  };