@hyper-fetch/core 8.1.0 → 8.2.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 (51) hide show
  1. package/README.md +137 -52
  2. package/__tests__/features/sdk/sdk.base.spec.ts +7 -11
  3. package/__tests__/features/sdk/sdk.configuration.spec.ts +5 -7
  4. package/__tests__/features/sdk/sdk.types.spec.ts +284 -0
  5. package/dist/adapter/adapter.d.ts +18 -1
  6. package/dist/adapter/adapter.d.ts.map +1 -1
  7. package/dist/adapter/adapter.types.d.ts +8 -0
  8. package/dist/adapter/adapter.types.d.ts.map +1 -1
  9. package/dist/cache/cache.d.ts +3 -6
  10. package/dist/cache/cache.d.ts.map +1 -1
  11. package/dist/cache/cache.events.d.ts +5 -2
  12. package/dist/cache/cache.events.d.ts.map +1 -1
  13. package/dist/cache/cache.types.d.ts +1 -0
  14. package/dist/cache/cache.types.d.ts.map +1 -1
  15. package/dist/client/client.d.ts +5 -1
  16. package/dist/client/client.d.ts.map +1 -1
  17. package/dist/dispatcher/dispatcher.d.ts +1 -1
  18. package/dist/index.mjs +74 -9
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/managers/app/app.manager.events.d.ts +9 -0
  21. package/dist/managers/app/app.manager.events.d.ts.map +1 -1
  22. package/dist/managers/request/request.manager.events.d.ts +12 -1
  23. package/dist/managers/request/request.manager.events.d.ts.map +1 -1
  24. package/dist/mocker/mocker.types.d.ts +1 -0
  25. package/dist/mocker/mocker.types.d.ts.map +1 -1
  26. package/dist/plugin/plugin.d.ts +16 -0
  27. package/dist/plugin/plugin.d.ts.map +1 -1
  28. package/dist/plugin/plugin.types.d.ts +1 -0
  29. package/dist/plugin/plugin.types.d.ts.map +1 -1
  30. package/dist/request/request.d.ts +28 -0
  31. package/dist/request/request.d.ts.map +1 -1
  32. package/dist/request/request.types.d.ts +89 -2
  33. package/dist/request/request.types.d.ts.map +1 -1
  34. package/dist/sdk/sdk.d.ts +25 -5
  35. package/dist/sdk/sdk.d.ts.map +1 -1
  36. package/package.json +1 -1
  37. package/src/adapter/adapter.ts +18 -1
  38. package/src/adapter/adapter.types.ts +8 -0
  39. package/src/cache/cache.events.ts +5 -2
  40. package/src/cache/cache.ts +3 -6
  41. package/src/cache/cache.types.ts +1 -0
  42. package/src/client/client.ts +5 -1
  43. package/src/dispatcher/dispatcher.ts +1 -1
  44. package/src/managers/app/app.manager.events.ts +9 -0
  45. package/src/managers/request/request.manager.events.ts +12 -9
  46. package/src/mocker/mocker.types.ts +1 -0
  47. package/src/plugin/plugin.ts +16 -0
  48. package/src/plugin/plugin.types.ts +1 -0
  49. package/src/request/request.ts +28 -0
  50. package/src/request/request.types.ts +103 -2
  51. package/src/sdk/sdk.ts +55 -6
@@ -21,6 +21,11 @@ import { getAdapterHeaders, getAdapterPayload, RequestProcessingError } from "./
21
21
  export type DefaultMapperType = <V, C>(value: V, config: C) => V;
22
22
  export const defaultMapper: DefaultMapperType = (value) => value;
23
23
 
24
+ /**
25
+ * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,
26
+ * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class
27
+ * to integrate custom transport layers (e.g., axios, graphql, firebase).
28
+ */
24
29
  export class Adapter<
25
30
  AdapterOptions,
26
31
  MethodType extends string,
@@ -92,6 +97,7 @@ export class Adapter<
92
97
  this.defaultRequestOptions = options.defaultRequestOptions;
93
98
  }
94
99
 
100
+ /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */
95
101
  initialize = (client: ClientInstance) => {
96
102
  this.logger = client.loggerManager.initialize(client, "Adapter");
97
103
  this.initialized = true;
@@ -101,6 +107,7 @@ export class Adapter<
101
107
  return this;
102
108
  };
103
109
 
110
+ /** Register a callback invoked once the adapter is initialized with a client. */
104
111
  onInitialize = (callback: (options: { client: ClientInstance }) => void) => {
105
112
  this.unstable_onInitializeCallback = callback;
106
113
  return this;
@@ -161,16 +168,19 @@ export class Adapter<
161
168
  * ********************
162
169
  */
163
170
 
171
+ /** Set the default HTTP method used when a request does not specify one. */
164
172
  setDefaultMethod = (method: MethodType) => {
165
173
  this.defaultMethod = method;
166
174
  return this;
167
175
  };
168
176
 
177
+ /** Set the default extra metadata attached to every request response (e.g., headers, status). */
169
178
  setDefaultExtra = (extra: Extra) => {
170
179
  this.defaultExtra = extra;
171
180
  return this;
172
181
  };
173
182
 
183
+ /** Set a function that formats the endpoint string for display in devtools. */
174
184
  setDevtoolsEndpointGetter = (callback: (endpoint: string) => string) => {
175
185
  this.unstable_devtoolsEndpointGetter = callback;
176
186
  return this;
@@ -217,6 +227,7 @@ export class Adapter<
217
227
  return this;
218
228
  };
219
229
 
230
+ /** Set a custom mapping for internal adapter errors before they are returned in the response. */
220
231
  setInternalErrorMapping = (callback: (error: ReturnType<typeof getErrorMessage>) => any) => {
221
232
  this.unstable_internalErrorMapping = callback;
222
233
  return this;
@@ -268,7 +279,7 @@ export class Adapter<
268
279
  };
269
280
 
270
281
  /**
271
- * Set the request payload mapping function which get triggered before request get sent
282
+ * Set the endpoint mapping function which transforms the endpoint string before the request is sent
272
283
  */
273
284
  setEndpointMapper = <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => {
274
285
  this.unstable_endpointMapper = ((endpoint: Parameters<NewEndpointMapper>[0]) =>
@@ -317,6 +328,7 @@ export class Adapter<
317
328
  >;
318
329
  };
319
330
 
331
+ /** Set the configuration object passed as the second argument to the query params mapper. */
320
332
  setQueryParamsMapperConfig = <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(
321
333
  config: NewQueryParamsMapperConfig,
322
334
  ) => {
@@ -324,6 +336,7 @@ export class Adapter<
324
336
  return this;
325
337
  };
326
338
 
339
+ /** Set the configuration object passed as the second argument to the header mapper. */
327
340
  setHeaderMapperConfig = <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(
328
341
  config: NewHeaderMapperConfig,
329
342
  ) => {
@@ -331,6 +344,7 @@ export class Adapter<
331
344
  return this;
332
345
  };
333
346
 
347
+ /** Set the configuration object passed as the second argument to the endpoint mapper. */
334
348
  setEndpointMapperConfig = <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(
335
349
  config: NewEndpointMapperConfig,
336
350
  ) => {
@@ -338,6 +352,7 @@ export class Adapter<
338
352
  return this;
339
353
  };
340
354
 
355
+ /** Set the configuration object passed as the second argument to the payload mapper. */
341
356
  setPayloadMapperConfig = <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(
342
357
  config: NewPayloadMapperConfig,
343
358
  ) => {
@@ -351,6 +366,7 @@ export class Adapter<
351
366
  * ********************
352
367
  */
353
368
 
369
+ /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */
354
370
  public setFetcher(
355
371
  fetcher: AdapterFetcherType<
356
372
  Adapter<
@@ -372,6 +388,7 @@ export class Adapter<
372
388
  return this;
373
389
  }
374
390
 
391
+ /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
375
392
  public async fetch(
376
393
  request: ExtendRequest<
377
394
  RequestInstance,
@@ -118,13 +118,21 @@ export type RequestResponseType<Request extends RequestInstance> = {
118
118
  requestTimestamp: number;
119
119
  };
120
120
 
121
+ /** The normalized response shape returned by every adapter after a request completes. */
121
122
  export type ResponseType<GenericDataType, GenericErrorType, Adapter extends AdapterInstance> = {
123
+ /** Response data when successful, null on error */
122
124
  data: GenericDataType | null;
125
+ /** Error payload when the request fails, null on success */
123
126
  error: GenericErrorType | null;
127
+ /** HTTP status code or adapter-specific status indicator */
124
128
  status: ExtractAdapterStatusType<Adapter> | null;
129
+ /** Whether the request completed successfully */
125
130
  success: true | false;
131
+ /** Adapter-specific metadata (e.g., response headers) */
126
132
  extra: ExtractAdapterExtraType<Adapter> | null;
133
+ /** Timestamp (ms) when the response was received */
127
134
  responseTimestamp: number;
135
+ /** Timestamp (ms) when the request was sent */
128
136
  requestTimestamp: number;
129
137
  };
130
138
  export type ResponseSuccessType<GenericDataType, Adapter extends AdapterInstance> = {
@@ -4,6 +4,7 @@ import type { CacheValueType } from "cache";
4
4
  import { getInvalidateByKey, getInvalidateKey, getCacheByKey, getCacheKey, getDeleteKey, getDeleteByKey } from "cache";
5
5
  import type { AdapterInstance } from "adapter";
6
6
 
7
+ /** Create the cache event emitters and listeners for data changes, invalidation, and deletion. */
7
8
  export const getCacheEvents = (emitter: EventEmitter) => ({
8
9
  /**
9
10
  * Set cache data
@@ -31,7 +32,7 @@ export const getCacheEvents = (emitter: EventEmitter) => ({
31
32
  emitter.emit(getDeleteByKey(cacheKey), isTriggeredExternally);
32
33
  },
33
34
  /**
34
- * Cache data listener
35
+ * Cache data listener for all keys
35
36
  * @param callback
36
37
  * @returns
37
38
  */
@@ -42,7 +43,7 @@ export const getCacheEvents = (emitter: EventEmitter) => ({
42
43
  return () => emitter.removeListener(getCacheKey(), callback);
43
44
  },
44
45
  /**
45
- * Cache data listener
46
+ * Cache data listener filtered by a specific cache key
46
47
  * @param cacheKey
47
48
  * @param callback
48
49
  * @returns
@@ -73,10 +74,12 @@ export const getCacheEvents = (emitter: EventEmitter) => ({
73
74
  emitter.on(getInvalidateByKey(cacheKey), callback);
74
75
  return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);
75
76
  },
77
+ /** Cache deletion listener for all keys */
76
78
  onDelete: (callback: (cacheKey: string) => void): VoidFunction => {
77
79
  emitter.on(getDeleteKey(), callback);
78
80
  return () => emitter.removeListener(getDeleteKey(), callback);
79
81
  },
82
+ /** Cache deletion listener filtered by a specific cache key */
80
83
  onDeleteByKey: (cacheKey: string, callback: () => void): VoidFunction => {
81
84
  emitter.on(getDeleteByKey(cacheKey), callback);
82
85
  return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);
@@ -44,6 +44,7 @@ export class Cache<Adapter extends AdapterInstance> {
44
44
  this.lazyStorage = lazyStorage;
45
45
  }
46
46
 
47
+ /** Initialize the cache with a client reference, set up logging, and start garbage collection. */
47
48
  initialize = (client: ClientInstance<{ adapter: Adapter }>) => {
48
49
  this.client = client;
49
50
  this.logger = client.loggerManager.initialize(client, "Cache");
@@ -126,8 +127,6 @@ export class Cache<Adapter extends AdapterInstance> {
126
127
  * Update the cache data with partial response data
127
128
  * @param request
128
129
  * @param partialResponse
129
- * @param isTriggeredExtrenally - informs whether an update was triggered due to internal logic or externally, e.g.
130
- * via plugin.
131
130
  * @returns
132
131
  */
133
132
  update = <Request extends RequestCacheType<RequestInstance>>(
@@ -273,8 +272,7 @@ export class Cache<Adapter extends AdapterInstance> {
273
272
  };
274
273
 
275
274
  /**
276
- * Used to receive keys from sync storage and lazy storage
277
- * @param cacheKey
275
+ * Used to receive keys from lazy storage only
278
276
  */
279
277
  getLazyKeys = async () => {
280
278
  const keys = (await this.lazyStorage?.keys()) || [];
@@ -283,8 +281,7 @@ export class Cache<Adapter extends AdapterInstance> {
283
281
  };
284
282
 
285
283
  /**
286
- * Used to receive keys from sync storage and lazy storage
287
- * @param cacheKey
284
+ * Used to receive deduplicated keys from both sync storage and lazy storage
288
285
  */
289
286
  getAllKeys = async () => {
290
287
  const keys = await this.lazyStorage?.keys();
@@ -2,6 +2,7 @@ import type { AdapterInstance, ResponseType } from "adapter";
2
2
  import type { ResponseDetailsType } from "managers";
3
3
  import type { RequestInstance } from "request";
4
4
 
5
+ /** Configuration options for the Cache instance. */
5
6
  export type CacheOptionsType = {
6
7
  /**
7
8
  * Assign your custom sync storage
@@ -232,7 +232,7 @@ export class Client<
232
232
  };
233
233
 
234
234
  /**
235
- * Method for removing listeners on request.
235
+ * Method for removing response interceptors.
236
236
  * */
237
237
  removeOnResponseInterceptors = (
238
238
  callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],
@@ -285,18 +285,22 @@ export class Client<
285
285
  * Key setters
286
286
  */
287
287
 
288
+ /** Set a custom mapper that generates the abort key used to cancel in-flight requests. */
288
289
  setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {
289
290
  this.unstable_abortKeyMapper = callback;
290
291
  return this;
291
292
  };
293
+ /** Set a custom mapper that generates the cache key used to store and retrieve cached responses. */
292
294
  setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {
293
295
  this.unstable_cacheKeyMapper = callback;
294
296
  return this;
295
297
  };
298
+ /** Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. */
296
299
  setQueryKeyMapper = (callback: (request: RequestInstance) => string) => {
297
300
  this.unstable_queryKeyMapper = callback;
298
301
  return this;
299
302
  };
303
+ /** Set a custom mapper that generates the unique request ID for deduplication and tracking. */
300
304
  setRequestIdMapper = (callback: (request: RequestInstance) => string) => {
301
305
  this.unstable_requestIdMapper = callback;
302
306
  return this;
@@ -109,7 +109,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
109
109
  };
110
110
 
111
111
  /**
112
- * Return all
112
+ * Return all queue keys currently tracked by the dispatcher storage
113
113
  */
114
114
  getQueuesKeys = () => {
115
115
  return Array.from(this.storage.keys());
@@ -2,31 +2,40 @@ import type EventEmitter from "events";
2
2
 
3
3
  import { AppEvents } from "managers";
4
4
 
5
+ /** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */
5
6
  export const getAppManagerEvents = (emitter: EventEmitter) => ({
7
+ /** Emit when the application window gains focus */
6
8
  emitFocus: (): void => {
7
9
  emitter.emit(AppEvents.FOCUS);
8
10
  },
11
+ /** Emit when the application window loses focus */
9
12
  emitBlur: (): void => {
10
13
  emitter.emit(AppEvents.BLUR);
11
14
  },
15
+ /** Emit when the application transitions to online state */
12
16
  emitOnline: (): void => {
13
17
  emitter.emit(AppEvents.ONLINE);
14
18
  },
19
+ /** Emit when the application transitions to offline state */
15
20
  emitOffline: (): void => {
16
21
  emitter.emit(AppEvents.OFFLINE);
17
22
  },
23
+ /** Listen for focus events */
18
24
  onFocus: (callback: () => void): VoidFunction => {
19
25
  emitter.on(AppEvents.FOCUS, callback);
20
26
  return () => emitter.removeListener(AppEvents.FOCUS, callback);
21
27
  },
28
+ /** Listen for blur events */
22
29
  onBlur: (callback: () => void): VoidFunction => {
23
30
  emitter.on(AppEvents.BLUR, callback);
24
31
  return () => emitter.removeListener(AppEvents.BLUR, callback);
25
32
  },
33
+ /** Listen for online state transitions */
26
34
  onOnline: (callback: () => void): VoidFunction => {
27
35
  emitter.on(AppEvents.ONLINE, callback);
28
36
  return () => emitter.removeListener(AppEvents.ONLINE, callback);
29
37
  },
38
+ /** Listen for offline state transitions */
30
39
  onOffline: (callback: () => void): VoidFunction => {
31
40
  emitter.on(AppEvents.OFFLINE, callback);
32
41
  return () => emitter.removeListener(AppEvents.OFFLINE, callback);
@@ -45,12 +45,13 @@ import type { RequestInstance } from "request";
45
45
  import type { Client } from "client";
46
46
  import type { ExtendRequest } from "types";
47
47
 
48
+ /** Create event emitters and listeners for the request lifecycle: loading, progress, response, abort, deduplication, and removal. */
48
49
  export const getRequestManagerEvents = (emitter: EventEmitter) => ({
49
50
  /**
50
- * Emiter
51
+ * Emitters
51
52
  */
52
53
 
53
- // Deduplicated
54
+ /** Emit when a request is deduplicated (skipped because an identical one is in-flight) */
54
55
  emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally = false): void => {
55
56
  emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);
56
57
  emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);
@@ -58,7 +59,7 @@ export const getRequestManagerEvents = (emitter: EventEmitter) => ({
58
59
  emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);
59
60
  },
60
61
 
61
- // Loading
62
+ /** Emit loading state changes for a request */
62
63
  emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally = false): void => {
63
64
  emitter.emit(getLoadingKey(), data, isTriggeredExternally);
64
65
  emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);
@@ -66,31 +67,33 @@ export const getRequestManagerEvents = (emitter: EventEmitter) => ({
66
67
  emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);
67
68
  },
68
69
 
69
- // Start
70
+ /** Emit when a request starts being sent */
70
71
  emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {
71
72
  emitter.emit(getRequestStartKey(), data, isTriggeredExternally);
72
73
  emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);
73
74
  emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);
74
75
  },
76
+ /** Emit when the response starts being received */
75
77
  emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {
76
78
  emitter.emit(getResponseStartKey(), data, isTriggeredExternally);
77
79
  emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);
78
80
  emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);
79
81
  },
80
82
 
81
- // Progress
83
+ /** Emit upload progress updates */
82
84
  emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {
83
85
  emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);
84
86
  emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);
85
87
  emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
86
88
  },
89
+ /** Emit download progress updates */
87
90
  emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {
88
91
  emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);
89
92
  emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);
90
93
  emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
91
94
  },
92
95
 
93
- // Response
96
+ /** Emit when a response is received */
94
97
  emitResponse: <Adapter extends AdapterInstance>(
95
98
  data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter> }>>,
96
99
  isTriggeredExternally = false,
@@ -100,14 +103,14 @@ export const getRequestManagerEvents = (emitter: EventEmitter) => ({
100
103
  emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
101
104
  },
102
105
 
103
- // Abort
106
+ /** Emit when a request is aborted */
104
107
  emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {
105
108
  emitter.emit(getAbortKey(), data, isTriggeredExternally);
106
109
  emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);
107
110
  emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);
108
111
  },
109
112
 
110
- // Remove
113
+ /** Emit when a request is removed from the dispatcher queue */
111
114
  emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally = false): void => {
112
115
  emitter.emit(getRemoveKey(), data, isTriggeredExternally);
113
116
  emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);
@@ -118,7 +121,7 @@ export const getRequestManagerEvents = (emitter: EventEmitter) => ({
118
121
  * Listeners
119
122
  */
120
123
 
121
- // Deduplicated
124
+ /** Listen for deduplicated request events */
122
125
  onDeduplicated: <T extends RequestInstance>(
123
126
  callback: (data: RequestDeduplicatedEventType<T>) => void,
124
127
  ): VoidFunction => {
@@ -17,6 +17,7 @@ export type MockerConfigType = {
17
17
  totalDownloaded?: number;
18
18
  };
19
19
 
20
+ /** Shape of a mocked response returned from the mocker. Must include either `data` (success) or `error` (failure). */
20
21
  export type MockResponseType<Response, Error, AdapterType extends AdapterInstance> = PartialBy<
21
22
  Omit<ResponseType<Response, Error, AdapterType>, "data" | "error" | "responseTimestamp" | "requestTimestamp">,
22
23
  "extra" | "success"
@@ -1,6 +1,10 @@
1
1
  import type { PluginMethodParameters, PluginMethods, PluginOptionsType } from "plugin";
2
2
  import type { ClientInstance } from "client";
3
3
 
4
+ /**
5
+ * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.
6
+ * Extend this to build devtools, logging, analytics, or custom side-effect plugins.
7
+ */
4
8
  export class Plugin<Client extends ClientInstance = ClientInstance, PluginData = void> {
5
9
  public name: string;
6
10
  public data: PluginData;
@@ -16,11 +20,13 @@ export class Plugin<Client extends ClientInstance = ClientInstance, PluginData =
16
20
  }
17
21
  }
18
22
 
23
+ /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */
19
24
  initialize = (client: Client) => {
20
25
  this.client = client;
21
26
  return this;
22
27
  };
23
28
 
29
+ /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */
24
30
  trigger = <Key extends keyof PluginMethods<Client>>(method: Key, data: PluginMethodParameters<Key, Client>) => {
25
31
  const callback = this.pluginMethods[method];
26
32
  if (callback) {
@@ -99,36 +105,43 @@ export class Plugin<Client extends ClientInstance = ClientInstance, PluginData =
99
105
  * Dispatcher lifecycle
100
106
  * -----------------------------------------------------------------------------------------------*/
101
107
 
108
+ /** Called when the dispatcher storage is fully cleared */
102
109
  onDispatcherCleared = (callback: PluginMethods<Client>["onDispatcherCleared"]) => {
103
110
  this.pluginMethods.onDispatcherCleared = callback;
104
111
  return this;
105
112
  };
106
113
 
114
+ /** Called when a dispatcher queue has no more pending requests */
107
115
  onDispatcherQueueDrained = (callback: PluginMethods<Client>["onDispatcherQueueDrained"]) => {
108
116
  this.pluginMethods.onDispatcherQueueDrained = callback;
109
117
  return this;
110
118
  };
111
119
 
120
+ /** Called when a dispatcher queue transitions to running, paused, or stopped */
112
121
  onDispatcherQueueRunning = (callback: PluginMethods<Client>["onDispatcherQueueRunning"]) => {
113
122
  this.pluginMethods.onDispatcherQueueRunning = callback;
114
123
  return this;
115
124
  };
116
125
 
126
+ /** Called when a new item is added to a dispatcher queue */
117
127
  onDispatcherItemAdded = (callback: PluginMethods<Client>["onDispatcherItemAdded"]) => {
118
128
  this.pluginMethods.onDispatcherItemAdded = callback;
119
129
  return this;
120
130
  };
121
131
 
132
+ /** Called when an item is removed from a dispatcher queue */
122
133
  onDispatcherItemDeleted = (callback: PluginMethods<Client>["onDispatcherItemDeleted"]) => {
123
134
  this.pluginMethods.onDispatcherItemDeleted = callback;
124
135
  return this;
125
136
  };
126
137
 
138
+ /** Called when a new dispatcher queue is created */
127
139
  onDispatcherQueueCreated = (callback: PluginMethods<Client>["onDispatcherQueueCreated"]) => {
128
140
  this.pluginMethods.onDispatcherQueueCreated = callback;
129
141
  return this;
130
142
  };
131
143
 
144
+ /** Called when an entire dispatcher queue is cleared */
132
145
  onDispatcherQueueCleared = (callback: PluginMethods<Client>["onDispatcherQueueCleared"]) => {
133
146
  this.pluginMethods.onDispatcherQueueCleared = callback;
134
147
  return this;
@@ -138,11 +151,13 @@ export class Plugin<Client extends ClientInstance = ClientInstance, PluginData =
138
151
  * Cache lifecycle
139
152
  * -----------------------------------------------------------------------------------------------*/
140
153
 
154
+ /** Called when a cache entry is created or updated */
141
155
  onCacheItemChange = (callback: PluginMethods<Client>["onCacheItemChange"]) => {
142
156
  this.pluginMethods.onCacheItemChange = callback;
143
157
  return this;
144
158
  };
145
159
 
160
+ /** Called when a cache entry is deleted */
146
161
  onCacheItemDelete = (callback: PluginMethods<Client>["onCacheItemDelete"]) => {
147
162
  this.pluginMethods.onCacheItemDelete = callback;
148
163
  return this;
@@ -152,6 +167,7 @@ export class Plugin<Client extends ClientInstance = ClientInstance, PluginData =
152
167
  * Adapter lifecycle
153
168
  * -----------------------------------------------------------------------------------------------*/
154
169
 
170
+ /** Called when the adapter fetcher is about to execute a request */
155
171
  onAdapterFetch = (callback: PluginMethods<Client>["onAdapterFetch"]) => {
156
172
  this.pluginMethods.onAdapterFetch = callback;
157
173
  return this;
@@ -21,6 +21,7 @@ export type PluginRequest<C extends ClientInstance> = ExtendRequest<
21
21
  }
22
22
  >;
23
23
 
24
+ /** Configuration options for creating a Plugin instance. */
24
25
  export type PluginOptionsType<PluginData> = {
25
26
  /**
26
27
  * Name of the plugin
@@ -204,28 +204,34 @@ export class Request<
204
204
  this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
205
205
  }
206
206
 
207
+ /** Set the request headers. Returns a cloned request with the new headers applied. */
207
208
  public setHeaders = (headers: HeadersInit) => {
208
209
  return this.clone({ headers });
209
210
  };
210
211
 
212
+ /** Set whether authentication interceptors should run for this request. */
211
213
  public setAuth = (auth: boolean) => {
212
214
  return this.clone({ auth });
213
215
  };
214
216
 
217
+ /** Set the URL path parameters (e.g., `:userId`). */
215
218
  public setParams = <P extends ExtractParamsType<this>>(params: P) => {
216
219
  return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });
217
220
  };
218
221
 
222
+ /** Set the request body payload. */
219
223
  public setPayload = <P extends Payload>(payload: P) => {
220
224
  return this.clone<P extends null ? false : true, HasParams, HasQuery>({
221
225
  payload,
222
226
  });
223
227
  };
224
228
 
229
+ /** Set the query parameters appended to the URL. */
225
230
  public setQueryParams = (queryParams: QueryParams) => {
226
231
  return this.clone<HasPayload, HasParams, true>({ queryParams });
227
232
  };
228
233
 
234
+ /** Set adapter-specific options (e.g., axios config, fetch init). */
229
235
  public setOptions = (options: ClientAdapterOptions<Client>) => {
230
236
  return this.clone<HasPayload, HasParams, true>({ options });
231
237
  };
@@ -242,14 +248,17 @@ export class Request<
242
248
  return cloned;
243
249
  };
244
250
 
251
+ /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */
245
252
  public setCancelable = (cancelable: boolean) => {
246
253
  return this.clone({ cancelable });
247
254
  };
248
255
 
256
+ /** Set the number of retry attempts on failure. */
249
257
  public setRetry = (retry: ClientRequestOptions<Endpoint, Client>["retry"]) => {
250
258
  return this.clone({ retry });
251
259
  };
252
260
 
261
+ /** Set the delay in milliseconds between retry attempts. */
253
262
  public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>["retryTime"]) => {
254
263
  return this.clone({ retryTime });
255
264
  };
@@ -293,53 +302,65 @@ export class Request<
293
302
  >;
294
303
  };
295
304
 
305
+ /** Set how long (in ms) the response remains in cache before being garbage collected. */
296
306
  public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>["cacheTime"]) => {
297
307
  return this.clone({ cacheTime });
298
308
  };
299
309
 
310
+ /** Set whether this request should use the cache. */
300
311
  public setCache = (cache: ClientRequestOptions<Endpoint, Client>["cache"]) => {
301
312
  return this.clone({ cache });
302
313
  };
303
314
 
315
+ /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */
304
316
  public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>["staleTime"]) => {
305
317
  return this.clone({ staleTime });
306
318
  };
307
319
 
320
+ /** Set whether the request should be queued and executed sequentially rather than immediately. */
308
321
  public setQueued = (queued: boolean) => {
309
322
  return this.clone({ queued });
310
323
  };
311
324
 
325
+ /** Override the abort key used to cancel this request. */
312
326
  public setAbortKey = (abortKey: string) => {
313
327
  this.updatedAbortKey = true;
314
328
  return this.clone({ abortKey });
315
329
  };
316
330
 
331
+ /** Override the cache key used to store/retrieve the response. */
317
332
  public setCacheKey = (cacheKey: string) => {
318
333
  this.updatedCacheKey = true;
319
334
  return this.clone({ cacheKey });
320
335
  };
321
336
 
337
+ /** Override the query key that identifies this request in the dispatcher queue. */
322
338
  public setQueryKey = (queryKey: string) => {
323
339
  this.updatedQueryKey = true;
324
340
  return this.clone({ queryKey });
325
341
  };
326
342
 
343
+ /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
327
344
  public setDeduplicate = (deduplicate: boolean) => {
328
345
  return this.clone({ deduplicate });
329
346
  };
330
347
 
348
+ /** Set the time window (in ms) during which identical requests are deduplicated. */
331
349
  public setDeduplicateTime = (deduplicateTime: number) => {
332
350
  return this.clone({ deduplicateTime });
333
351
  };
334
352
 
353
+ /** Mark the request as used (prevents automatic refetching in hooks). */
335
354
  public setUsed = (used: boolean) => {
336
355
  return this.clone({ used });
337
356
  };
338
357
 
358
+ /** Set whether the request should be stored in the offline queue when there is no network connection. */
339
359
  public setOffline = (offline: boolean) => {
340
360
  return this.clone({ offline });
341
361
  };
342
362
 
363
+ /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */
343
364
  public setMock = (
344
365
  fn: (options: {
345
366
  request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
@@ -354,12 +375,14 @@ export class Request<
354
375
  return this;
355
376
  };
356
377
 
378
+ /** Remove any attached mock handler and disable mocking for this request. */
357
379
  public clearMock = () => {
358
380
  this.unstable_mock = undefined;
359
381
  this.isMockerEnabled = false;
360
382
  return this;
361
383
  };
362
384
 
385
+ /** Enable or disable the mocker for this request without removing the mock handler. */
363
386
  public setMockingEnabled = (isMockerEnabled: boolean) => {
364
387
  this.isMockerEnabled = isMockerEnabled;
365
388
  return this;
@@ -432,6 +455,7 @@ export class Request<
432
455
  return stringEndpoint as Endpoint;
433
456
  };
434
457
 
458
+ /** Serialize the request configuration into a plain JSON object for persistence or transfer. */
435
459
  public toJSON(): RequestJSON<this> {
436
460
  return {
437
461
  requestOptions: this.requestOptions as unknown as RequestOptionsType<
@@ -473,6 +497,7 @@ export class Request<
473
497
  };
474
498
  }
475
499
 
500
+ /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */
476
501
  public clone<
477
502
  NewData extends true | false = HasPayload,
478
503
  NewParams extends true | false = HasParams,
@@ -537,6 +562,7 @@ export class Request<
537
562
  return cloned;
538
563
  }
539
564
 
565
+ /** Abort all in-flight requests sharing this request's abort key. */
540
566
  public abort = () => {
541
567
  const { requestManager } = this.client;
542
568
  requestManager.abortByKey(scopeKey(this.abortKey, this.scope));
@@ -544,6 +570,7 @@ export class Request<
544
570
  return this.clone();
545
571
  };
546
572
 
573
+ /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */
547
574
  public dehydrate = (config?: {
548
575
  /** in case of using adapter without cache we can provide response to dehydrate */
549
576
  response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
@@ -698,6 +725,7 @@ export class Request<
698
725
  return sendRequest(request, sendRequestOptions);
699
726
  };
700
727
 
728
+ /** Reconstruct a Request instance from a previously serialized JSON representation. */
701
729
  static fromJSON = <
702
730
  NewResponse,
703
731
  NewPayload,