@hyper-fetch/core 8.2.0 → 8.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +4 -4
  2. package/__tests__/e2e/e2e.advanced.spec.ts +7 -7
  3. package/__tests__/features/adapter/adapter.base.spec.ts +2 -1
  4. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -4
  5. package/__tests__/features/adapter/adapter.browser.spec.ts +0 -1
  6. package/__tests__/features/adapter/adapter.server.spec.ts +4 -5
  7. package/__tests__/features/adapter/adapter.utils.spec.ts +6 -7
  8. package/__tests__/features/cache/cache.base.spec.ts +7 -7
  9. package/__tests__/features/cache/cache.events.spec.ts +15 -15
  10. package/__tests__/features/cache/cache.garbage-collector.spec.ts +18 -18
  11. package/__tests__/features/cache/cache.lazy-storage.spec.ts +8 -8
  12. package/__tests__/features/cache/cache.modes.spec.ts +7 -6
  13. package/__tests__/features/cache/cache.scoping.spec.ts +12 -8
  14. package/__tests__/features/cache/cache.typescript.spec.ts +2 -2
  15. package/__tests__/features/cache/cache.utils.spec.ts +14 -14
  16. package/__tests__/features/client/client.auth.spec.ts +0 -1
  17. package/__tests__/features/client/client.base.spec.ts +2 -3
  18. package/__tests__/features/client/client.from-json.spec.ts +0 -1
  19. package/__tests__/features/client/client.hydration.spec.ts +5 -5
  20. package/__tests__/features/client/client.interceptor.spec.ts +3 -3
  21. package/__tests__/features/client/client.methods.spec.ts +5 -5
  22. package/__tests__/features/client/client.middleware.spec.ts +2 -2
  23. package/__tests__/features/client/client.utils.spec.ts +16 -15
  24. package/__tests__/features/dispatcher/dispatcher.base.spec.ts +3 -3
  25. package/__tests__/features/dispatcher/dispatcher.custom-storage.spec.ts +4 -5
  26. package/__tests__/features/dispatcher/dispatcher.events.spec.ts +4 -4
  27. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +13 -13
  28. package/__tests__/features/dispatcher/dispatcher.requests.spec.ts +10 -10
  29. package/__tests__/features/dispatcher/dispatcher.utils.spec.ts +35 -8
  30. package/__tests__/features/managers/app/app.manager.base.spec.ts +2 -3
  31. package/__tests__/features/managers/logger/logger.base.spec.ts +1 -2
  32. package/__tests__/features/managers/request/request.manager.base.spec.ts +8 -9
  33. package/__tests__/features/managers/request/request.manager.events.spec.ts +1 -2
  34. package/__tests__/features/mocker/mocker.base.spec.ts +6 -6
  35. package/__tests__/features/plugin/plugin.base.spec.ts +1 -2
  36. package/__tests__/features/request/request.cloning.spec.ts +0 -1
  37. package/__tests__/features/request/request.deduplicate-defaults.spec.ts +79 -0
  38. package/__tests__/features/request/request.retry-on-error.spec.ts +1 -2
  39. package/__tests__/features/request/request.sending.spec.ts +73 -24
  40. package/__tests__/features/request/request.setters.spec.ts +4 -3
  41. package/__tests__/features/request/request.typescript.spec.ts +0 -1
  42. package/__tests__/features/request/request.utils.spec.ts +1 -0
  43. package/__tests__/features/sdk/sdk.base.spec.ts +0 -1
  44. package/__tests__/features/sdk/sdk.request-fields.spec.ts +80 -0
  45. package/__tests__/features/sdk/sdk.types.spec.ts +3 -4
  46. package/__tests__/shared/callbacks.shared.ts +1 -1
  47. package/__tests__/tsconfig.json +4 -17
  48. package/__tests__/utils/adapter.utils.ts +1 -2
  49. package/__tests__/utils/callbacks.utils.ts +1 -2
  50. package/__tests__/utils/dispatcher.utils.ts +1 -1
  51. package/__tests__/vitest.setup.ts +1 -1
  52. package/dist/adapter/adapter.d.ts +4 -4
  53. package/dist/adapter/adapter.d.ts.map +1 -1
  54. package/dist/adapter/adapter.types.d.ts +1 -1
  55. package/dist/adapter/adapter.types.d.ts.map +1 -1
  56. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  57. package/dist/cache/cache.d.ts +3 -3
  58. package/dist/cache/cache.d.ts.map +1 -1
  59. package/dist/cache/cache.events.d.ts +2 -2
  60. package/dist/cache/cache.events.d.ts.map +1 -1
  61. package/dist/client/client.create.d.ts +1 -1
  62. package/dist/client/client.create.d.ts.map +1 -1
  63. package/dist/client/client.d.ts +3 -3
  64. package/dist/client/client.d.ts.map +1 -1
  65. package/dist/client/client.types.d.ts +1 -1
  66. package/dist/client/client.types.d.ts.map +1 -1
  67. package/dist/client/client.utils.d.ts.map +1 -1
  68. package/dist/constants/http.constants.d.ts +5 -1
  69. package/dist/constants/http.constants.d.ts.map +1 -1
  70. package/dist/constants/time.constants.d.ts.map +1 -1
  71. package/dist/dispatcher/dispatcher.d.ts +3 -3
  72. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  73. package/dist/dispatcher/dispatcher.events.d.ts +1 -1
  74. package/dist/dispatcher/dispatcher.events.d.ts.map +1 -1
  75. package/dist/dispatcher/dispatcher.utils.d.ts +1 -1
  76. package/dist/dispatcher/dispatcher.utils.d.ts.map +1 -1
  77. package/dist/http-adapter/http-adapter.constants.d.ts.map +1 -1
  78. package/dist/http-adapter/http-adapter.d.ts.map +1 -1
  79. package/dist/http-adapter/http-adapter.fetch.d.ts +2 -2
  80. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  81. package/dist/http-adapter/http-adapter.types.d.ts +2 -2
  82. package/dist/http-adapter/http-adapter.types.d.ts.map +1 -1
  83. package/dist/http-adapter/http-adapter.utils.d.ts.map +1 -1
  84. package/dist/index.mjs +2363 -2347
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/managers/app/app.manager.constants.d.ts +1 -1
  87. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  88. package/dist/managers/app/app.manager.d.ts +1 -1
  89. package/dist/managers/app/app.manager.d.ts.map +1 -1
  90. package/dist/managers/app/app.manager.events.d.ts.map +1 -1
  91. package/dist/managers/logger/logger.manager.d.ts +1 -1
  92. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  93. package/dist/managers/request/request.manager.d.ts.map +1 -1
  94. package/dist/managers/request/request.manager.events.d.ts +2 -2
  95. package/dist/managers/request/request.manager.events.d.ts.map +1 -1
  96. package/dist/plugin/plugin.d.ts +1 -1
  97. package/dist/plugin/plugin.d.ts.map +1 -1
  98. package/dist/plugin/plugin.types.d.ts +4 -4
  99. package/dist/plugin/plugin.types.d.ts.map +1 -1
  100. package/dist/request/request.d.ts +5 -4
  101. package/dist/request/request.d.ts.map +1 -1
  102. package/dist/request/request.hooks.d.ts +2 -2
  103. package/dist/request/request.hooks.d.ts.map +1 -1
  104. package/dist/request/request.types.d.ts +3 -3
  105. package/dist/request/request.types.d.ts.map +1 -1
  106. package/dist/request/request.utils.d.ts.map +1 -1
  107. package/dist/sdk/sdk.d.ts +1 -1
  108. package/dist/sdk/sdk.d.ts.map +1 -1
  109. package/dist/types/http.types.d.ts +1 -1
  110. package/dist/types/http.types.d.ts.map +1 -1
  111. package/dist/types/request.types.d.ts +2 -2
  112. package/dist/types/request.types.d.ts.map +1 -1
  113. package/dist/utils/emitter.utils.d.ts +1 -1
  114. package/dist/utils/emitter.utils.d.ts.map +1 -1
  115. package/package.json +8 -8
  116. package/src/adapter/adapter.bindings.ts +14 -14
  117. package/src/adapter/adapter.ts +10 -9
  118. package/src/adapter/adapter.types.ts +2 -1
  119. package/src/adapter/adapter.utils.ts +5 -5
  120. package/src/cache/cache.events.ts +2 -3
  121. package/src/cache/cache.ts +11 -11
  122. package/src/client/client.create.ts +1 -1
  123. package/src/client/client.ts +9 -8
  124. package/src/client/client.types.ts +2 -2
  125. package/src/client/client.utils.ts +3 -2
  126. package/src/constants/http.constants.ts +5 -0
  127. package/src/constants/time.constants.ts +1 -1
  128. package/src/dispatcher/dispatcher.events.ts +1 -2
  129. package/src/dispatcher/dispatcher.ts +12 -12
  130. package/src/dispatcher/dispatcher.utils.ts +10 -4
  131. package/src/http-adapter/http-adapter.constants.ts +1 -0
  132. package/src/http-adapter/http-adapter.fetch.ts +19 -9
  133. package/src/http-adapter/http-adapter.ts +2 -1
  134. package/src/http-adapter/http-adapter.types.ts +3 -2
  135. package/src/http-adapter/http-adapter.utils.ts +15 -11
  136. package/src/managers/app/app.manager.constants.ts +2 -1
  137. package/src/managers/app/app.manager.events.ts +0 -1
  138. package/src/managers/app/app.manager.ts +1 -1
  139. package/src/managers/app/app.manager.utils.ts +2 -2
  140. package/src/managers/logger/logger.manager.ts +1 -2
  141. package/src/managers/request/request.manager.events.ts +2 -3
  142. package/src/managers/request/request.manager.ts +4 -4
  143. package/src/mocker/mocker.ts +2 -2
  144. package/src/plugin/plugin.ts +1 -1
  145. package/src/plugin/plugin.types.ts +4 -4
  146. package/src/request/request.hooks.ts +6 -5
  147. package/src/request/request.ts +49 -34
  148. package/src/request/request.types.ts +4 -3
  149. package/src/request/request.utils.ts +17 -16
  150. package/src/sdk/sdk.ts +26 -19
  151. package/src/types/http.types.ts +1 -1
  152. package/src/types/request.types.ts +3 -2
  153. package/src/utils/emitter.utils.ts +1 -1
  154. package/src/utils/uuid.utils.ts +1 -1
  155. package/tsconfig.json +30 -2
  156. package/vite.config.ts +14 -20
  157. package/.eslintrc.cjs +0 -12
  158. package/tsconfig.base.json +0 -7
@@ -1,5 +1,6 @@
1
- import type { RequiredKeys } from "types";
2
1
  import type { AppManagerOptionsType } from "managers";
2
+ import type { RequiredKeys } from "types";
3
+
3
4
  import { onWindowEvent, onDocumentEvent } from "./app.manager.utils";
4
5
 
5
6
  export enum AppEvents {
@@ -1,5 +1,4 @@
1
1
  import type EventEmitter from "events";
2
-
3
2
  import { AppEvents } from "managers";
4
3
 
5
4
  /** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */
@@ -1,6 +1,6 @@
1
- import { EventEmitter } from "utils";
2
1
  import type { AppManagerOptionsType } from "managers";
3
2
  import { appManagerInitialOptions, getAppManagerEvents, hasDocument } from "managers";
3
+ import { EventEmitter } from "utils";
4
4
 
5
5
  /**
6
6
  * App manager handles main application states - focus and online. Those two values can answer questions:
@@ -1,7 +1,7 @@
1
1
  export const hasWindow = () => {
2
2
  try {
3
3
  return Boolean(window && window.addEventListener);
4
- } catch (err) {
4
+ } catch {
5
5
  /* istanbul ignore next */
6
6
  return false;
7
7
  }
@@ -10,7 +10,7 @@ export const hasWindow = () => {
10
10
  export const hasDocument = () => {
11
11
  try {
12
12
  return Boolean(hasWindow() && window.document && window.document.addEventListener);
13
- } catch (err) {
13
+ } catch {
14
14
  /* istanbul ignore next */
15
15
  return false;
16
16
  }
@@ -1,6 +1,5 @@
1
- import EventEmitter from "events";
2
-
3
1
  import type { ClientInstance } from "client";
2
+ import EventEmitter from "events";
4
3
  import type { LogLevel, LoggerOptionsType, LoggerType, LoggerMethods } from "managers";
5
4
  import { logger, logLevelOrder } from "managers";
6
5
 
@@ -1,6 +1,7 @@
1
+ import type { AdapterInstance } from "adapter";
2
+ import type { Client } from "client";
1
3
  /* eslint-disable max-params */
2
4
  import type EventEmitter from "events";
3
-
4
5
  import type {
5
6
  RequestEventType,
6
7
  RequestLoadingEventType,
@@ -40,9 +41,7 @@ import {
40
41
  getRequestDeduplicatedByCacheKey,
41
42
  getRequestDeduplicatedByQueryKey,
42
43
  } from "managers";
43
- import type { AdapterInstance } from "adapter";
44
44
  import type { RequestInstance } from "request";
45
- import type { Client } from "client";
46
45
  import type { ExtendRequest } from "types";
47
46
 
48
47
  /** Create event emitters and listeners for the request lifecycle: loading, progress, response, abort, deduplication, and removal. */
@@ -1,5 +1,5 @@
1
- import { EventEmitter } from "utils";
2
1
  import { getRequestManagerEvents } from "managers";
2
+ import { EventEmitter } from "utils";
3
3
 
4
4
  /**
5
5
  * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.
@@ -48,7 +48,7 @@ export class RequestManager {
48
48
  const controllers = this.abortControllers.get(abortKey);
49
49
 
50
50
  if (controllers) {
51
- const entries = Array.from(controllers.entries());
51
+ const entries = [...controllers.entries()];
52
52
  entries.forEach(([key]) => {
53
53
  this.useAbortController(abortKey, key);
54
54
  });
@@ -60,9 +60,9 @@ export class RequestManager {
60
60
  };
61
61
 
62
62
  abortAll = () => {
63
- const entries = Array.from(this.abortControllers.entries());
63
+ const entries = [...this.abortControllers.entries()];
64
64
  entries.forEach(([abortKey, value]) => {
65
- const controllers = Array.from(value.entries());
65
+ const controllers = [...value.entries()];
66
66
  controllers.forEach(([requestId]) => {
67
67
  this.useAbortController(abortKey, requestId);
68
68
  });
@@ -59,7 +59,7 @@ export const mocker = async <T extends AdapterInstance>({
59
59
  }
60
60
 
61
61
  const interval = 20;
62
- const dataStart = +new Date();
62
+ const dataStart = Date.now();
63
63
  const intervals = Math.ceil(totalTime / interval);
64
64
  const chunkSize = Math.ceil(totalSize / intervals);
65
65
  let currentlyLoaded = 0;
@@ -69,7 +69,7 @@ export const mocker = async <T extends AdapterInstance>({
69
69
  clearInterval(timer);
70
70
  }
71
71
 
72
- const currentTime = Math.min(totalTime, +new Date() - dataStart);
72
+ const currentTime = Math.min(totalTime, Date.now() - dataStart);
73
73
  currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;
74
74
  progressFunction({
75
75
  total: totalSize,
@@ -1,5 +1,5 @@
1
- import type { PluginMethodParameters, PluginMethods, PluginOptionsType } from "plugin";
2
1
  import type { ClientInstance } from "client";
2
+ import type { PluginMethodParameters, PluginMethods, PluginOptionsType } from "plugin";
3
3
 
4
4
  /**
5
5
  * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.
@@ -1,6 +1,9 @@
1
- import type { RequestInstance } from "request";
2
1
  import type { ResponseErrorType, ResponseType, ResponseSuccessType, AdapterInstance } from "adapter";
2
+ import type { Cache, CacheValueType } from "cache";
3
+ import type { ClientInstance } from "client";
4
+ import type { Dispatcher, QueueDataType, ResolvedQueueItemType } from "dispatcher";
3
5
  import type { Plugin } from "plugin";
6
+ import type { RequestInstance } from "request";
4
7
  import type {
5
8
  ExtractAdapterType,
6
9
  ExtractErrorType,
@@ -8,9 +11,6 @@ import type {
8
11
  ExtendRequest,
9
12
  ExtractClientAdapterType,
10
13
  } from "types";
11
- import type { ClientInstance } from "client";
12
- import type { Cache, CacheValueType } from "cache";
13
- import type { Dispatcher, QueueDataType, ResolvedQueueItemType } from "dispatcher";
14
14
 
15
15
  export type PluginLifecycle = "trigger" | "start" | "success" | "error" | "finished";
16
16
  export type PluginInstance = Plugin<any, any>;
@@ -1,4 +1,5 @@
1
1
  import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
2
+
2
3
  import type { RequestInstance } from "./request.types";
3
4
 
4
5
  type HookName =
@@ -21,7 +22,7 @@ export interface RequestHooks<R extends RequestInstance> {
21
22
  /** @internal Invoke all registered listeners for a given hook */
22
23
  __emit: (name: HookName, data: any) => void;
23
24
  /** @internal Get a snapshot of all registered listeners (used by clone) */
24
- __snapshot: () => Record<HookName, Array<(...args: any[]) => void>>;
25
+ __snapshot: () => Record<HookName, ((...args: any[]) => void)[]>;
25
26
  }
26
27
 
27
28
  const HOOK_NAMES: HookName[] = [
@@ -35,9 +36,9 @@ const HOOK_NAMES: HookName[] = [
35
36
  ];
36
37
 
37
38
  export function createRequestHooks<R extends RequestInstance>(
38
- initial?: Record<HookName, Array<(...args: any[]) => void>>,
39
+ initial?: Record<HookName, ((...args: any[]) => void)[]>,
39
40
  ): RequestHooks<R> {
40
- const listeners: Record<HookName, Array<(...args: any[]) => void>> = {
41
+ const listeners: Record<HookName, ((...args: any[]) => void)[]> = {
41
42
  onBeforeSent: [],
42
43
  onRequestStart: [],
43
44
  onResponseStart: [],
@@ -58,7 +59,7 @@ export function createRequestHooks<R extends RequestInstance>(
58
59
  listeners[name].push(cb);
59
60
  return () => {
60
61
  const idx = listeners[name].indexOf(cb);
61
- if (idx !== -1) listeners[name].splice(idx, 1);
62
+ if (idx !== -1) {listeners[name].splice(idx, 1);}
62
63
  };
63
64
  };
64
65
  };
@@ -77,7 +78,7 @@ export function createRequestHooks<R extends RequestInstance>(
77
78
  });
78
79
  },
79
80
  __snapshot() {
80
- const snap = {} as Record<HookName, Array<(...args: any[]) => void>>;
81
+ const snap = {} as Record<HookName, ((...args: any[]) => void)[]>;
81
82
  HOOK_NAMES.forEach((name) => {
82
83
  snap[name] = [...listeners[name]];
83
84
  });
@@ -1,3 +1,24 @@
1
+ import type { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
2
+ import type { ClientInstance } from "client";
3
+ import { Time } from "constants/time.constants";
4
+ import type { MockerConfigType, MockResponseType } from "mocker";
5
+ import type {
6
+ ExtractAdapterType,
7
+ ExtractClientAdapterType,
8
+ ExtractClientGlobalError,
9
+ ExtractEndpointType,
10
+ ExtractParamsType,
11
+ ExtractPayloadType,
12
+ ExtractQueryParamsType,
13
+ EmptyTypes,
14
+ ExtractAdapterMethodType,
15
+ ExtractAdapterOptionsType,
16
+ HydrateDataType,
17
+ SyncOrAsync,
18
+ } from "types";
19
+
20
+ import type { RequestHooks } from "./request.hooks";
21
+ import { createRequestHooks } from "./request.hooks";
1
22
  /* eslint-disable max-lines */
2
23
  import type {
3
24
  RequestSendOptionsType,
@@ -15,27 +36,7 @@ import type {
15
36
  RetryOnErrorCallbackType,
16
37
  OptimisticCallback,
17
38
  } from "./request.types";
18
- import type { RequestHooks } from "./request.hooks";
19
- import { createRequestHooks } from "./request.hooks";
20
39
  import { mapResponseForSend, sendRequest, scopeKey } from "./request.utils";
21
- import type { ClientInstance } from "client";
22
- import type { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
23
- import type {
24
- ExtractAdapterType,
25
- ExtractClientAdapterType,
26
- ExtractClientGlobalError,
27
- ExtractEndpointType,
28
- ExtractParamsType,
29
- ExtractPayloadType,
30
- ExtractQueryParamsType,
31
- EmptyTypes,
32
- ExtractAdapterMethodType,
33
- ExtractAdapterOptionsType,
34
- HydrateDataType,
35
- SyncOrAsync,
36
- } from "types";
37
- import { Time } from "constants/time.constants";
38
- import type { MockerConfigType, MockResponseType } from "mocker";
39
40
 
40
41
  type ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;
41
42
  type ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;
@@ -76,13 +77,13 @@ export class Request<
76
77
  MutationContext = undefined,
77
78
  > {
78
79
  endpoint: Endpoint;
79
- headers?: HeadersInit;
80
+ headers?: HeadersInit = undefined;
80
81
  auth: boolean;
81
82
  method: ClientAdapterMethod<Client>;
82
83
  params: ExtractUrlParams<Endpoint> | EmptyTypes;
83
84
  payload: PayloadType<Payload>;
84
85
  queryParams: QueryParams | EmptyTypes;
85
- options?: ClientAdapterOptions<Client> | undefined;
86
+ options?: ClientAdapterOptions<Client> | undefined = undefined;
86
87
  cancelable: boolean;
87
88
  retry: number;
88
89
  retryTime: number;
@@ -111,23 +112,37 @@ export class Request<
111
112
 
112
113
  isMockerEnabled = false;
113
114
 
115
+ static readonly OPTIONAL_FIELDS = [
116
+ "unstable_mock",
117
+ "unstable_payloadMapper",
118
+ "unstable_requestMapper",
119
+ "unstable_responseMapper",
120
+ "retryOnError",
121
+ "optimistic",
122
+ ] as const;
123
+
124
+ // The `= undefined` initializers below are load-bearing. Metro (React Native) compiles
125
+ // class properties in loose mode, which drops field declarations that have no initializer,
126
+ // and the SDK proxy relies on an `in` check to tell request properties apart from deeper
127
+ // API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).
114
128
  unstable_mock?: {
115
129
  fn: (options: {
116
130
  request: RequestInstance;
117
131
  requestId: string;
118
132
  }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
119
133
  config: MockerConfigType;
120
- };
134
+ } = undefined;
121
135
  /** @internal */
122
- unstable_payloadMapper?: PayloadMapperType<Payload>;
136
+ unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;
123
137
  /** @internal */
124
- unstable_requestMapper?: RequestMapper<any, any>;
138
+ unstable_requestMapper?: RequestMapper<any, any> = undefined;
125
139
  /** @internal */
126
- unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>>;
140
+ unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =
141
+ undefined;
127
142
  /** @internal */
128
- retryOnError?: RetryOnErrorCallbackType<RequestInstance>;
143
+ retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;
129
144
  /** @internal */
130
- optimistic?: OptimisticCallback<RequestInstance, any>;
145
+ optimistic?: OptimisticCallback<RequestInstance, any> = undefined;
131
146
 
132
147
  unstable_hasParams: HasParams = false as HasParams;
133
148
  unstable_hasPayload: HasPayload = false as HasPayload;
@@ -396,7 +411,7 @@ export class Request<
396
411
  public setPayloadMapper = <MappedPayload extends any | Promise<any>>(
397
412
  payloadMapper: (data: Payload) => MappedPayload,
398
413
  ) => {
399
- const cloned = this.clone<HasPayload, HasParams, HasQuery>(undefined);
414
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>();
400
415
 
401
416
  cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;
402
417
 
@@ -409,7 +424,7 @@ export class Request<
409
424
  * @returns new request
410
425
  */
411
426
  public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {
412
- const cloned = this.clone<HasPayload, HasParams, HasQuery>(undefined);
427
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>();
413
428
 
414
429
  cloned.unstable_requestMapper = requestMapper;
415
430
 
@@ -448,7 +463,7 @@ export class Request<
448
463
  let stringEndpoint = String(endpoint);
449
464
  if (params) {
450
465
  Object.entries(params).forEach(([key, value]) => {
451
- stringEndpoint = stringEndpoint.replace(new RegExp(`:${key}`, "g"), String(value));
466
+ stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, "g"), String(value));
452
467
  });
453
468
  }
454
469
 
@@ -588,7 +603,7 @@ export class Request<
588
603
  staleTime: this.staleTime,
589
604
  cacheKey: this.cacheKey,
590
605
  scope: this.scope,
591
- timestamp: +new Date(),
606
+ timestamp: Date.now(),
592
607
  hydrated: true,
593
608
  cache: true,
594
609
  response,
@@ -609,7 +624,7 @@ export class Request<
609
624
  staleTime: this.staleTime,
610
625
  cacheKey: this.cacheKey,
611
626
  scope: this.scope,
612
- timestamp: +new Date(),
627
+ timestamp: Date.now(),
613
628
  hydrated: true,
614
629
  cache: true,
615
630
  response: {
@@ -694,7 +709,7 @@ export class Request<
694
709
  * ```
695
710
  */
696
711
  public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
697
- const { dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
712
+ const { dispatcherType: _dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
698
713
 
699
714
  const request = this.clone(configuration) as unknown as this;
700
715
 
@@ -1,3 +1,6 @@
1
+ import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
2
+ import type { ClientInstance } from "client";
3
+ import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
1
4
  /* eslint-disable @typescript-eslint/no-shadow */
2
5
  import type {
3
6
  NullableKeys,
@@ -17,10 +20,8 @@ import type {
17
20
  ExtractAdapterMethodType,
18
21
  TypeWithDefaults,
19
22
  } from "types";
23
+
20
24
  import type { Request } from "./request";
21
- import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
22
- import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
23
- import type { ClientInstance } from "client";
24
25
 
25
26
  // Instance
26
27
 
@@ -1,8 +1,9 @@
1
1
  import { getErrorMessage } from "adapter";
2
- import { HttpMethods } from "constants/http.constants";
3
2
  import type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from "adapter";
3
+ import { SAFE_HTTP_METHODS } from "constants/http.constants";
4
4
  import type { Dispatcher } from "dispatcher";
5
5
  import type { ExtractAdapterType, ExtractErrorType } from "types";
6
+
6
7
  import type {
7
8
  OptimisticCallbackResult,
8
9
  ProgressEventType,
@@ -17,18 +18,18 @@ export const scopeKey = (key: string, scope: string | null): string => {
17
18
 
18
19
  export const stringifyKey = (value: unknown): string => {
19
20
  try {
20
- if (typeof value === "string") return value;
21
- if (value === undefined || value === null) return "";
21
+ if (typeof value === "string") {return value;}
22
+ if (value === undefined || value === null) {return "";}
22
23
  const data = JSON.stringify(value);
23
- if (typeof data !== "string") throw new Error();
24
+ if (typeof data !== "string") {throw new TypeError();}
24
25
  return data;
25
- } catch (_) {
26
+ } catch {
26
27
  return "";
27
28
  }
28
29
  };
29
30
 
30
31
  export const getProgressValue = ({ loaded, total }: ProgressEventType): number => {
31
- if (!loaded || !total) return 0;
32
+ if (!loaded || !total) {return 0;}
32
33
  return Number(((loaded * 100) / total).toFixed(0));
33
34
  };
34
35
 
@@ -115,8 +116,8 @@ export const getRequestDispatcher = <Request extends RequestInstance>(
115
116
  dispatcherType: "auto" | "fetch" | "submit" = "auto",
116
117
  ): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {
117
118
  const { fetchDispatcher, submitDispatcher } = request.client;
118
- const isGet = request.method === HttpMethods.GET;
119
- const isFetchDispatcher = (dispatcherType === "auto" && isGet) || dispatcherType === "fetch";
119
+ const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);
120
+ const isFetchDispatcher = (dispatcherType === "auto" && isSafeRead) || dispatcherType === "fetch";
120
121
  const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;
121
122
 
122
123
  return [dispatcher, isFetchDispatcher];
@@ -152,17 +153,17 @@ export const sendRequest = async <Request extends RequestInstance>(
152
153
  client: request.client,
153
154
  payload: request.payload,
154
155
  });
155
- } catch (err) {
156
+ } catch (error) {
156
157
  return {
157
158
  data: null,
158
159
  error: new Error(
159
- `Optimistic callback failed: ${err instanceof Error ? err.message : err}`,
160
+ `Optimistic callback failed: ${error instanceof Error ? error.message : error}`,
160
161
  ) as unknown as ExtractErrorType<Request>,
161
162
  status: null,
162
163
  success: false,
163
164
  extra: client.adapter.defaultExtra,
164
- requestTimestamp: +new Date(),
165
- responseTimestamp: +new Date(),
165
+ requestTimestamp: Date.now(),
166
+ responseTimestamp: Date.now(),
166
167
  };
167
168
  }
168
169
  }
@@ -214,10 +215,10 @@ export const sendRequest = async <Request extends RequestInstance>(
214
215
 
215
216
  const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {
216
217
  // When going offline we can't handle the request as it will be postponed to later resolve
217
- if (!success && isOfflineStatus) return;
218
+ if (!success && isOfflineStatus) {return;}
218
219
 
219
220
  // When request is in retry mode we need to listen for retries end
220
- if (!success && willRetry) return;
221
+ if (!success && willRetry) {return;}
221
222
 
222
223
  options?.onResponse?.(enrichedValues);
223
224
  $hooks.__emit("onResponse", enrichedValues);
@@ -257,8 +258,8 @@ export const sendRequest = async <Request extends RequestInstance>(
257
258
  success: false,
258
259
  error: getErrorMessage("deleted") as unknown as ExtractErrorType<Request>,
259
260
  extra: request.client.adapter.defaultExtra,
260
- requestTimestamp: +new Date(),
261
- responseTimestamp: +new Date(),
261
+ requestTimestamp: Date.now(),
262
+ responseTimestamp: Date.now(),
262
263
  });
263
264
 
264
265
  // Unmount Listeners
package/src/sdk/sdk.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ClientInstance } from "client";
2
- import type { Request, RequestInstance } from "request";
2
+ import type { RequestInstance } from "request";
3
+ import { Request } from "request";
3
4
  import type {
4
5
  ExtractEndpointType,
5
6
  ExtractResponseType,
@@ -136,14 +137,16 @@ export type CreateSdkOptions<Schema extends RecursiveSchemaType = RecursiveSchem
136
137
  defaults?: SdkConfigurationMap<Schema>;
137
138
  };
138
139
 
140
+ const OPTIONAL_REQUEST_FIELDS = Request.OPTIONAL_FIELDS;
141
+
139
142
  const getMethod = (key: string, options?: CreateSdkOptions<any>) => {
140
143
  const { methodTransform = (method: string) => method.toUpperCase() } = options ?? {};
141
144
  return methodTransform(key);
142
145
  };
143
146
 
144
147
  const endpointMatchesPattern = (endpoint: string, pattern: string): boolean => {
145
- if (pattern === "*") return true;
146
- if (pattern === endpoint) return true;
148
+ if (pattern === "*") {return true;}
149
+ if (pattern === endpoint) {return true;}
147
150
  // Simple wildcard: "/users/*" matches "/users/:userId", "/users/:userId/posts", etc.
148
151
  if (pattern.endsWith("/*")) {
149
152
  const prefix = pattern.slice(0, -1);
@@ -158,17 +161,17 @@ const isDotPath = (key: string): boolean => {
158
161
 
159
162
  const applyObjectDefaults = (request: RequestInstance, config: SdkRequestDefaults): RequestInstance => {
160
163
  let result = request;
161
- if (config.headers) result = result.setHeaders(config.headers);
162
- if (config.auth !== undefined) result = result.setAuth(config.auth);
163
- if (config.cache !== undefined) result = result.setCache(config.cache);
164
- if (config.cacheTime !== undefined) result = result.setCacheTime(config.cacheTime);
165
- if (config.staleTime !== undefined) result = result.setStaleTime(config.staleTime);
166
- if (config.retry !== undefined) result = result.setRetry(config.retry);
167
- if (config.retryTime !== undefined) result = result.setRetryTime(config.retryTime);
168
- if (config.cancelable !== undefined) result = result.setCancelable(config.cancelable);
169
- if (config.queued !== undefined) result = result.setQueued(config.queued);
170
- if (config.offline !== undefined) result = result.setOffline(config.offline);
171
- if (config.deduplicate !== undefined) result = result.setDeduplicate(config.deduplicate);
164
+ if (config.headers) {result = result.setHeaders(config.headers);}
165
+ if (config.auth !== undefined) {result = result.setAuth(config.auth);}
166
+ if (config.cache !== undefined) {result = result.setCache(config.cache);}
167
+ if (config.cacheTime !== undefined) {result = result.setCacheTime(config.cacheTime);}
168
+ if (config.staleTime !== undefined) {result = result.setStaleTime(config.staleTime);}
169
+ if (config.retry !== undefined) {result = result.setRetry(config.retry);}
170
+ if (config.retryTime !== undefined) {result = result.setRetryTime(config.retryTime);}
171
+ if (config.cancelable !== undefined) {result = result.setCancelable(config.cancelable);}
172
+ if (config.queued !== undefined) {result = result.setQueued(config.queued);}
173
+ if (config.offline !== undefined) {result = result.setOffline(config.offline);}
174
+ if (config.deduplicate !== undefined) {result = result.setDeduplicate(config.deduplicate);}
172
175
  if (config.deduplicateTime !== undefined && config.deduplicateTime !== null) {
173
176
  result = result.setDeduplicateTime(config.deduplicateTime);
174
177
  }
@@ -180,7 +183,7 @@ const applyDefaults = (
180
183
  context: { endpoint: string; sdkPath: string; defaults?: Partial<Record<string, SdkConfigurationValue>> },
181
184
  ): RequestInstance => {
182
185
  const { endpoint, sdkPath, defaults } = context;
183
- if (!defaults) return request;
186
+ if (!defaults) {return request;}
184
187
 
185
188
  let result = request;
186
189
  const entries = Object.entries(defaults);
@@ -192,7 +195,7 @@ const applyDefaults = (
192
195
 
193
196
  for (let i = 0; i < entries.length; i += 1) {
194
197
  const [key, value] = entries[i];
195
- if (!value) continue;
198
+ if (!value) {continue;}
196
199
  const entry: [string, SdkConfigurationValue] = [key, value];
197
200
  if (entry[0] === "*") {
198
201
  globalEntries.push(entry);
@@ -236,7 +239,7 @@ const createRecursiveProxy = (
236
239
  return new Proxy(() => {}, {
237
240
  get: (_target, key: string) => {
238
241
  if (typeof key === "symbol" || key === "inspect") {
239
- return undefined;
242
+ return;
240
243
  }
241
244
 
242
245
  // Check if this is a method (starts with $) or a path segment
@@ -249,7 +252,7 @@ const createRecursiveProxy = (
249
252
  methodName = key.slice(1);
250
253
  pathSegment = `:${key.slice(1)}`;
251
254
  } else if (options?.camelCaseToKebabCase) {
252
- pathSegment = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
255
+ pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
253
256
  }
254
257
 
255
258
  // Build the sdk dot-path for method-specific configuration matching
@@ -270,7 +273,11 @@ const createRecursiveProxy = (
270
273
  return new Proxy(request, {
271
274
  get: (reqTarget, reqKey: string) => {
272
275
  // If the property exists on the request instance (like .send(), .setParams()), return it.
273
- if (reqKey in reqTarget) {
276
+ // Optional fields are checked by name as well: transpilers that compile class
277
+ // properties in loose mode (Metro on React Native) drop uninitialized field
278
+ // declarations, and falling through to the deeper proxy would hand callers a
279
+ // truthy path proxy where they expect undefined.
280
+ if (reqKey in reqTarget || (OPTIONAL_REQUEST_FIELDS as readonly string[]).includes(reqKey)) {
274
281
  return reqTarget[reqKey as keyof typeof reqTarget];
275
282
  }
276
283
  // Otherwise, it's a deeper path, so delegate to the deeper proxy.
@@ -1,2 +1,2 @@
1
- export type HttpMethodsType = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1
+ export type HttpMethodsType = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "QUERY";
2
2
  export type HttpStatusType = number;
@@ -1,9 +1,10 @@
1
1
  import type { ResponseType } from "adapter";
2
+ import type { Client, ClientInstance } from "client";
2
3
  import type { ExtractUrlParams, Request, RequestInstance } from "request";
4
+
5
+ import type { ExtractAdapterEndpointType } from "./adapter.types";
3
6
  import type { ExtractClientAdapterType, ExtractClientGlobalError } from "./client.types";
4
- import type { Client, ClientInstance } from "client";
5
7
  import type { TypeWithDefaults } from "./helpers.types";
6
- import type { ExtractAdapterEndpointType } from "./adapter.types";
7
8
 
8
9
  export type ExtractAdapterResolvedType<T extends RequestInstance> = ResponseType<
9
10
  ExtractResponseType<T>,
@@ -3,7 +3,7 @@ import Emitter from "events";
3
3
  const getListenName = (event: string | symbol) => `listen_${String(event)}`;
4
4
 
5
5
  export class EventEmitter extends Emitter {
6
- emitCallbacks: Array<(event: string, data: any, isTriggeredExternally?: true) => void> = [];
6
+ emitCallbacks: ((event: string, data: any, isTriggeredExternally?: true) => void)[] = [];
7
7
 
8
8
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
9
9
  constructor(options?: ConstructorParameters<typeof Emitter>[0]) {
@@ -1,5 +1,5 @@
1
1
  import type { RequestInstance } from "request";
2
2
 
3
3
  export const getUniqueRequestId = (request: Pick<RequestInstance, "queryKey">) => {
4
- return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2)}`;
4
+ return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;
5
5
  };
package/tsconfig.json CHANGED
@@ -1,10 +1,38 @@
1
1
  {
2
2
  "extends": "../../tsconfig.json",
3
3
  "compilerOptions": {
4
- "baseUrl": "./src",
4
+ "types": ["node"],
5
5
  "paths": {
6
- "@hyper-fetch/core": ["../src"]
6
+ "adapter": ["./src/adapter"],
7
+ "adapter/*": ["./src/adapter/*"],
8
+ "cache": ["./src/cache"],
9
+ "cache/*": ["./src/cache/*"],
10
+ "client": ["./src/client"],
11
+ "client/*": ["./src/client/*"],
12
+ "constants": ["./src/constants"],
13
+ "constants/*": ["./src/constants/*"],
14
+ "dispatcher": ["./src/dispatcher"],
15
+ "dispatcher/*": ["./src/dispatcher/*"],
16
+ "http-adapter": ["./src/http-adapter"],
17
+ "http-adapter/*": ["./src/http-adapter/*"],
18
+ "managers": ["./src/managers"],
19
+ "managers/*": ["./src/managers/*"],
20
+ "mocker": ["./src/mocker"],
21
+ "mocker/*": ["./src/mocker/*"],
22
+ "plugin": ["./src/plugin"],
23
+ "plugin/*": ["./src/plugin/*"],
24
+ "request": ["./src/request"],
25
+ "request/*": ["./src/request/*"],
26
+ "sdk": ["./src/sdk"],
27
+ "sdk/*": ["./src/sdk/*"],
28
+ "types": ["./src/types"],
29
+ "types/*": ["./src/types/*"],
30
+ "utils": ["./src/utils"],
31
+ "utils/*": ["./src/utils/*"],
32
+ "index": ["./src/index"],
33
+ "@hyper-fetch/core": ["./src"]
7
34
  }
8
35
  },
36
+ "include": ["src/**/*.ts", "../../global.d.ts"],
9
37
  "exclude": ["node_modules", "dist", "vite.config.ts", "__tests__"]
10
38
  }