@hyper-fetch/core 7.5.3 → 8.0.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 (270) hide show
  1. package/.eslintrc.cjs +12 -0
  2. package/__tests__/e2e/e2e.abort-timeout.spec.ts +101 -0
  3. package/__tests__/e2e/e2e.advanced.spec.ts +423 -0
  4. package/__tests__/e2e/e2e.methods.spec.ts +243 -0
  5. package/__tests__/e2e/e2e.payloads.spec.ts +154 -0
  6. package/__tests__/features/adapter/adapter.base.spec.ts +44 -17
  7. package/__tests__/features/adapter/adapter.bindings.spec.ts +35 -33
  8. package/__tests__/features/adapter/adapter.browser.spec.ts +5 -20
  9. package/__tests__/features/adapter/adapter.server.spec.ts +229 -37
  10. package/__tests__/features/cache/cache.base.spec.ts +23 -15
  11. package/__tests__/features/cache/cache.events.spec.ts +9 -5
  12. package/__tests__/features/cache/cache.garbage-collector.spec.ts +9 -6
  13. package/__tests__/features/cache/cache.lazy-storage.spec.ts +11 -8
  14. package/__tests__/features/cache/cache.modes.spec.ts +145 -0
  15. package/__tests__/features/cache/cache.scoping.spec.ts +171 -0
  16. package/__tests__/features/cache/cache.typescript.spec.ts +147 -0
  17. package/__tests__/features/cache/cache.utils.spec.ts +10 -3
  18. package/__tests__/features/client/client.auth.spec.ts +5 -5
  19. package/__tests__/features/client/client.base.spec.ts +16 -4
  20. package/__tests__/features/client/client.from-json.spec.ts +182 -0
  21. package/__tests__/features/client/client.hydration.spec.ts +69 -4
  22. package/__tests__/features/client/client.interceptor.spec.ts +4 -4
  23. package/__tests__/features/client/client.methods.spec.ts +5 -4
  24. package/__tests__/features/client/client.middleware.spec.ts +4 -4
  25. package/__tests__/features/client/client.utils.spec.ts +3 -3
  26. package/__tests__/features/dispatcher/dispatcher.base.spec.ts +8 -8
  27. package/__tests__/features/dispatcher/dispatcher.custom-storage.spec.ts +189 -0
  28. package/__tests__/features/dispatcher/dispatcher.events.spec.ts +17 -12
  29. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +31 -31
  30. package/__tests__/features/dispatcher/dispatcher.requests.spec.ts +15 -15
  31. package/__tests__/features/dispatcher/dispatcher.utils.spec.ts +22 -5
  32. package/__tests__/features/managers/app/app.manager.base.spec.ts +23 -23
  33. package/__tests__/features/managers/app/app.manager.ssr.spec.ts +6 -3
  34. package/__tests__/features/managers/logger/logger.base.spec.ts +4 -2
  35. package/__tests__/features/managers/logger/logger.utils.spec.ts +10 -4
  36. package/__tests__/features/managers/request/request.manager.base.spec.ts +21 -19
  37. package/__tests__/features/managers/request/request.manager.events.spec.ts +137 -53
  38. package/__tests__/features/mocker/mocker.base.spec.ts +82 -10
  39. package/__tests__/features/plugin/plugin.base.spec.ts +19 -19
  40. package/__tests__/features/request/request.base.spec.ts +39 -13
  41. package/__tests__/features/request/request.cloning.spec.ts +1 -1
  42. package/__tests__/features/request/request.hooks.spec.ts +173 -0
  43. package/__tests__/features/request/request.optimistic.spec.ts +93 -0
  44. package/__tests__/features/request/request.retry-on-error.spec.ts +359 -0
  45. package/__tests__/features/request/request.sending.spec.ts +107 -15
  46. package/__tests__/features/request/request.setters.spec.ts +11 -4
  47. package/__tests__/features/request/request.typescript.spec.ts +1 -1
  48. package/__tests__/features/request/request.utils.spec.ts +2 -2
  49. package/__tests__/features/sdk/sdk.base.spec.ts +5 -3
  50. package/__tests__/features/sdk/sdk.configuration.spec.ts +262 -0
  51. package/__tests__/features/utils/emitter.utils.spec.ts +88 -0
  52. package/__tests__/shared/callbacks.shared.ts +3 -1
  53. package/__tests__/shared/progress.shared.ts +2 -1
  54. package/__tests__/tsconfig.json +14 -3
  55. package/__tests__/type-stress/generate-stress-test.ts +92 -0
  56. package/__tests__/type-stress/stress-10.ts +35 -0
  57. package/__tests__/type-stress/stress-just-create.ts +2107 -0
  58. package/__tests__/type-stress/stress-minimal.ts +23 -0
  59. package/__tests__/type-stress/stress-test-500.ts +2319 -0
  60. package/__tests__/type-stress/stress-test-sdk.ts +210 -0
  61. package/__tests__/type-stress/tsconfig.json +6 -0
  62. package/__tests__/utils/adapter.utils.ts +3 -2
  63. package/__tests__/utils/cache.utils.ts +3 -2
  64. package/__tests__/utils/callbacks.utils.ts +5 -4
  65. package/__tests__/utils/dispatcher.utils.ts +3 -2
  66. package/__tests__/vitest.setup.ts +15 -0
  67. package/dist/adapter/adapter.bindings.d.ts +71 -0
  68. package/dist/adapter/adapter.bindings.d.ts.map +1 -0
  69. package/dist/adapter/adapter.d.ts +127 -0
  70. package/dist/adapter/adapter.d.ts.map +1 -0
  71. package/dist/adapter/adapter.types.d.ts +108 -0
  72. package/dist/adapter/adapter.types.d.ts.map +1 -0
  73. package/dist/adapter/adapter.utils.d.ts +23 -0
  74. package/dist/adapter/adapter.utils.d.ts.map +1 -0
  75. package/dist/adapter/index.d.ts +5 -0
  76. package/dist/adapter/index.d.ts.map +1 -0
  77. package/dist/cache/cache.d.ts +95 -0
  78. package/dist/cache/cache.d.ts.map +1 -0
  79. package/dist/cache/cache.events.d.ts +51 -0
  80. package/dist/cache/cache.events.d.ts.map +1 -0
  81. package/dist/cache/cache.types.d.ts +44 -0
  82. package/dist/cache/cache.types.d.ts.map +1 -0
  83. package/dist/cache/cache.utils.d.ts +11 -0
  84. package/dist/cache/cache.utils.d.ts.map +1 -0
  85. package/dist/cache/index.d.ts +5 -0
  86. package/dist/cache/index.d.ts.map +1 -0
  87. package/dist/client/client.constants.d.ts +10 -0
  88. package/dist/client/client.constants.d.ts.map +1 -0
  89. package/dist/client/client.create.d.ts +8 -0
  90. package/dist/client/client.create.d.ts.map +1 -0
  91. package/dist/client/client.d.ts +195 -0
  92. package/dist/client/client.d.ts.map +1 -0
  93. package/dist/client/client.types.d.ts +71 -0
  94. package/dist/client/client.types.d.ts.map +1 -0
  95. package/dist/client/client.utils.d.ts +11 -0
  96. package/dist/client/client.utils.d.ts.map +1 -0
  97. package/dist/client/index.d.ts +6 -0
  98. package/dist/client/index.d.ts.map +1 -0
  99. package/dist/constants/http.constants.d.ts +8 -0
  100. package/dist/constants/http.constants.d.ts.map +1 -0
  101. package/dist/constants/time.constants.d.ts +12 -0
  102. package/dist/constants/time.constants.d.ts.map +1 -0
  103. package/dist/dispatcher/dispatcher.constants.d.ts +7 -0
  104. package/dist/dispatcher/dispatcher.constants.d.ts.map +1 -0
  105. package/dist/dispatcher/dispatcher.d.ts +168 -0
  106. package/dist/dispatcher/dispatcher.d.ts.map +1 -0
  107. package/dist/dispatcher/dispatcher.events.d.ts +49 -0
  108. package/dist/dispatcher/dispatcher.events.d.ts.map +1 -0
  109. package/dist/dispatcher/dispatcher.types.d.ts +44 -0
  110. package/dist/dispatcher/dispatcher.types.d.ts.map +1 -0
  111. package/dist/dispatcher/dispatcher.utils.d.ts +12 -0
  112. package/dist/dispatcher/dispatcher.utils.d.ts.map +1 -0
  113. package/dist/dispatcher/index.d.ts +6 -0
  114. package/dist/dispatcher/index.d.ts.map +1 -0
  115. package/dist/http-adapter/http-adapter.constants.d.ts +4 -0
  116. package/dist/http-adapter/http-adapter.constants.d.ts.map +1 -0
  117. package/dist/http-adapter/http-adapter.d.ts +3 -0
  118. package/dist/http-adapter/http-adapter.d.ts.map +1 -0
  119. package/dist/http-adapter/http-adapter.fetch.d.ts +6 -0
  120. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -0
  121. package/dist/http-adapter/http-adapter.types.d.ts +73 -0
  122. package/dist/http-adapter/http-adapter.types.d.ts.map +1 -0
  123. package/dist/http-adapter/http-adapter.utils.d.ts +10 -0
  124. package/dist/http-adapter/http-adapter.utils.d.ts.map +1 -0
  125. package/dist/http-adapter/index.d.ts +6 -0
  126. package/dist/http-adapter/index.d.ts.map +1 -0
  127. package/dist/index.d.ts +15 -2083
  128. package/dist/index.d.ts.map +1 -0
  129. package/dist/index.mjs +4084 -0
  130. package/dist/index.mjs.map +1 -0
  131. package/dist/managers/app/app.manager.constants.d.ts +10 -0
  132. package/dist/managers/app/app.manager.constants.d.ts.map +1 -0
  133. package/dist/managers/app/app.manager.d.ts +35 -0
  134. package/dist/managers/app/app.manager.d.ts.map +1 -0
  135. package/dist/managers/app/app.manager.events.d.ts +12 -0
  136. package/dist/managers/app/app.manager.events.d.ts.map +1 -0
  137. package/dist/managers/app/app.manager.types.d.ts +7 -0
  138. package/dist/managers/app/app.manager.types.d.ts.map +1 -0
  139. package/dist/managers/app/app.manager.utils.d.ts +5 -0
  140. package/dist/managers/app/app.manager.utils.d.ts.map +1 -0
  141. package/dist/managers/app/index.d.ts +6 -0
  142. package/dist/managers/app/index.d.ts.map +1 -0
  143. package/dist/managers/index.d.ts +4 -0
  144. package/dist/managers/index.d.ts.map +1 -0
  145. package/dist/managers/logger/index.d.ts +5 -0
  146. package/dist/managers/logger/index.d.ts.map +1 -0
  147. package/dist/managers/logger/logger.manager.constants.d.ts +5 -0
  148. package/dist/managers/logger/logger.manager.constants.d.ts.map +1 -0
  149. package/dist/managers/logger/logger.manager.d.ts +22 -0
  150. package/dist/managers/logger/logger.manager.d.ts.map +1 -0
  151. package/dist/managers/logger/logger.manager.types.d.ts +43 -0
  152. package/dist/managers/logger/logger.manager.types.d.ts.map +1 -0
  153. package/dist/managers/logger/logger.manager.utils.d.ts +4 -0
  154. package/dist/managers/logger/logger.manager.utils.d.ts.map +1 -0
  155. package/dist/managers/request/index.d.ts +5 -0
  156. package/dist/managers/request/index.d.ts.map +1 -0
  157. package/dist/managers/request/request.manager.d.ts +60 -0
  158. package/dist/managers/request/request.manager.d.ts.map +1 -0
  159. package/dist/managers/request/request.manager.events.d.ts +55 -0
  160. package/dist/managers/request/request.manager.events.d.ts.map +1 -0
  161. package/dist/managers/request/request.manager.types.d.ts +48 -0
  162. package/dist/managers/request/request.manager.types.d.ts.map +1 -0
  163. package/dist/managers/request/request.manager.utils.d.ts +30 -0
  164. package/dist/managers/request/request.manager.utils.d.ts.map +1 -0
  165. package/dist/mocker/index.d.ts +3 -0
  166. package/dist/mocker/index.d.ts.map +1 -0
  167. package/dist/mocker/mocker.d.ts +3 -0
  168. package/dist/mocker/mocker.d.ts.map +1 -0
  169. package/dist/mocker/mocker.types.d.ts +25 -0
  170. package/dist/mocker/mocker.types.d.ts.map +1 -0
  171. package/dist/plugin/index.d.ts +3 -0
  172. package/dist/plugin/index.d.ts.map +1 -0
  173. package/dist/plugin/plugin.d.ts +55 -0
  174. package/dist/plugin/plugin.d.ts.map +1 -0
  175. package/dist/plugin/plugin.types.d.ts +122 -0
  176. package/dist/plugin/plugin.types.d.ts.map +1 -0
  177. package/dist/request/index.d.ts +5 -0
  178. package/dist/request/index.d.ts.map +1 -0
  179. package/dist/request/request.d.ts +195 -0
  180. package/dist/request/request.d.ts.map +1 -0
  181. package/dist/request/request.hooks.d.ts +19 -0
  182. package/dist/request/request.hooks.d.ts.map +1 -0
  183. package/dist/request/request.types.d.ts +240 -0
  184. package/dist/request/request.types.d.ts.map +1 -0
  185. package/dist/request/request.utils.d.ts +25 -0
  186. package/dist/request/request.utils.d.ts.map +1 -0
  187. package/dist/sdk/index.d.ts +2 -0
  188. package/dist/sdk/index.d.ts.map +1 -0
  189. package/dist/sdk/sdk.d.ts +69 -0
  190. package/dist/sdk/sdk.d.ts.map +1 -0
  191. package/dist/types/adapter.types.d.ts +22 -0
  192. package/dist/types/adapter.types.d.ts.map +1 -0
  193. package/dist/types/client.types.d.ts +4 -0
  194. package/dist/types/client.types.d.ts.map +1 -0
  195. package/dist/types/helpers.types.d.ts +17 -0
  196. package/dist/types/helpers.types.d.ts.map +1 -0
  197. package/dist/types/http.types.d.ts +3 -0
  198. package/dist/types/http.types.d.ts.map +1 -0
  199. package/dist/types/hydration.types.d.ts +15 -0
  200. package/dist/types/hydration.types.d.ts.map +1 -0
  201. package/dist/types/index.d.ts +7 -0
  202. package/dist/types/index.d.ts.map +1 -0
  203. package/dist/types/request.types.d.ts +34 -0
  204. package/dist/types/request.types.d.ts.map +1 -0
  205. package/dist/utils/emitter.utils.d.ts +13 -0
  206. package/dist/utils/emitter.utils.d.ts.map +1 -0
  207. package/dist/utils/index.d.ts +3 -0
  208. package/dist/utils/index.d.ts.map +1 -0
  209. package/dist/utils/uuid.utils.d.ts +3 -0
  210. package/dist/utils/uuid.utils.d.ts.map +1 -0
  211. package/package.json +10 -25
  212. package/src/adapter/adapter.bindings.ts +8 -12
  213. package/src/adapter/adapter.ts +8 -7
  214. package/src/adapter/adapter.types.ts +10 -6
  215. package/src/adapter/adapter.utils.ts +1 -1
  216. package/src/cache/cache.events.ts +4 -11
  217. package/src/cache/cache.ts +28 -22
  218. package/src/cache/cache.types.ts +8 -4
  219. package/src/cache/cache.utils.ts +3 -3
  220. package/src/client/client.create.ts +4 -3
  221. package/src/client/client.ts +44 -12
  222. package/src/client/client.types.ts +25 -3
  223. package/src/client/client.utils.ts +24 -4
  224. package/src/dispatcher/dispatcher.events.ts +3 -3
  225. package/src/dispatcher/dispatcher.ts +59 -28
  226. package/src/dispatcher/dispatcher.types.ts +19 -2
  227. package/src/dispatcher/dispatcher.utils.ts +5 -4
  228. package/src/http-adapter/http-adapter.constants.ts +1 -1
  229. package/src/http-adapter/http-adapter.fetch.ts +174 -0
  230. package/src/http-adapter/http-adapter.ts +3 -8
  231. package/src/http-adapter/http-adapter.types.ts +17 -9
  232. package/src/http-adapter/http-adapter.utils.ts +6 -9
  233. package/src/http-adapter/index.ts +1 -0
  234. package/src/managers/app/app.manager.constants.ts +2 -2
  235. package/src/managers/app/app.manager.events.ts +1 -1
  236. package/src/managers/app/app.manager.ts +2 -1
  237. package/src/managers/logger/logger.manager.constants.ts +1 -1
  238. package/src/managers/logger/logger.manager.ts +2 -1
  239. package/src/managers/logger/logger.manager.types.ts +2 -2
  240. package/src/managers/logger/logger.manager.utils.ts +2 -1
  241. package/src/managers/request/request.manager.events.ts +13 -11
  242. package/src/managers/request/request.manager.types.ts +6 -3
  243. package/src/mocker/mocker.ts +3 -2
  244. package/src/mocker/mocker.types.ts +1 -1
  245. package/src/plugin/plugin.ts +2 -2
  246. package/src/plugin/plugin.types.ts +9 -9
  247. package/src/request/index.ts +1 -0
  248. package/src/request/request.hooks.ts +87 -0
  249. package/src/request/request.ts +155 -77
  250. package/src/request/request.types.ts +54 -22
  251. package/src/request/request.utils.ts +86 -23
  252. package/src/sdk/sdk.ts +153 -8
  253. package/src/types/adapter.types.ts +1 -1
  254. package/src/types/client.types.ts +1 -1
  255. package/src/types/hydration.types.ts +3 -3
  256. package/src/types/request.types.ts +30 -20
  257. package/src/utils/uuid.utils.ts +1 -1
  258. package/tsconfig.base.json +1 -6
  259. package/tsconfig.json +1 -4
  260. package/vite.config.ts +45 -0
  261. package/.eslintrc.json +0 -11
  262. package/__tests__/global.d.ts +0 -1
  263. package/__tests__/jest.setup.ts +0 -13
  264. package/dist/browser/index.js +0 -3751
  265. package/dist/browser/index.js.map +0 -7
  266. package/dist/index.js +0 -4002
  267. package/dist/index.js.map +0 -7
  268. package/jest.config.ts +0 -6
  269. package/src/http-adapter/http-adapter.browser.ts +0 -102
  270. package/src/http-adapter/http-adapter.server.ts +0 -149
package/dist/index.js DELETED
@@ -1,4002 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __spreadValues = (a, b) => {
14
- for (var prop in b || (b = {}))
15
- if (__hasOwnProp.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- if (__getOwnPropSymbols)
18
- for (var prop of __getOwnPropSymbols(b)) {
19
- if (__propIsEnum.call(b, prop))
20
- __defNormalProp(a, prop, b[prop]);
21
- }
22
- return a;
23
- };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
- var __objRest = (source, exclude) => {
26
- var target = {};
27
- for (var prop in source)
28
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
- target[prop] = source[prop];
30
- if (source != null && __getOwnPropSymbols)
31
- for (var prop of __getOwnPropSymbols(source)) {
32
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
- target[prop] = source[prop];
34
- }
35
- return target;
36
- };
37
- var __export = (target, all) => {
38
- for (var name in all)
39
- __defProp(target, name, { get: all[name], enumerable: true });
40
- };
41
- var __copyProps = (to, from, except, desc) => {
42
- if (from && typeof from === "object" || typeof from === "function") {
43
- for (let key of __getOwnPropNames(from))
44
- if (!__hasOwnProp.call(to, key) && key !== except)
45
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
- }
47
- return to;
48
- };
49
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
- // If the importer is in node compatibility mode or this is not an ESM
51
- // file that has been converted to a CommonJS file using a Babel-
52
- // compatible transform (i.e. "__esModule" has not been set), then set
53
- // "default" to the CommonJS "module.exports" for node compatibility.
54
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
- mod
56
- ));
57
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
59
- var __async = (__this, __arguments, generator) => {
60
- return new Promise((resolve, reject) => {
61
- var fulfilled = (value) => {
62
- try {
63
- step(generator.next(value));
64
- } catch (e) {
65
- reject(e);
66
- }
67
- };
68
- var rejected = (value) => {
69
- try {
70
- step(generator.throw(value));
71
- } catch (e) {
72
- reject(e);
73
- }
74
- };
75
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
76
- step((generator = generator.apply(__this, __arguments)).next());
77
- });
78
- };
79
-
80
- // src/index.ts
81
- var index_exports = {};
82
- __export(index_exports, {
83
- AbortError: () => AbortError,
84
- Adapter: () => Adapter,
85
- AppEvents: () => AppEvents,
86
- AppManager: () => AppManager,
87
- Cache: () => Cache,
88
- Client: () => Client,
89
- DeletedError: () => DeletedError,
90
- Dispatcher: () => Dispatcher,
91
- DispatcherMode: () => DispatcherMode,
92
- EventEmitter: () => EventEmitter,
93
- HttpAdapter: () => HttpAdapter,
94
- HttpMethods: () => HttpMethods,
95
- LoggerManager: () => LoggerManager,
96
- Plugin: () => Plugin,
97
- Request: () => Request,
98
- RequestManager: () => RequestManager,
99
- RequestProcessingError: () => RequestProcessingError,
100
- Time: () => Time,
101
- TimeoutError: () => TimeoutError,
102
- UnexpectedError: () => UnexpectedError,
103
- appManagerInitialOptions: () => appManagerInitialOptions,
104
- canRetryRequest: () => canRetryRequest,
105
- createClient: () => createClient,
106
- createSdk: () => createSdk,
107
- defaultMapper: () => defaultMapper,
108
- defaultTimeout: () => defaultTimeout,
109
- getAbortByAbortKey: () => getAbortByAbortKey,
110
- getAbortByIdKey: () => getAbortByIdKey,
111
- getAbortKey: () => getAbortKey,
112
- getAdapterBindings: () => getAdapterBindings,
113
- getAdapterHeaders: () => getAdapterHeaders,
114
- getAdapterOnError: () => getAdapterOnError,
115
- getAdapterPayload: () => getAdapterPayload,
116
- getAppManagerEvents: () => getAppManagerEvents,
117
- getCacheByKey: () => getCacheByKey,
118
- getCacheData: () => getCacheData,
119
- getCacheEvents: () => getCacheEvents,
120
- getCacheKey: () => getCacheKey,
121
- getDeleteByKey: () => getDeleteByKey,
122
- getDeleteKey: () => getDeleteKey,
123
- getDispatcherChangeByKey: () => getDispatcherChangeByKey,
124
- getDispatcherChangeKey: () => getDispatcherChangeKey,
125
- getDispatcherDrainedByKey: () => getDispatcherDrainedByKey,
126
- getDispatcherDrainedKey: () => getDispatcherDrainedKey,
127
- getDispatcherEvents: () => getDispatcherEvents,
128
- getDispatcherStatusByKey: () => getDispatcherStatusByKey,
129
- getDispatcherStatusKey: () => getDispatcherStatusKey,
130
- getDownloadProgressByIdKey: () => getDownloadProgressByIdKey,
131
- getDownloadProgressByQueryKey: () => getDownloadProgressByQueryKey,
132
- getDownloadProgressKey: () => getDownloadProgressKey,
133
- getErrorMessage: () => getErrorMessage,
134
- getInvalidateByKey: () => getInvalidateByKey,
135
- getInvalidateKey: () => getInvalidateKey,
136
- getIsEqualTimestamp: () => getIsEqualTimestamp,
137
- getLoadingByCacheKey: () => getLoadingByCacheKey,
138
- getLoadingByIdKey: () => getLoadingByIdKey,
139
- getLoadingByQueryKey: () => getLoadingByQueryKey,
140
- getLoadingKey: () => getLoadingKey,
141
- getProgressData: () => getProgressData,
142
- getProgressValue: () => getProgressValue,
143
- getRemoveByIdKey: () => getRemoveByIdKey,
144
- getRemoveByQueryKey: () => getRemoveByQueryKey,
145
- getRemoveKey: () => getRemoveKey,
146
- getRequestDeduplicatedByCacheKey: () => getRequestDeduplicatedByCacheKey,
147
- getRequestDeduplicatedByIdKey: () => getRequestDeduplicatedByIdKey,
148
- getRequestDeduplicatedByQueryKey: () => getRequestDeduplicatedByQueryKey,
149
- getRequestDeduplicatedKey: () => getRequestDeduplicatedKey,
150
- getRequestDispatcher: () => getRequestDispatcher,
151
- getRequestEta: () => getRequestEta,
152
- getRequestKey: () => getRequestKey,
153
- getRequestManagerEvents: () => getRequestManagerEvents,
154
- getRequestStarByQueryKey: () => getRequestStarByQueryKey,
155
- getRequestStartByIdKey: () => getRequestStartByIdKey,
156
- getRequestStartKey: () => getRequestStartKey,
157
- getRequestType: () => getRequestType,
158
- getResponseByCacheKey: () => getResponseByCacheKey,
159
- getResponseByIdKey: () => getResponseByIdKey,
160
- getResponseHeaders: () => getResponseHeaders,
161
- getResponseKey: () => getResponseKey,
162
- getResponseStartByIdKey: () => getResponseStartByIdKey,
163
- getResponseStartByQueryKey: () => getResponseStartByQueryKey,
164
- getResponseStartKey: () => getResponseStartKey,
165
- getSimpleKey: () => getSimpleKey,
166
- getTime: () => getTime,
167
- getUniqueRequestId: () => getUniqueRequestId,
168
- getUploadProgressByIdKey: () => getUploadProgressByIdKey,
169
- getUploadProgressByQueryKey: () => getUploadProgressByQueryKey,
170
- getUploadProgressKey: () => getUploadProgressKey,
171
- handleResponse: () => handleResponse,
172
- hasDocument: () => hasDocument,
173
- hasWindow: () => hasWindow,
174
- interceptRequest: () => interceptRequest,
175
- interceptResponse: () => interceptResponse,
176
- logLevelOrder: () => logLevelOrder,
177
- logger: () => logger,
178
- loggerColors: () => loggerColors,
179
- loggerStyles: () => loggerStyles,
180
- mocker: () => mocker,
181
- onDocumentEvent: () => onDocumentEvent,
182
- onWindowEvent: () => onWindowEvent,
183
- parseErrorResponse: () => parseErrorResponse,
184
- parseResponse: () => parseResponse,
185
- sendRequest: () => sendRequest,
186
- stringifyDefaultOptions: () => stringifyDefaultOptions,
187
- stringifyKey: () => stringifyKey,
188
- stringifyQueryParams: () => stringifyQueryParams,
189
- stringifyValue: () => stringifyValue,
190
- xhrExtra: () => xhrExtra
191
- });
192
- module.exports = __toCommonJS(index_exports);
193
-
194
- // src/plugin/plugin.ts
195
- var Plugin = class {
196
- constructor(config) {
197
- this.config = config;
198
- __publicField(this, "name");
199
- __publicField(this, "data");
200
- __publicField(this, "client");
201
- __publicField(this, "pluginMethods", {});
202
- __publicField(this, "initialize", (client) => {
203
- this.client = client;
204
- return this;
205
- });
206
- __publicField(this, "trigger", (method, data) => {
207
- const callback = this.pluginMethods[method];
208
- if (callback) {
209
- callback(data);
210
- }
211
- });
212
- /* -------------------------------------------------------------------------------------------------
213
- * Plugin lifecycle
214
- * -----------------------------------------------------------------------------------------------*/
215
- /**
216
- * Callback that will be executed when plugin is mounted
217
- */
218
- __publicField(this, "onMount", (callback) => {
219
- this.pluginMethods.onMount = callback;
220
- return this;
221
- });
222
- /**
223
- * Callback that will be executed when plugin is unmounted
224
- */
225
- __publicField(this, "onUnmount", (callback) => {
226
- this.pluginMethods.onUnmount = callback;
227
- return this;
228
- });
229
- /* -------------------------------------------------------------------------------------------------
230
- * Request lifecycle
231
- * -----------------------------------------------------------------------------------------------*/
232
- /**
233
- * Callback that will be executed when request is created
234
- */
235
- __publicField(this, "onRequestCreate", (callback) => {
236
- this.pluginMethods.onRequestCreate = callback;
237
- return this;
238
- });
239
- /**
240
- * Callback that will be executed when request gets triggered
241
- */
242
- __publicField(this, "onRequestTrigger", (callback) => {
243
- this.pluginMethods.onRequestTrigger = callback;
244
- return this;
245
- });
246
- /**
247
- * Callback that will be executed when request starts
248
- */
249
- __publicField(this, "onRequestStart", (callback) => {
250
- this.pluginMethods.onRequestStart = callback;
251
- return this;
252
- });
253
- /**
254
- * Callback that will be executed when response is successful
255
- */
256
- __publicField(this, "onRequestSuccess", (callback) => {
257
- this.pluginMethods.onRequestSuccess = callback;
258
- return this;
259
- });
260
- /**
261
- * Callback that will be executed when response is failed
262
- */
263
- __publicField(this, "onRequestError", (callback) => {
264
- this.pluginMethods.onRequestError = callback;
265
- return this;
266
- });
267
- /**
268
- * Callback that will be executed when response is finished
269
- */
270
- __publicField(this, "onRequestFinished", (callback) => {
271
- this.pluginMethods.onRequestFinished = callback;
272
- return this;
273
- });
274
- /* -------------------------------------------------------------------------------------------------
275
- * Dispatcher lifecycle
276
- * -----------------------------------------------------------------------------------------------*/
277
- __publicField(this, "onDispatcherCleared", (callback) => {
278
- this.pluginMethods.onDispatcherCleared = callback;
279
- return this;
280
- });
281
- __publicField(this, "onDispatcherQueueDrained", (callback) => {
282
- this.pluginMethods.onDispatcherQueueDrained = callback;
283
- return this;
284
- });
285
- __publicField(this, "onDispatcherQueueRunning", (callback) => {
286
- this.pluginMethods.onDispatcherQueueRunning = callback;
287
- return this;
288
- });
289
- __publicField(this, "onDispatcherItemAdded", (callback) => {
290
- this.pluginMethods.onDispatcherItemAdded = callback;
291
- return this;
292
- });
293
- __publicField(this, "onDispatcherItemDeleted", (callback) => {
294
- this.pluginMethods.onDispatcherItemDeleted = callback;
295
- return this;
296
- });
297
- __publicField(this, "onDispatcherQueueCreated", (callback) => {
298
- this.pluginMethods.onDispatcherQueueCreated = callback;
299
- return this;
300
- });
301
- __publicField(this, "onDispatcherQueueCleared", (callback) => {
302
- this.pluginMethods.onDispatcherQueueCleared = callback;
303
- return this;
304
- });
305
- /* -------------------------------------------------------------------------------------------------
306
- * Cache lifecycle
307
- * -----------------------------------------------------------------------------------------------*/
308
- __publicField(this, "onCacheItemChange", (callback) => {
309
- this.pluginMethods.onCacheItemChange = callback;
310
- return this;
311
- });
312
- __publicField(this, "onCacheItemDelete", (callback) => {
313
- this.pluginMethods.onCacheItemDelete = callback;
314
- return this;
315
- });
316
- /* -------------------------------------------------------------------------------------------------
317
- * Adapter lifecycle
318
- * -----------------------------------------------------------------------------------------------*/
319
- __publicField(this, "onAdapterFetch", (callback) => {
320
- this.pluginMethods.onAdapterFetch = callback;
321
- return this;
322
- });
323
- this.name = config.name;
324
- if (config.data) {
325
- this.data = config.data;
326
- }
327
- }
328
- };
329
-
330
- // src/constants/time.constants.ts
331
- var Time = /* @__PURE__ */ ((Time2) => {
332
- Time2[Time2["SEC"] = 1e3] = "SEC";
333
- Time2[Time2["MIN"] = 6e4] = "MIN";
334
- Time2[Time2["HOUR"] = 36e5] = "HOUR";
335
- Time2[Time2["DAY"] = 864e5] = "DAY";
336
- Time2[Time2["WEEK"] = 6048e5] = "WEEK";
337
- Time2[Time2["MONTH_30"] = 2592e6] = "MONTH_30";
338
- Time2[Time2["MONTH_31"] = 26784e5] = "MONTH_31";
339
- Time2[Time2["YEAR"] = 31536e6] = "YEAR";
340
- Time2[Time2["YEAR_LEAP"] = 316224e5] = "YEAR_LEAP";
341
- return Time2;
342
- })(Time || {});
343
-
344
- // src/request/request.ts
345
- var _Request = class _Request {
346
- constructor(client, requestOptions, initialRequestConfiguration) {
347
- this.client = client;
348
- this.requestOptions = requestOptions;
349
- this.initialRequestConfiguration = initialRequestConfiguration;
350
- __publicField(this, "endpoint");
351
- __publicField(this, "headers");
352
- __publicField(this, "auth");
353
- __publicField(this, "method");
354
- __publicField(this, "params");
355
- __publicField(this, "payload");
356
- __publicField(this, "queryParams");
357
- __publicField(this, "options");
358
- __publicField(this, "cancelable");
359
- __publicField(this, "retry");
360
- __publicField(this, "retryTime");
361
- __publicField(this, "cacheTime");
362
- __publicField(this, "cache");
363
- __publicField(this, "staleTime");
364
- __publicField(this, "queued");
365
- __publicField(this, "offline");
366
- __publicField(this, "abortKey");
367
- __publicField(this, "cacheKey");
368
- __publicField(this, "queryKey");
369
- __publicField(this, "used");
370
- __publicField(this, "deduplicate");
371
- __publicField(this, "deduplicateTime");
372
- __publicField(this, "isMockerEnabled", false);
373
- __publicField(this, "unstable_mock");
374
- /** @internal */
375
- __publicField(this, "unstable_payloadMapper");
376
- /** @internal */
377
- __publicField(this, "unstable_requestMapper");
378
- /** @internal */
379
- __publicField(this, "unstable_responseMapper");
380
- __publicField(this, "unstable_hasParams", false);
381
- __publicField(this, "unstable_hasPayload", false);
382
- __publicField(this, "unstable_hasQuery", false);
383
- __publicField(this, "updatedAbortKey");
384
- __publicField(this, "updatedCacheKey");
385
- __publicField(this, "updatedQueryKey");
386
- __publicField(this, "setHeaders", (headers) => {
387
- return this.clone({ headers });
388
- });
389
- __publicField(this, "setAuth", (auth) => {
390
- return this.clone({ auth });
391
- });
392
- __publicField(this, "setParams", (params) => {
393
- return this.clone({ params });
394
- });
395
- __publicField(this, "setPayload", (payload) => {
396
- return this.clone({
397
- payload
398
- });
399
- });
400
- __publicField(this, "setQueryParams", (queryParams) => {
401
- return this.clone({ queryParams });
402
- });
403
- __publicField(this, "setOptions", (options) => {
404
- return this.clone({ options });
405
- });
406
- __publicField(this, "setCancelable", (cancelable) => {
407
- return this.clone({ cancelable });
408
- });
409
- __publicField(this, "setRetry", (retry) => {
410
- return this.clone({ retry });
411
- });
412
- __publicField(this, "setRetryTime", (retryTime) => {
413
- return this.clone({ retryTime });
414
- });
415
- __publicField(this, "setCacheTime", (cacheTime) => {
416
- return this.clone({ cacheTime });
417
- });
418
- __publicField(this, "setCache", (cache) => {
419
- return this.clone({ cache });
420
- });
421
- __publicField(this, "setStaleTime", (staleTime) => {
422
- return this.clone({ staleTime });
423
- });
424
- __publicField(this, "setQueued", (queued) => {
425
- return this.clone({ queued });
426
- });
427
- __publicField(this, "setAbortKey", (abortKey) => {
428
- this.updatedAbortKey = true;
429
- return this.clone({ abortKey });
430
- });
431
- __publicField(this, "setCacheKey", (cacheKey) => {
432
- this.updatedCacheKey = true;
433
- return this.clone({ cacheKey });
434
- });
435
- __publicField(this, "setQueryKey", (queryKey) => {
436
- this.updatedQueryKey = true;
437
- return this.clone({ queryKey });
438
- });
439
- __publicField(this, "setDeduplicate", (deduplicate) => {
440
- return this.clone({ deduplicate });
441
- });
442
- __publicField(this, "setDeduplicateTime", (deduplicateTime) => {
443
- return this.clone({ deduplicateTime });
444
- });
445
- __publicField(this, "setUsed", (used) => {
446
- return this.clone({ used });
447
- });
448
- __publicField(this, "setOffline", (offline) => {
449
- return this.clone({ offline });
450
- });
451
- __publicField(this, "setMock", (fn, config = {}) => {
452
- this.unstable_mock = { fn, config };
453
- this.isMockerEnabled = true;
454
- return this;
455
- });
456
- __publicField(this, "clearMock", () => {
457
- this.unstable_mock = void 0;
458
- this.isMockerEnabled = false;
459
- return this;
460
- });
461
- __publicField(this, "setMockingEnabled", (isMockerEnabled) => {
462
- this.isMockerEnabled = isMockerEnabled;
463
- return this;
464
- });
465
- /**
466
- * Map data before it gets send to the server
467
- * @param payloadMapper
468
- * @returns
469
- */
470
- __publicField(this, "setPayloadMapper", (payloadMapper) => {
471
- const cloned = this.clone(void 0);
472
- cloned.unstable_payloadMapper = payloadMapper;
473
- return cloned;
474
- });
475
- /**
476
- * Map request before it gets send to the server
477
- * @param requestMapper mapper of the request
478
- * @returns new request
479
- */
480
- __publicField(this, "setRequestMapper", (requestMapper) => {
481
- const cloned = this.clone(void 0);
482
- cloned.unstable_requestMapper = requestMapper;
483
- return cloned;
484
- });
485
- /**
486
- * Map the response to the new interface
487
- * @param responseMapper our mapping callback
488
- * @returns new response
489
- */
490
- __publicField(this, "setResponseMapper", (responseMapper) => {
491
- const cloned = this.clone();
492
- cloned.unstable_responseMapper = responseMapper;
493
- return cloned;
494
- });
495
- __publicField(this, "paramsMapper", (params) => {
496
- const { endpoint } = this.requestOptions;
497
- let stringEndpoint = String(endpoint);
498
- if (params) {
499
- Object.entries(params).forEach(([key, value]) => {
500
- stringEndpoint = stringEndpoint.replace(new RegExp(`:${key}`, "g"), String(value));
501
- });
502
- }
503
- return stringEndpoint;
504
- });
505
- __publicField(this, "abort", () => {
506
- const { requestManager } = this.client;
507
- requestManager.abortByKey(this.abortKey);
508
- return this.clone();
509
- });
510
- __publicField(this, "dehydrate", (config) => {
511
- const { response, override = true } = config || {};
512
- if (response) {
513
- return {
514
- override,
515
- cacheTime: this.cacheTime,
516
- staleTime: this.staleTime,
517
- cacheKey: this.cacheKey,
518
- timestamp: +/* @__PURE__ */ new Date(),
519
- hydrated: true,
520
- cache: true,
521
- response
522
- };
523
- }
524
- const cacheData = this.client.cache.get(this.cacheKey);
525
- if (!cacheData) {
526
- return void 0;
527
- }
528
- return {
529
- override,
530
- cacheTime: this.cacheTime,
531
- staleTime: this.staleTime,
532
- cacheKey: this.cacheKey,
533
- timestamp: +/* @__PURE__ */ new Date(),
534
- hydrated: true,
535
- cache: true,
536
- response: {
537
- data: cacheData.data,
538
- error: cacheData.error,
539
- status: cacheData.status,
540
- success: cacheData.success,
541
- extra: cacheData.extra,
542
- requestTimestamp: cacheData.requestTimestamp,
543
- responseTimestamp: cacheData.responseTimestamp
544
- }
545
- };
546
- });
547
- /**
548
- * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
549
- * @param options
550
- * @disableReturns
551
- * @returns
552
- * ```tsx
553
- * Promise<[Data | null, Error | null, HttpStatus]>
554
- * ```
555
- */
556
- __publicField(this, "exec", (options) => __async(this, null, function* () {
557
- const { adapter, requestManager } = this.client;
558
- const request = this.clone(options);
559
- const requestId = this.client.unstable_requestIdMapper(this);
560
- requestManager.addAbortController(this.abortKey, requestId);
561
- const response = yield adapter.fetch(request, requestId);
562
- requestManager.removeAbortController(this.abortKey, requestId);
563
- if (request.unstable_responseMapper) {
564
- return request.unstable_responseMapper(response);
565
- }
566
- return response;
567
- }));
568
- /**
569
- * Method used to perform requests with usage of cache and queues
570
- * @param options
571
- * @param requestCallback
572
- * @disableReturns
573
- * @returns
574
- * ```tsx
575
- * Promise<[Data | null, Error | null, HttpStatus]>
576
- * ```
577
- */
578
- __publicField(this, "send", (options) => __async(this, null, function* () {
579
- const _a = options || {}, { dispatcherType } = _a, configuration = __objRest(_a, ["dispatcherType"]);
580
- const request = this.clone(configuration);
581
- return sendRequest(request, options);
582
- }));
583
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
584
- const configuration = __spreadValues(__spreadValues({}, (_b = (_a = this.client.adapter).unstable_getRequestDefaults) == null ? void 0 : _b.call(_a, requestOptions)), requestOptions);
585
- const {
586
- endpoint,
587
- headers,
588
- auth = true,
589
- method = client.adapter.defaultMethod,
590
- options,
591
- cancelable = false,
592
- retry = 0,
593
- retryTime = 500,
594
- cacheTime = 6e4 /* MIN */ * 5,
595
- cache = true,
596
- staleTime = 6e4 /* MIN */ * 5,
597
- queued = false,
598
- offline = true,
599
- abortKey,
600
- cacheKey,
601
- queryKey,
602
- deduplicate = false,
603
- deduplicateTime = null
604
- } = configuration;
605
- this.endpoint = (_c = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.endpoint) != null ? _c : endpoint;
606
- this.headers = (_d = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.headers) != null ? _d : headers;
607
- this.auth = (_e = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.auth) != null ? _e : auth;
608
- this.method = method;
609
- this.params = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.params;
610
- this.payload = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.payload;
611
- this.queryParams = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.queryParams;
612
- this.options = (_f = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.options) != null ? _f : options;
613
- this.cancelable = (_g = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.cancelable) != null ? _g : cancelable;
614
- this.retry = (_h = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.retry) != null ? _h : retry;
615
- this.retryTime = (_i = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.retryTime) != null ? _i : retryTime;
616
- this.cacheTime = (_j = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.cacheTime) != null ? _j : cacheTime;
617
- this.cache = (_k = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.cache) != null ? _k : cache;
618
- this.staleTime = (_l = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.staleTime) != null ? _l : staleTime;
619
- this.queued = (_m = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.queued) != null ? _m : queued;
620
- this.offline = (_n = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.offline) != null ? _n : offline;
621
- this.abortKey = (_p = (_o = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.abortKey) != null ? _o : abortKey) != null ? _p : this.client.unstable_abortKeyMapper(this);
622
- this.cacheKey = (_r = (_q = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.cacheKey) != null ? _q : cacheKey) != null ? _r : this.client.unstable_cacheKeyMapper(this);
623
- this.queryKey = (_t = (_s = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.queryKey) != null ? _s : queryKey) != null ? _t : this.client.unstable_queryKeyMapper(this);
624
- this.used = (_u = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.used) != null ? _u : false;
625
- this.deduplicate = (_v = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.deduplicate) != null ? _v : deduplicate;
626
- this.deduplicateTime = (_w = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.deduplicateTime) != null ? _w : deduplicateTime;
627
- this.updatedAbortKey = (_x = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.updatedAbortKey) != null ? _x : false;
628
- this.updatedCacheKey = (_y = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.updatedCacheKey) != null ? _y : false;
629
- this.updatedQueryKey = (_z = initialRequestConfiguration == null ? void 0 : initialRequestConfiguration.updatedQueryKey) != null ? _z : false;
630
- }
631
- toJSON() {
632
- return {
633
- requestOptions: this.requestOptions,
634
- endpoint: this.endpoint,
635
- headers: this.headers,
636
- auth: this.auth,
637
- // TODO: fix this type
638
- method: this.method,
639
- params: this.params,
640
- payload: this.payload,
641
- queryParams: this.queryParams,
642
- options: this.options,
643
- cancelable: this.cancelable,
644
- retry: this.retry,
645
- retryTime: this.retryTime,
646
- cacheTime: this.cacheTime,
647
- cache: this.cache,
648
- staleTime: this.staleTime,
649
- queued: this.queued,
650
- offline: this.offline,
651
- abortKey: this.abortKey,
652
- cacheKey: this.cacheKey,
653
- queryKey: this.queryKey,
654
- used: this.used,
655
- disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,
656
- disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,
657
- updatedAbortKey: this.updatedAbortKey,
658
- updatedCacheKey: this.updatedCacheKey,
659
- updatedQueryKey: this.updatedQueryKey,
660
- deduplicate: this.deduplicate,
661
- deduplicateTime: this.deduplicateTime,
662
- isMockerEnabled: this.isMockerEnabled,
663
- hasMock: !!this.unstable_mock
664
- };
665
- }
666
- clone(configuration) {
667
- const json = this.toJSON();
668
- const initialRequestConfiguration = __spreadProps(__spreadValues(__spreadValues({}, json), configuration), {
669
- options: (configuration == null ? void 0 : configuration.options) || this.options,
670
- abortKey: this.updatedAbortKey ? (configuration == null ? void 0 : configuration.abortKey) || this.abortKey : void 0,
671
- cacheKey: this.updatedCacheKey ? (configuration == null ? void 0 : configuration.cacheKey) || this.cacheKey : void 0,
672
- queryKey: this.updatedQueryKey ? (configuration == null ? void 0 : configuration.queryKey) || this.queryKey : void 0,
673
- endpoint: this.paramsMapper((configuration == null ? void 0 : configuration.params) || this.params),
674
- queryParams: (configuration == null ? void 0 : configuration.queryParams) || this.queryParams,
675
- payload: (configuration == null ? void 0 : configuration.payload) || this.payload,
676
- params: (configuration == null ? void 0 : configuration.params) || this.params
677
- });
678
- const cloned = new _Request(this.client, this.requestOptions, initialRequestConfiguration);
679
- cloned.unstable_payloadMapper = this.unstable_payloadMapper;
680
- cloned.unstable_responseMapper = this.unstable_responseMapper;
681
- cloned.unstable_requestMapper = this.unstable_requestMapper;
682
- cloned.unstable_mock = this.unstable_mock;
683
- cloned.isMockerEnabled = this.isMockerEnabled;
684
- return cloned;
685
- }
686
- /**
687
- * Read the response from cache data
688
- *
689
- * If it returns error and data at the same time, it means that latest request was failed
690
- * and we show previous data from cache together with error received from actual request
691
- */
692
- read() {
693
- const cacheData = this.client.cache.get(this.cacheKey);
694
- if (cacheData) {
695
- return {
696
- data: cacheData.data,
697
- error: cacheData.error,
698
- status: cacheData.status,
699
- success: cacheData.success,
700
- extra: cacheData.extra,
701
- requestTimestamp: cacheData.requestTimestamp,
702
- responseTimestamp: cacheData.responseTimestamp
703
- };
704
- }
705
- return void 0;
706
- }
707
- };
708
- __publicField(_Request, "fromJSON", (client, json) => {
709
- return new _Request(client, json.requestOptions, json);
710
- });
711
- var Request = _Request;
712
-
713
- // src/constants/http.constants.ts
714
- var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
715
- HttpMethods2["GET"] = "GET";
716
- HttpMethods2["POST"] = "POST";
717
- HttpMethods2["PUT"] = "PUT";
718
- HttpMethods2["PATCH"] = "PATCH";
719
- HttpMethods2["DELETE"] = "DELETE";
720
- return HttpMethods2;
721
- })(HttpMethods || {});
722
-
723
- // src/dispatcher/dispatcher.constants.ts
724
- var DispatcherMode = /* @__PURE__ */ ((DispatcherMode2) => {
725
- DispatcherMode2["ONE_BY_ONE"] = "one-by-one";
726
- DispatcherMode2["ALL_AT_ONCE"] = "all-at-once";
727
- DispatcherMode2["PREVIOUS_CANCELED"] = "previous-canceled";
728
- DispatcherMode2["DEDUPLICATED"] = "deduplicated";
729
- return DispatcherMode2;
730
- })(DispatcherMode || {});
731
-
732
- // src/dispatcher/dispatcher.events.ts
733
- var getDispatcherEvents = (emitter) => ({
734
- emitDrained: (values, isTriggeredExternally) => {
735
- emitter.emit(getDispatcherDrainedKey(), values, isTriggeredExternally);
736
- emitter.emit(getDispatcherDrainedByKey(values.queryKey), values, isTriggeredExternally);
737
- },
738
- emitQueueStatusChanged: (values, isTriggeredExternally) => {
739
- emitter.emit(getDispatcherStatusKey(), values, isTriggeredExternally);
740
- emitter.emit(getDispatcherStatusByKey(values.queryKey), values, isTriggeredExternally);
741
- },
742
- emitQueueChanged: (values, isTriggeredExternally) => {
743
- emitter.emit(getDispatcherChangeKey(), values, isTriggeredExternally);
744
- emitter.emit(getDispatcherChangeByKey(values.queryKey), values, isTriggeredExternally);
745
- },
746
- /**
747
- * When queue becomes empty
748
- * @param callback
749
- * @returns
750
- */
751
- onDrained: (callback) => {
752
- emitter.on(getDispatcherDrainedKey(), callback);
753
- return () => emitter.removeListener(getDispatcherDrainedKey(), callback);
754
- },
755
- /**
756
- * When queue becomes empty
757
- * @param queryKey
758
- * @param callback
759
- * @returns
760
- */
761
- onDrainedByKey: (queryKey, callback) => {
762
- emitter.on(getDispatcherDrainedByKey(queryKey), callback);
763
- return () => emitter.removeListener(getDispatcherDrainedByKey(queryKey), callback);
764
- },
765
- /**
766
- * When queue status change from enabled to paused or vice versa
767
- * @param callback
768
- * @returns
769
- */
770
- onQueueStatusChange: (callback) => {
771
- emitter.on(getDispatcherStatusKey(), callback);
772
- return () => emitter.removeListener(getDispatcherStatusKey(), callback);
773
- },
774
- /**
775
- * When queue status change from enabled to paused or vice versa
776
- * @param queryKey
777
- * @param callback
778
- * @returns
779
- */
780
- onQueueStatusChangeByKey: (queryKey, callback) => {
781
- emitter.on(getDispatcherStatusByKey(queryKey), callback);
782
- return () => emitter.removeListener(getDispatcherStatusByKey(queryKey), callback);
783
- },
784
- /**
785
- * When new elements are added or removed from the queue
786
- * @param queryKey
787
- * @param callback
788
- * @returns
789
- */
790
- onQueueChange: (callback) => {
791
- emitter.on(getDispatcherChangeKey(), callback);
792
- return () => emitter.removeListener(getDispatcherChangeKey(), callback);
793
- },
794
- /**
795
- * When new elements are added or removed from the queue
796
- * @param queryKey
797
- * @param callback
798
- * @returns
799
- */
800
- onQueueChangeByKey: (queryKey, callback) => {
801
- emitter.on(getDispatcherChangeByKey(queryKey), callback);
802
- return () => emitter.removeListener(getDispatcherChangeByKey(queryKey), callback);
803
- }
804
- });
805
-
806
- // src/utils/uuid.utils.ts
807
- var getUniqueRequestId = (request) => {
808
- return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2)}`;
809
- };
810
-
811
- // src/utils/emitter.utils.ts
812
- var import_events = __toESM(require("events"));
813
- var getListenName = (event) => `listen_${String(event)}`;
814
- var EventEmitter = class extends import_events.default {
815
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
816
- constructor(options) {
817
- super(options);
818
- __publicField(this, "emitCallbacks", []);
819
- __publicField(this, "onEmit", (callback) => {
820
- var _a;
821
- (_a = this.emitCallbacks) == null ? void 0 : _a.push(callback);
822
- return () => {
823
- var _a2;
824
- this.emitCallbacks = (_a2 = this.emitCallbacks) == null ? void 0 : _a2.filter((cb) => cb !== callback);
825
- };
826
- });
827
- __publicField(this, "onListener", (event, listener) => {
828
- super.on(getListenName(event), listener);
829
- return () => {
830
- super.off(getListenName(event), listener);
831
- };
832
- });
833
- __publicField(this, "on", (event, listener) => {
834
- super.on(event, listener);
835
- super.emit(getListenName(event), super.listeners(event).length);
836
- return this;
837
- });
838
- __publicField(this, "off", (event, listener) => {
839
- super.off(event, listener);
840
- super.emit(getListenName(event), super.listeners(event).length);
841
- return this;
842
- });
843
- __publicField(this, "addListener", this.on);
844
- __publicField(this, "removeListener", this.off);
845
- }
846
- emit(type, data, isTriggeredExternally) {
847
- var _a;
848
- const params = [type, data];
849
- if (isTriggeredExternally) {
850
- params.push(isTriggeredExternally);
851
- }
852
- (_a = this.emitCallbacks) == null ? void 0 : _a.forEach((callback) => callback(...params));
853
- return super.emit(...params);
854
- }
855
- };
856
-
857
- // src/dispatcher/dispatcher.ts
858
- var Dispatcher = class {
859
- constructor(options) {
860
- this.options = options;
861
- __publicField(this, "emitter", new EventEmitter());
862
- __publicField(this, "events", getDispatcherEvents(this.emitter));
863
- __publicField(this, "storage", /* @__PURE__ */ new Map());
864
- __publicField(this, "requestCount", /* @__PURE__ */ new Map());
865
- __publicField(this, "runningRequests", /* @__PURE__ */ new Map());
866
- __publicField(this, "logger");
867
- __publicField(this, "client");
868
- __publicField(this, "initialize", (client) => {
869
- this.client = client;
870
- this.logger = client.loggerManager.initialize(client, "Dispatcher");
871
- this.client.appManager.events.onOnline(() => {
872
- this.flush();
873
- });
874
- return this;
875
- });
876
- // *********************************************************************
877
- // *********************************************************************
878
- // Queue
879
- // *********************************************************************
880
- // *********************************************************************
881
- /**
882
- * Start request handling by queryKey
883
- */
884
- __publicField(this, "start", (queryKey) => {
885
- const queue = this.getQueue(queryKey);
886
- queue.stopped = false;
887
- this.setQueue(queryKey, queue);
888
- this.flushQueue(queryKey);
889
- this.client.triggerPlugins("onDispatcherQueueRunning", { dispatcher: this, queue, status: "running" });
890
- this.events.emitQueueStatusChanged(queue);
891
- });
892
- /**
893
- * Pause request queue, but do not cancel already started requests
894
- */
895
- __publicField(this, "pause", (queryKey) => {
896
- const queue = this.getQueue(queryKey);
897
- queue.stopped = true;
898
- this.setQueue(queryKey, queue);
899
- this.client.triggerPlugins("onDispatcherQueueRunning", { dispatcher: this, queue, status: "paused" });
900
- this.events.emitQueueStatusChanged(queue);
901
- });
902
- /**
903
- * Stop request queue and cancel all started requests - those will be treated like not started
904
- */
905
- __publicField(this, "stop", (queryKey) => {
906
- const queue = this.getQueue(queryKey);
907
- queue.stopped = true;
908
- this.setQueue(queryKey, queue);
909
- this.cancelRunningRequests(queryKey);
910
- this.client.triggerPlugins("onDispatcherQueueRunning", { dispatcher: this, queue, status: "stopped" });
911
- this.events.emitQueueStatusChanged(queue);
912
- });
913
- /**
914
- * Return all
915
- */
916
- __publicField(this, "getQueuesKeys", () => {
917
- return Array.from(this.storage.keys());
918
- });
919
- /**
920
- * Return queue state object
921
- */
922
- __publicField(this, "getQueue", (queryKey) => {
923
- const initialQueueState = { queryKey, requests: [], stopped: false };
924
- const storedEntity = this.storage.get(queryKey);
925
- return storedEntity || initialQueueState;
926
- });
927
- /**
928
- * Return request from queue state
929
- */
930
- __publicField(this, "getRequest", (queryKey, requestId) => {
931
- const initialQueueState = { queryKey, requests: [], stopped: false };
932
- const storedEntity = this.storage.get(queryKey) || initialQueueState;
933
- return storedEntity.requests.find((req) => req.requestId === requestId);
934
- });
935
- /**
936
- * Get value of the active queue status based on the stopped status
937
- */
938
- __publicField(this, "getIsActiveQueue", (queryKey) => {
939
- const queue = this.getQueue(queryKey);
940
- const hasAvailableRequests = queue.requests.some((req) => !req.stopped);
941
- const isRunningQueue = !queue.stopped;
942
- return hasAvailableRequests && isRunningQueue;
943
- });
944
- /**
945
- * Add new element to storage
946
- */
947
- __publicField(this, "addQueueItem", (queryKey, element) => {
948
- const queue = this.getQueue(queryKey);
949
- queue.requests.push(element);
950
- this.client.triggerPlugins("onDispatcherItemAdded", { dispatcher: this, queue, queueItem: element });
951
- this.setQueue(queryKey, queue);
952
- });
953
- /**
954
- * Set new queue storage value
955
- */
956
- __publicField(this, "setQueue", (queryKey, queue) => {
957
- this.storage.set(queryKey, queue);
958
- this.client.triggerPlugins("onDispatcherQueueCreated", { dispatcher: this, queue });
959
- this.events.emitQueueChanged(queue);
960
- return queue;
961
- });
962
- /**
963
- * Clear requests from queue cache
964
- */
965
- __publicField(this, "clearQueue", (queryKey) => {
966
- const queue = this.getQueue(queryKey);
967
- const newQueue = { queryKey, requests: [], stopped: queue.stopped };
968
- this.storage.set(queryKey, newQueue);
969
- this.client.triggerPlugins("onDispatcherQueueCleared", { dispatcher: this, queue: newQueue });
970
- this.events.emitQueueChanged(newQueue);
971
- this.events.emitDrained(newQueue);
972
- return newQueue;
973
- });
974
- /**
975
- * Method used to flush the queue requests
976
- */
977
- __publicField(this, "flushQueue", (queryKey) => __async(this, null, function* () {
978
- const queue = this.getQueue(queryKey);
979
- const runningRequests = this.getRunningRequests(queryKey);
980
- const queueItem = queue.requests.find((request) => !request.stopped);
981
- const isStopped = queue && queue.stopped;
982
- const isOffline = !this.client.appManager.isOnline;
983
- const isConcurrent = !(queueItem == null ? void 0 : queueItem.request.queued);
984
- const isInactive = !runningRequests.length;
985
- const isEmpty = !queueItem;
986
- if (isStopped || isOffline || isEmpty) {
987
- this.logger.debug({ title: "Skipping queue trigger", type: "system", extra: { isStopped, isOffline, isEmpty } });
988
- } else if (isConcurrent) {
989
- queue.requests.forEach((element) => {
990
- if (!this.hasRunningRequest(queryKey, element.requestId)) {
991
- this.performRequest(element);
992
- }
993
- });
994
- } else if (isInactive) {
995
- yield this.performRequest(queueItem);
996
- this.flushQueue(queryKey);
997
- }
998
- }));
999
- /**
1000
- * Flush all available requests from all queues
1001
- */
1002
- __publicField(this, "flush", () => __async(this, null, function* () {
1003
- const keys = this.getQueuesKeys();
1004
- for (const key of keys) {
1005
- const storageItem = this.getQueue(key);
1006
- if (storageItem) {
1007
- this.flushQueue(key);
1008
- }
1009
- }
1010
- }));
1011
- /**
1012
- * Clear all running requests and storage
1013
- */
1014
- __publicField(this, "clear", () => {
1015
- const keys = this.getQueuesKeys();
1016
- keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));
1017
- this.runningRequests.clear();
1018
- this.storage.clear();
1019
- this.client.triggerPlugins("onDispatcherCleared", { dispatcher: this });
1020
- });
1021
- // *********************************************************************
1022
- // *********************************************************************
1023
- // Requests
1024
- // *********************************************************************
1025
- // *********************************************************************
1026
- /**
1027
- * Start particular request
1028
- */
1029
- __publicField(this, "startRequest", (queryKey, requestId) => {
1030
- const queue = this.getQueue(queryKey);
1031
- const request = queue.requests.find((element) => element.requestId === requestId);
1032
- if (request) {
1033
- request.stopped = false;
1034
- this.setQueue(queryKey, queue);
1035
- this.flushQueue(queryKey);
1036
- this.events.emitQueueStatusChanged(queue);
1037
- }
1038
- });
1039
- /**
1040
- * Stop particular request
1041
- */
1042
- __publicField(this, "stopRequest", (queryKey, requestId) => {
1043
- const queue = this.getQueue(queryKey);
1044
- const request = queue.requests.find((element) => element.requestId === requestId);
1045
- if (request) {
1046
- request.stopped = true;
1047
- this.setQueue(queryKey, queue);
1048
- this.cancelRunningRequest(queryKey, requestId);
1049
- this.events.emitQueueStatusChanged(queue);
1050
- }
1051
- });
1052
- /**
1053
- * Get currently running requests from all queryKeys
1054
- */
1055
- __publicField(this, "getAllRunningRequests", () => {
1056
- return Array.from(this.runningRequests.values()).flat();
1057
- });
1058
- /**
1059
- * Get currently running requests
1060
- */
1061
- __publicField(this, "getRunningRequests", (queryKey) => {
1062
- return this.runningRequests.get(queryKey) || [];
1063
- });
1064
- /**
1065
- * Get running request by id
1066
- */
1067
- __publicField(this, "getRunningRequest", (queryKey, requestId) => {
1068
- const runningRequests = this.getRunningRequests(queryKey);
1069
- return runningRequests.find((req) => req.requestId === requestId);
1070
- });
1071
- /**
1072
- * Add request to the running requests list
1073
- */
1074
- __publicField(this, "addRunningRequest", (queryKey, requestId, request) => {
1075
- const newRunningRequest = { requestId, request, timestamp: Date.now() };
1076
- const runningRequests = this.getRunningRequests(queryKey);
1077
- runningRequests.push(newRunningRequest);
1078
- this.runningRequests.set(queryKey, runningRequests);
1079
- return newRunningRequest;
1080
- });
1081
- /**
1082
- * Get the value based on the currently running requests
1083
- */
1084
- __publicField(this, "hasRunningRequests", (queryKey) => {
1085
- return !!this.getRunningRequests(queryKey).length;
1086
- });
1087
- /**
1088
- * Check if request is currently processing
1089
- */
1090
- __publicField(this, "hasRunningRequest", (queryKey, requestId) => {
1091
- const runningRequests = this.getRunningRequests(queryKey);
1092
- return !!runningRequests.find((req) => req.requestId === requestId);
1093
- });
1094
- /**
1095
- * Cancel all started requests, but do NOT remove it from main storage
1096
- */
1097
- __publicField(this, "cancelRunningRequests", (queryKey) => {
1098
- var _a;
1099
- (_a = this.runningRequests.get(queryKey)) == null ? void 0 : _a.forEach((request) => {
1100
- this.client.requestManager.abortByRequestId(request.request.abortKey, request.requestId);
1101
- });
1102
- this.deleteRunningRequests(queryKey);
1103
- });
1104
- /**
1105
- * Cancel started request, but do NOT remove it from main storage
1106
- */
1107
- __publicField(this, "cancelRunningRequest", (queryKey, requestId) => {
1108
- const requests = this.getRunningRequests(queryKey).filter((request) => {
1109
- if (request.requestId === requestId) {
1110
- this.client.requestManager.abortByRequestId(request.request.abortKey, request.requestId);
1111
- return false;
1112
- }
1113
- return true;
1114
- });
1115
- this.runningRequests.set(queryKey, requests);
1116
- });
1117
- /**
1118
- * Delete all started requests, but do NOT clear it from queue and do NOT cancel them
1119
- */
1120
- __publicField(this, "deleteRunningRequests", (queryKey) => {
1121
- this.runningRequests.set(queryKey, []);
1122
- });
1123
- /**
1124
- * Delete request by id, but do NOT clear it from queue and do NOT cancel them
1125
- */
1126
- __publicField(this, "deleteRunningRequest", (queryKey, requestId) => {
1127
- const runningRequests = this.getRunningRequests(queryKey);
1128
- this.runningRequests.set(
1129
- queryKey,
1130
- runningRequests.filter((req) => req.requestId !== requestId)
1131
- );
1132
- });
1133
- /**
1134
- * Get count of requests from the same queryKey
1135
- */
1136
- __publicField(this, "getQueueRequestCount", (queryKey) => {
1137
- return this.requestCount.get(queryKey) || 0;
1138
- });
1139
- /**
1140
- * Add request count to the queryKey
1141
- */
1142
- __publicField(this, "incrementQueueRequestCount", (queryKey) => {
1143
- const count = this.requestCount.get(queryKey) || 0;
1144
- this.requestCount.set(queryKey, count + 1);
1145
- });
1146
- /**
1147
- * Create storage element from request
1148
- */
1149
- // eslint-disable-next-line class-methods-use-this
1150
- __publicField(this, "createStorageItem", (request) => {
1151
- const requestId = this.client.unstable_requestIdMapper(request);
1152
- const storageItem = {
1153
- requestId,
1154
- timestamp: +/* @__PURE__ */ new Date(),
1155
- request,
1156
- retries: 0,
1157
- stopped: false,
1158
- resolved: false
1159
- };
1160
- return storageItem;
1161
- });
1162
- // *********************************************************************
1163
- // *********************************************************************
1164
- // Dispatching
1165
- // *********************************************************************
1166
- // *********************************************************************
1167
- /**
1168
- * Add request to the dispatcher handler
1169
- */
1170
- __publicField(this, "add", (request) => {
1171
- const { queryKey } = request;
1172
- const storageItem = this.createStorageItem(request);
1173
- const { requestId } = storageItem;
1174
- const queue = this.getQueue(queryKey);
1175
- const [latestRequest] = queue.requests.slice(-1);
1176
- const requestType = getRequestType(request, latestRequest);
1177
- this.logger.debug({ title: "Adding request to queue", type: "system", extra: { requestType, request, requestId } });
1178
- switch (requestType) {
1179
- case "one-by-one" /* ONE_BY_ONE */: {
1180
- this.addQueueItem(queryKey, storageItem);
1181
- this.flushQueue(queryKey);
1182
- return requestId;
1183
- }
1184
- case "previous-canceled" /* PREVIOUS_CANCELED */: {
1185
- this.cancelRunningRequests(queryKey);
1186
- this.clearQueue(queryKey);
1187
- this.addQueueItem(queryKey, storageItem);
1188
- this.flushQueue(queryKey);
1189
- return requestId;
1190
- }
1191
- case "deduplicated" /* DEDUPLICATED */: {
1192
- this.client.requestManager.events.emitDeduplicated({
1193
- request: latestRequest.request,
1194
- requestId,
1195
- deduplicatedRequest: request
1196
- });
1197
- return latestRequest.requestId;
1198
- }
1199
- default: {
1200
- this.addQueueItem(queryKey, storageItem);
1201
- this.flushQueue(queryKey);
1202
- return requestId;
1203
- }
1204
- }
1205
- });
1206
- /**
1207
- * Delete from the storage and cancel request
1208
- */
1209
- __publicField(this, "delete", (queryKey, requestId, abortKey) => {
1210
- this.logger.debug({ title: "Deleting request", type: "system", extra: { queryKey, requestId, abortKey } });
1211
- const queue = this.getQueue(queryKey);
1212
- const queueItem = queue.requests.find((req) => req.requestId === requestId);
1213
- if (!queueItem) return;
1214
- queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
1215
- this.storage.set(queryKey, queue);
1216
- if (this.hasRunningRequest(queryKey, requestId)) {
1217
- this.deleteRunningRequest(queryKey, requestId);
1218
- this.client.requestManager.abortByRequestId(abortKey, requestId);
1219
- }
1220
- this.client.triggerPlugins("onDispatcherItemDeleted", { queue, dispatcher: this, queueItem });
1221
- this.events.emitQueueChanged(queue);
1222
- this.client.requestManager.events.emitRemove({
1223
- requestId,
1224
- request: queueItem.request,
1225
- resolved: queueItem.resolved
1226
- });
1227
- if (!queue.requests.length) {
1228
- this.client.triggerPlugins("onDispatcherQueueDrained", { queue, dispatcher: this });
1229
- this.events.emitDrained(queue);
1230
- }
1231
- return queue;
1232
- });
1233
- /**
1234
- * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
1235
- * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
1236
- */
1237
- __publicField(this, "performRequest", (storageItem) => __async(this, null, function* () {
1238
- var _a;
1239
- const { request, requestId } = storageItem;
1240
- this.logger.debug({ title: "Performing request", type: "system", extra: { request, requestId } });
1241
- const { retry, retryTime, queryKey, abortKey, offline } = request;
1242
- const { adapter, requestManager, cache, appManager } = this.client;
1243
- const canRetry = canRetryRequest(storageItem.retries, retry);
1244
- const isOffline = !appManager.isOnline && offline;
1245
- const isAlreadyRunning = this.hasRunningRequest(queryKey, requestId);
1246
- const isStopped = storageItem.stopped;
1247
- if (isOffline || isAlreadyRunning || isStopped) {
1248
- return this.logger.warning({
1249
- title: "Unable to perform request",
1250
- type: "system",
1251
- extra: { isOffline, isAlreadyRunning, isStopped }
1252
- });
1253
- }
1254
- const runningRequest = this.addRunningRequest(queryKey, requestId, request);
1255
- requestManager.events.emitLoading({
1256
- request,
1257
- requestId,
1258
- loading: true,
1259
- isRetry: !!storageItem.retries,
1260
- isOffline
1261
- });
1262
- this.incrementQueueRequestCount(queryKey);
1263
- requestManager.addAbortController(abortKey, requestId);
1264
- const response = yield adapter.fetch(request, requestId);
1265
- storageItem.resolved = true;
1266
- requestManager.removeAbortController(abortKey, requestId);
1267
- const isOfflineResponseStatus = !appManager.isOnline;
1268
- const isCancelMessage = getErrorMessage("abort").message === ((_a = response.error) == null ? void 0 : _a.message);
1269
- const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;
1270
- this.deleteRunningRequest(queryKey, requestId);
1271
- const requestDetails = {
1272
- isCanceled,
1273
- isOffline: isOfflineResponseStatus,
1274
- retries: storageItem.retries,
1275
- addedTimestamp: storageItem.timestamp,
1276
- triggerTimestamp: runningRequest.timestamp,
1277
- requestTimestamp: response.requestTimestamp,
1278
- responseTimestamp: response.responseTimestamp
1279
- };
1280
- requestManager.events.emitResponse({ request, requestId, response, details: requestDetails });
1281
- requestManager.events.emitLoading({
1282
- request,
1283
- requestId,
1284
- loading: false,
1285
- isRetry: !!storageItem.retries,
1286
- isOffline
1287
- });
1288
- cache.set(request, __spreadValues(__spreadValues({}, response), requestDetails));
1289
- this.logger.debug({
1290
- title: "Dispatcher processing response",
1291
- type: "system",
1292
- extra: { requestId, request, response, details: requestDetails }
1293
- });
1294
- if (isCanceled) {
1295
- const queue = this.getQueue(queryKey);
1296
- const queueItem = queue.requests.find((req) => req.requestId === requestId);
1297
- if (!queue.stopped && !(queueItem == null ? void 0 : queueItem.stopped)) {
1298
- this.logger.debug({ title: "Request paused", type: "system", extra: { response, requestDetails, request } });
1299
- return this.delete(queryKey, requestId, abortKey);
1300
- }
1301
- return this.logger.debug({
1302
- title: "Request canceled",
1303
- type: "system",
1304
- extra: { response, requestDetails, request }
1305
- });
1306
- }
1307
- if (!response.success && isOfflineResponseStatus) {
1308
- if (!offline) {
1309
- this.logger.warning({
1310
- title: "Removing non-offline request",
1311
- type: "system",
1312
- extra: { response, requestDetails, request }
1313
- });
1314
- return this.delete(queryKey, requestId, abortKey);
1315
- }
1316
- return this.logger.debug({
1317
- title: "Awaiting for network restoration",
1318
- type: "system",
1319
- extra: { response, requestDetails, request }
1320
- });
1321
- }
1322
- if (response.success) {
1323
- this.delete(queryKey, requestId, abortKey);
1324
- return this.logger.debug({
1325
- title: "Successful response, removing request from queue.",
1326
- type: "system",
1327
- extra: {
1328
- response,
1329
- requestDetails,
1330
- request
1331
- }
1332
- });
1333
- }
1334
- if (!response.success && canRetry) {
1335
- this.logger.debug({ title: "Waiting for retry", type: "system", extra: { response, requestDetails, request } });
1336
- setTimeout(() => {
1337
- this.logger.warning({
1338
- title: "Error response, performing retry",
1339
- type: "request",
1340
- extra: { response, requestDetails, request, requestId }
1341
- });
1342
- this.performRequest(__spreadProps(__spreadValues({}, storageItem), {
1343
- retries: storageItem.retries + 1
1344
- }));
1345
- }, retryTime || 0);
1346
- } else {
1347
- if (request.retry) {
1348
- this.logger.error({
1349
- title: "All retries have been used. Removing request from queue.",
1350
- type: "request",
1351
- extra: { response, requestDetails, request, requestId }
1352
- });
1353
- }
1354
- this.delete(queryKey, requestId, abortKey);
1355
- }
1356
- }));
1357
- var _a, _b;
1358
- (_a = this.emitter) == null ? void 0 : _a.setMaxListeners(1e3);
1359
- if ((_b = this.options) == null ? void 0 : _b.storage) {
1360
- this.storage = this.options.storage;
1361
- }
1362
- }
1363
- };
1364
-
1365
- // src/dispatcher/dispatcher.utils.ts
1366
- var getDispatcherDrainedKey = () => {
1367
- return `drained-event`;
1368
- };
1369
- var getDispatcherDrainedByKey = (key) => {
1370
- return `${key}-drained-event`;
1371
- };
1372
- var getDispatcherStatusKey = () => {
1373
- return `status-event`;
1374
- };
1375
- var getDispatcherStatusByKey = (key) => {
1376
- return `${key}-status-event`;
1377
- };
1378
- var getDispatcherChangeKey = () => {
1379
- return `change-event`;
1380
- };
1381
- var getDispatcherChangeByKey = (key) => {
1382
- return `${key}-change-event`;
1383
- };
1384
- var getIsEqualTimestamp = (currentTimestamp, threshold, queueTimestamp) => {
1385
- if (!queueTimestamp) {
1386
- return false;
1387
- }
1388
- return queueTimestamp - currentTimestamp <= threshold;
1389
- };
1390
- var canRetryRequest = (currentRetries, retry) => {
1391
- if (retry && currentRetries < retry) {
1392
- return true;
1393
- }
1394
- return false;
1395
- };
1396
- var isInDeduplicateRange = (request, latestRequest) => {
1397
- if (request.deduplicateTime) {
1398
- return +/* @__PURE__ */ new Date() - latestRequest.timestamp <= request.deduplicateTime;
1399
- }
1400
- return true;
1401
- };
1402
- var getRequestType = (request, latestRequest) => {
1403
- const { queued, cancelable, deduplicate } = request;
1404
- const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;
1405
- if (queued) {
1406
- return "one-by-one" /* ONE_BY_ONE */;
1407
- }
1408
- if (cancelable) {
1409
- return "previous-canceled" /* PREVIOUS_CANCELED */;
1410
- }
1411
- if (canDeduplicate && deduplicate) {
1412
- return "deduplicated" /* DEDUPLICATED */;
1413
- }
1414
- return "all-at-once" /* ALL_AT_ONCE */;
1415
- };
1416
-
1417
- // src/request/request.utils.ts
1418
- var stringifyKey = (value) => {
1419
- try {
1420
- if (typeof value === "string") return value;
1421
- if (value === void 0 || value === null) return "";
1422
- const data = JSON.stringify(value);
1423
- if (typeof data !== "string") throw new Error();
1424
- return data;
1425
- } catch (_) {
1426
- return "";
1427
- }
1428
- };
1429
- var getProgressValue = ({ loaded, total }) => {
1430
- if (!loaded || !total) return 0;
1431
- return Number((loaded * 100 / total).toFixed(0));
1432
- };
1433
- var getRequestEta = (startDate, progressDate, { total, loaded }) => {
1434
- const timeElapsed = +progressDate - +startDate || 1;
1435
- const uploadSpeed = loaded / timeElapsed;
1436
- const totalValue = Math.max(total, loaded);
1437
- const sizeLeft = totalValue - loaded;
1438
- const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;
1439
- const timeLeft = totalValue === loaded ? 0 : estimatedTimeValue;
1440
- return { timeLeft, sizeLeft };
1441
- };
1442
- var getProgressData = (requestStartTime, progressDate, progressEvent) => {
1443
- const { total, loaded } = progressEvent;
1444
- if (Number.isNaN(total) || Number.isNaN(loaded)) {
1445
- return {
1446
- progress: 0,
1447
- timeLeft: 0,
1448
- sizeLeft: 0,
1449
- total: 0,
1450
- loaded: 0,
1451
- startTimestamp: +requestStartTime
1452
- };
1453
- }
1454
- const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);
1455
- return {
1456
- progress: getProgressValue(progressEvent),
1457
- timeLeft,
1458
- sizeLeft,
1459
- total,
1460
- loaded,
1461
- startTimestamp: +requestStartTime
1462
- };
1463
- };
1464
- var getSimpleKey = (request) => {
1465
- return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;
1466
- };
1467
- var getRequestKey = (request, useInitialValues) => {
1468
- const methodKey = stringifyKey(request.method);
1469
- const endpointKey = useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint);
1470
- const queryParamsKey = useInitialValues ? "" : stringifyKey(request.queryParams);
1471
- return `${methodKey}_${endpointKey}_${queryParamsKey}`;
1472
- };
1473
- var getRequestDispatcher = (request, dispatcherType = "auto") => {
1474
- const { fetchDispatcher, submitDispatcher } = request.client;
1475
- const isGet = request.method === "GET" /* GET */;
1476
- const isFetchDispatcher = dispatcherType === "auto" && isGet || dispatcherType === "fetch";
1477
- const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;
1478
- return [dispatcher, isFetchDispatcher];
1479
- };
1480
- var sendRequest = (request, options) => {
1481
- const { client } = request;
1482
- const { requestManager } = client;
1483
- const [dispatcher] = getRequestDispatcher(request, options == null ? void 0 : options.dispatcherType);
1484
- return new Promise((resolve) => {
1485
- var _a;
1486
- let isResolved = false;
1487
- const requestId = dispatcher.add(request);
1488
- (_a = options == null ? void 0 : options.onBeforeSent) == null ? void 0 : _a.call(options, { requestId, request });
1489
- const unmountRequestStart = requestManager.events.onRequestStartById(
1490
- requestId,
1491
- (data) => {
1492
- var _a2;
1493
- return (_a2 = options == null ? void 0 : options.onRequestStart) == null ? void 0 : _a2.call(options, data);
1494
- }
1495
- );
1496
- const unmountResponseStart = requestManager.events.onResponseStartById(
1497
- requestId,
1498
- (data) => {
1499
- var _a2;
1500
- return (_a2 = options == null ? void 0 : options.onResponseStart) == null ? void 0 : _a2.call(options, data);
1501
- }
1502
- );
1503
- const unmountUpload = requestManager.events.onUploadProgressById(
1504
- requestId,
1505
- (data) => {
1506
- var _a2;
1507
- return (_a2 = options == null ? void 0 : options.onUploadProgress) == null ? void 0 : _a2.call(options, data);
1508
- }
1509
- );
1510
- const unmountDownload = requestManager.events.onDownloadProgressById(
1511
- requestId,
1512
- (data) => {
1513
- var _a2;
1514
- return (_a2 = options == null ? void 0 : options.onDownloadProgress) == null ? void 0 : _a2.call(options, data);
1515
- }
1516
- );
1517
- const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
1518
- var _a2;
1519
- const { details, response } = values;
1520
- isResolved = true;
1521
- const mapping = (_a2 = request.unstable_responseMapper) == null ? void 0 : _a2.call(
1522
- request,
1523
- response
1524
- );
1525
- const isOfflineStatus = request.offline && details.isOffline;
1526
- const willRetry = canRetryRequest(details.retries, request.retry);
1527
- const handleResponse2 = (success, data) => {
1528
- var _a3;
1529
- if (!success && isOfflineStatus) return;
1530
- if (!success && willRetry) return;
1531
- (_a3 = options == null ? void 0 : options.onResponse) == null ? void 0 : _a3.call(options, values);
1532
- resolve(data);
1533
- umountAll();
1534
- };
1535
- if (mapping instanceof Promise) {
1536
- (() => __async(null, null, function* () {
1537
- const responseData = yield mapping;
1538
- const { success } = responseData;
1539
- handleResponse2(success, responseData);
1540
- }))();
1541
- } else {
1542
- const data = mapping || response;
1543
- const { success } = data;
1544
- handleResponse2(success, data);
1545
- }
1546
- });
1547
- const unmountRemoveQueueElement = requestManager.events.onRemoveById(requestId, (...props) => {
1548
- var _a2;
1549
- if (!isResolved) {
1550
- (_a2 = options == null ? void 0 : options.onRemove) == null ? void 0 : _a2.call(options, ...props);
1551
- resolve({
1552
- data: null,
1553
- status: null,
1554
- success: false,
1555
- error: getErrorMessage("deleted"),
1556
- extra: request.client.adapter.defaultExtra,
1557
- requestTimestamp: +/* @__PURE__ */ new Date(),
1558
- responseTimestamp: +/* @__PURE__ */ new Date()
1559
- });
1560
- umountAll();
1561
- }
1562
- });
1563
- function umountAll() {
1564
- unmountRequestStart();
1565
- unmountResponseStart();
1566
- unmountUpload();
1567
- unmountDownload();
1568
- unmountResponse();
1569
- unmountRemoveQueueElement();
1570
- }
1571
- });
1572
- };
1573
-
1574
- // src/adapter/adapter.bindings.ts
1575
- var getAdapterBindings = (_0) => __async(null, [_0], function* ({
1576
- request: baseRequest,
1577
- requestId,
1578
- resolve,
1579
- onStartTime,
1580
- internalErrorMapping
1581
- }) {
1582
- const { requestManager, loggerManager } = baseRequest.client;
1583
- const { unstable_payloadMapper } = baseRequest.client.adapter;
1584
- const logger2 = loggerManager.initialize(baseRequest.client, "Adapter");
1585
- let requestStartTimestamp = null;
1586
- let responseStartTimestamp = null;
1587
- let request = baseRequest;
1588
- let requestTotal = 1;
1589
- let responseTotal = 1;
1590
- let previousRequestTotal = 0;
1591
- let previousResponseTotal = 0;
1592
- logger2.debug({
1593
- title: `Running middleware callbacks`,
1594
- type: "request",
1595
- extra: {
1596
- request,
1597
- requestId
1598
- }
1599
- });
1600
- request = yield request.client.unstable_modifyRequest(request);
1601
- if (request.auth) {
1602
- request = yield request.client.unstable_modifyAuth(request);
1603
- }
1604
- if (request.unstable_requestMapper) {
1605
- request = yield request.unstable_requestMapper(request, requestId);
1606
- }
1607
- const { client, abortKey } = request;
1608
- let payload = request.payload;
1609
- if (request.unstable_payloadMapper) {
1610
- payload = yield request.unstable_payloadMapper(request.payload);
1611
- } else if (unstable_payloadMapper) {
1612
- payload = yield unstable_payloadMapper(payload);
1613
- }
1614
- const adapterOptions = request.options;
1615
- const startTime = +/* @__PURE__ */ new Date();
1616
- onStartTime(startTime);
1617
- const getRequestStartTimestamp = () => {
1618
- return requestStartTimestamp;
1619
- };
1620
- const getResponseStartTimestamp = () => {
1621
- return responseStartTimestamp;
1622
- };
1623
- const getTotal = (previousTotal, progress) => {
1624
- if (!progress) return previousTotal;
1625
- const total = Number(progress.total || 0);
1626
- const loaded = Number(progress.loaded || 0);
1627
- return Math.max(total, loaded, previousTotal);
1628
- };
1629
- const handleRequestProgress = (startTimestamp, progressTimestamp, progressEvent) => {
1630
- const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
1631
- if (previousRequestTotal !== 100) {
1632
- previousRequestTotal = progress.total;
1633
- requestManager.events.emitUploadProgress(__spreadProps(__spreadValues({}, progress), { requestId, request }));
1634
- }
1635
- };
1636
- const handleResponseProgress = (startTimestamp, progressTimestamp, progressEvent) => {
1637
- const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
1638
- if (previousResponseTotal !== 100) {
1639
- previousResponseTotal = progress.total;
1640
- requestManager.events.emitDownloadProgress(__spreadProps(__spreadValues({}, progress), { requestId, request }));
1641
- }
1642
- };
1643
- const onBeforeRequest = () => {
1644
- logger2.debug({
1645
- title: `Request about to be sent`,
1646
- type: "request",
1647
- extra: {
1648
- request,
1649
- requestId
1650
- }
1651
- });
1652
- client.triggerPlugins("onRequestTrigger", { request });
1653
- };
1654
- const onRequestStart = (progress) => {
1655
- logger2.info({
1656
- title: `Request start`,
1657
- type: "request",
1658
- extra: {
1659
- request,
1660
- requestId
1661
- }
1662
- });
1663
- client.triggerPlugins("onRequestStart", { request });
1664
- if (progress == null ? void 0 : progress.total) {
1665
- requestTotal = getTotal(requestTotal, progress);
1666
- }
1667
- const initialPayload = {
1668
- total: requestTotal,
1669
- loaded: (progress == null ? void 0 : progress.loaded) || 0
1670
- };
1671
- requestStartTimestamp = +/* @__PURE__ */ new Date();
1672
- handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);
1673
- requestManager.events.emitRequestStart({ requestId, request });
1674
- return requestStartTimestamp;
1675
- };
1676
- const onRequestProgress = (progress) => {
1677
- if (!requestStartTimestamp) {
1678
- requestStartTimestamp = +/* @__PURE__ */ new Date();
1679
- }
1680
- requestTotal = getTotal(requestTotal, progress);
1681
- const progressTimestamp = +/* @__PURE__ */ new Date();
1682
- handleRequestProgress(requestStartTimestamp, progressTimestamp, {
1683
- total: requestTotal,
1684
- loaded: progress.loaded || 0
1685
- });
1686
- return progressTimestamp;
1687
- };
1688
- const onRequestEnd = () => {
1689
- if (!requestStartTimestamp) {
1690
- requestStartTimestamp = +/* @__PURE__ */ new Date();
1691
- }
1692
- const progressTimestamp = +/* @__PURE__ */ new Date();
1693
- handleRequestProgress(requestStartTimestamp, progressTimestamp, {
1694
- total: requestTotal,
1695
- loaded: requestTotal
1696
- });
1697
- return progressTimestamp;
1698
- };
1699
- const onResponseStart = (progress) => {
1700
- responseStartTimestamp = +/* @__PURE__ */ new Date();
1701
- responseTotal = getTotal(responseTotal, progress);
1702
- const initialPayload = {
1703
- total: responseTotal,
1704
- loaded: (progress == null ? void 0 : progress.loaded) || 0
1705
- };
1706
- handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);
1707
- requestManager.events.emitResponseStart({ requestId, request });
1708
- return responseStartTimestamp;
1709
- };
1710
- const onResponseProgress = (progress) => {
1711
- if (!responseStartTimestamp) {
1712
- responseStartTimestamp = +/* @__PURE__ */ new Date();
1713
- }
1714
- const progressTimestamp = +/* @__PURE__ */ new Date();
1715
- responseTotal = getTotal(responseTotal, progress);
1716
- handleResponseProgress(responseStartTimestamp, progressTimestamp, {
1717
- total: progress.total || responseTotal,
1718
- loaded: progress.loaded || 0
1719
- });
1720
- return progressTimestamp;
1721
- };
1722
- const onResponseEnd = () => {
1723
- if (!responseStartTimestamp) {
1724
- responseStartTimestamp = +/* @__PURE__ */ new Date();
1725
- }
1726
- const progressTimestamp = +/* @__PURE__ */ new Date();
1727
- handleResponseProgress(responseStartTimestamp, progressTimestamp, {
1728
- total: responseTotal,
1729
- loaded: responseTotal
1730
- });
1731
- return progressTimestamp;
1732
- };
1733
- const onSuccess = (_02) => __async(null, [_02], function* ({
1734
- data,
1735
- error,
1736
- status,
1737
- extra
1738
- }) {
1739
- var _a, _b, _c, _d;
1740
- let response = {
1741
- data,
1742
- error: error != null ? error : null,
1743
- success: true,
1744
- status,
1745
- extra,
1746
- requestTimestamp: startTime,
1747
- responseTimestamp: +/* @__PURE__ */ new Date()
1748
- };
1749
- response = yield (_b = (_a = request.client).unstable_modifyResponse) == null ? void 0 : _b.call(_a, response, request);
1750
- response = yield (_d = (_c = request.client).unstable_modifySuccessResponse) == null ? void 0 : _d.call(_c, response, request);
1751
- client.triggerPlugins("onRequestSuccess", { response, request });
1752
- client.triggerPlugins("onRequestFinished", { response, request });
1753
- resolve(response);
1754
- logger2.info({
1755
- title: `Response success`,
1756
- type: "response",
1757
- extra: {
1758
- request,
1759
- requestId,
1760
- response
1761
- }
1762
- });
1763
- return response;
1764
- });
1765
- const onError = getAdapterOnError({
1766
- request,
1767
- requestId,
1768
- startTime,
1769
- logger: logger2,
1770
- resolve
1771
- });
1772
- const onAbortError = ({
1773
- status,
1774
- extra
1775
- }) => {
1776
- logger2.error({
1777
- title: `Abort error`,
1778
- type: "request",
1779
- extra: {
1780
- request,
1781
- requestId
1782
- }
1783
- });
1784
- const error = internalErrorMapping(getErrorMessage("abort"));
1785
- return onError({ error, status, extra });
1786
- };
1787
- const onTimeoutError = ({
1788
- status,
1789
- extra
1790
- }) => {
1791
- logger2.error({
1792
- title: `Timeout error`,
1793
- type: "request",
1794
- extra: {
1795
- request,
1796
- requestId
1797
- }
1798
- });
1799
- const error = getErrorMessage("timeout");
1800
- return onError({ error, status, extra });
1801
- };
1802
- const onUnexpectedError = ({
1803
- status,
1804
- extra
1805
- }) => {
1806
- logger2.error({
1807
- title: `Unexpected error`,
1808
- type: "request",
1809
- extra: {
1810
- request,
1811
- requestId
1812
- }
1813
- });
1814
- const error = getErrorMessage();
1815
- return onError({ error, status, extra });
1816
- };
1817
- const getAbortController = () => {
1818
- return requestManager.getAbortController(abortKey, requestId);
1819
- };
1820
- const createAbortListener = ({
1821
- status,
1822
- extra,
1823
- onAbort = () => {
1824
- }
1825
- }) => {
1826
- const controller = getAbortController();
1827
- if (!controller) {
1828
- throw new RequestProcessingError("Controller is not found");
1829
- }
1830
- const abort = () => {
1831
- onAbortError({ status, extra });
1832
- onAbort();
1833
- requestManager.events.emitAbort({ requestId, request });
1834
- };
1835
- if (controller.signal.aborted) {
1836
- abort();
1837
- }
1838
- controller.signal.addEventListener("abort", abort);
1839
- return () => controller.signal.removeEventListener("abort", abort);
1840
- };
1841
- logger2.debug({
1842
- title: `Mounted adapter bindings`,
1843
- type: "request",
1844
- extra: {
1845
- request,
1846
- requestId,
1847
- payload,
1848
- adapterOptions
1849
- }
1850
- });
1851
- const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);
1852
- const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);
1853
- const headers = baseRequest.client.adapter.unstable_headerMapper(request);
1854
- const { url } = baseRequest.client;
1855
- return {
1856
- request,
1857
- requestId,
1858
- url,
1859
- endpoint,
1860
- queryParams,
1861
- payload,
1862
- headers,
1863
- adapter: baseRequest.client.adapter,
1864
- adapterOptions,
1865
- getAbortController,
1866
- getRequestStartTimestamp,
1867
- getResponseStartTimestamp,
1868
- createAbortListener,
1869
- onBeforeRequest,
1870
- onRequestStart,
1871
- onRequestProgress,
1872
- onRequestEnd,
1873
- onResponseStart,
1874
- onResponseProgress,
1875
- onResponseEnd,
1876
- onSuccess,
1877
- onAbortError,
1878
- onTimeoutError,
1879
- onUnexpectedError,
1880
- onError
1881
- };
1882
- });
1883
- function getAdapterOnError({
1884
- request,
1885
- requestId,
1886
- startTime,
1887
- resolve,
1888
- logger: logger2
1889
- }) {
1890
- const { client } = request;
1891
- return (_0) => __async(null, [_0], function* ({
1892
- error,
1893
- status,
1894
- extra
1895
- }) {
1896
- let response = {
1897
- data: null,
1898
- status,
1899
- error,
1900
- success: false,
1901
- extra,
1902
- requestTimestamp: startTime,
1903
- responseTimestamp: +/* @__PURE__ */ new Date()
1904
- };
1905
- response = yield client.unstable_modifyResponse(response, request);
1906
- response = yield client.unstable_modifyErrorResponse(response, request);
1907
- client.triggerPlugins("onRequestError", { response, request });
1908
- client.triggerPlugins("onRequestFinished", { response, request });
1909
- resolve(response);
1910
- logger2.error({
1911
- title: `Request error`,
1912
- type: "request",
1913
- extra: {
1914
- request,
1915
- requestId,
1916
- response
1917
- }
1918
- });
1919
- return response;
1920
- });
1921
- }
1922
-
1923
- // src/mocker/mocker.ts
1924
- var mocker = (_0) => __async(null, [_0], function* ({
1925
- request,
1926
- requestId,
1927
- onError,
1928
- onResponseEnd,
1929
- onTimeoutError,
1930
- onRequestEnd,
1931
- createAbortListener,
1932
- onResponseProgress,
1933
- onRequestProgress,
1934
- onResponseStart,
1935
- onBeforeRequest,
1936
- onRequestStart,
1937
- onSuccess,
1938
- onAbortError,
1939
- adapter
1940
- }) {
1941
- if (!request.unstable_mock) {
1942
- throw new RequestProcessingError("Mock should be defined when calling mocker");
1943
- }
1944
- let thrown = false;
1945
- const {
1946
- requestTime = 20,
1947
- responseTime = 20,
1948
- totalUploaded = 1e3,
1949
- totalDownloaded = 1e3,
1950
- timeout
1951
- } = request.unstable_mock.config;
1952
- const result = yield request.unstable_mock.fn({ request, requestId });
1953
- const { data, error, status, success = true, extra = request.client.adapter.defaultExtra } = result;
1954
- createAbortListener({
1955
- status: adapter.systemErrorStatus,
1956
- extra: adapter.systemErrorExtra,
1957
- onAbort: () => {
1958
- thrown = true;
1959
- }
1960
- });
1961
- onBeforeRequest();
1962
- onRequestStart();
1963
- const progress = (totalTime, totalSize, progressFunction) => new Promise((resolveProgress) => {
1964
- if (thrown) {
1965
- resolveProgress(true);
1966
- return;
1967
- }
1968
- const interval = 20;
1969
- const dataStart = +/* @__PURE__ */ new Date();
1970
- const intervals = Math.ceil(totalTime / interval);
1971
- const chunkSize = Math.ceil(totalSize / intervals);
1972
- let currentlyLoaded = 0;
1973
- const timer = setInterval(function handleProgressInterval() {
1974
- if (thrown) {
1975
- resolveProgress(true);
1976
- clearInterval(timer);
1977
- }
1978
- const currentTime = Math.min(totalTime, +/* @__PURE__ */ new Date() - dataStart);
1979
- currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;
1980
- progressFunction({
1981
- total: totalSize,
1982
- loaded: currentTime >= totalTime ? totalSize : currentlyLoaded
1983
- });
1984
- if (currentTime >= totalTime) {
1985
- resolveProgress(true);
1986
- clearInterval(timer);
1987
- }
1988
- }, interval);
1989
- });
1990
- if (typeof timeout === "number") {
1991
- setTimeout(() => {
1992
- thrown = true;
1993
- onTimeoutError({
1994
- status: 0,
1995
- extra
1996
- });
1997
- }, timeout);
1998
- }
1999
- if (!thrown) {
2000
- yield progress(requestTime, totalUploaded, onRequestProgress);
2001
- }
2002
- if (!thrown) {
2003
- onRequestEnd();
2004
- onResponseStart();
2005
- }
2006
- if (!thrown) {
2007
- yield progress(responseTime, totalDownloaded, onResponseProgress);
2008
- }
2009
- if (thrown) {
2010
- onAbortError({
2011
- status: adapter.systemErrorStatus,
2012
- extra: adapter.systemErrorExtra
2013
- });
2014
- } else if (success || error && data) {
2015
- onSuccess({
2016
- data,
2017
- error,
2018
- status,
2019
- extra
2020
- });
2021
- } else {
2022
- onError({
2023
- error,
2024
- status,
2025
- extra
2026
- });
2027
- }
2028
- if (!thrown) {
2029
- onResponseEnd();
2030
- }
2031
- });
2032
-
2033
- // src/managers/app/app.manager.ts
2034
- var AppManager = class {
2035
- constructor(options) {
2036
- this.options = options;
2037
- __publicField(this, "emitter", new EventEmitter());
2038
- __publicField(this, "events", getAppManagerEvents(this.emitter));
2039
- __publicField(this, "isBrowser");
2040
- __publicField(this, "isOnline");
2041
- __publicField(this, "isFocused");
2042
- __publicField(this, "initialize", () => {
2043
- const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } = this.options || appManagerInitialOptions;
2044
- focusEvent(this.setFocused);
2045
- onlineEvent(this.setOnline);
2046
- });
2047
- __publicField(this, "setInitialFocus", (initValue) => __async(this, null, function* () {
2048
- if (typeof initValue === "function") {
2049
- this.isFocused = false;
2050
- this.isFocused = yield initValue();
2051
- } else {
2052
- this.isFocused = initValue;
2053
- }
2054
- }));
2055
- __publicField(this, "setInitialOnline", (initValue) => __async(this, null, function* () {
2056
- if (typeof initValue === "function") {
2057
- this.isOnline = false;
2058
- this.isOnline = yield initValue();
2059
- } else {
2060
- this.isOnline = initValue;
2061
- }
2062
- }));
2063
- __publicField(this, "setFocused", (isFocused) => {
2064
- this.isFocused = isFocused;
2065
- if (isFocused) {
2066
- this.events.emitFocus();
2067
- } else {
2068
- this.events.emitBlur();
2069
- }
2070
- });
2071
- __publicField(this, "setOnline", (isOnline) => {
2072
- this.isOnline = isOnline;
2073
- if (isOnline) {
2074
- this.events.emitOnline();
2075
- } else {
2076
- this.events.emitOffline();
2077
- }
2078
- });
2079
- var _a;
2080
- (_a = this.emitter) == null ? void 0 : _a.setMaxListeners(1e3);
2081
- const {
2082
- initiallyFocused = appManagerInitialOptions.initiallyFocused,
2083
- initiallyOnline = appManagerInitialOptions.initiallyOnline
2084
- } = this.options || appManagerInitialOptions;
2085
- this.setInitialFocus(initiallyFocused);
2086
- this.setInitialOnline(initiallyOnline);
2087
- this.isBrowser = hasDocument();
2088
- }
2089
- };
2090
-
2091
- // src/managers/app/app.manager.utils.ts
2092
- var hasWindow = () => {
2093
- try {
2094
- return Boolean(window && window.addEventListener);
2095
- } catch (err) {
2096
- return false;
2097
- }
2098
- };
2099
- var hasDocument = () => {
2100
- try {
2101
- return Boolean(hasWindow() && window.document && window.document.addEventListener);
2102
- } catch (err) {
2103
- return false;
2104
- }
2105
- };
2106
- var onWindowEvent = (key, listener, options) => {
2107
- if (hasWindow()) {
2108
- window.addEventListener(key, listener, options);
2109
- return () => window.removeEventListener(key, listener, options);
2110
- }
2111
- return () => null;
2112
- };
2113
- var onDocumentEvent = (key, listener, options) => {
2114
- if (hasDocument()) {
2115
- window.document.addEventListener(key, listener, options);
2116
- return () => window.document.removeEventListener(key, listener, options);
2117
- }
2118
- return () => null;
2119
- };
2120
-
2121
- // src/managers/app/app.manager.events.ts
2122
- var getAppManagerEvents = (emitter) => ({
2123
- emitFocus: () => {
2124
- emitter.emit("focus" /* FOCUS */);
2125
- },
2126
- emitBlur: () => {
2127
- emitter.emit("blur" /* BLUR */);
2128
- },
2129
- emitOnline: () => {
2130
- emitter.emit("online" /* ONLINE */);
2131
- },
2132
- emitOffline: () => {
2133
- emitter.emit("offline" /* OFFLINE */);
2134
- },
2135
- onFocus: (callback) => {
2136
- emitter.on("focus" /* FOCUS */, callback);
2137
- return () => emitter.removeListener("focus" /* FOCUS */, callback);
2138
- },
2139
- onBlur: (callback) => {
2140
- emitter.on("blur" /* BLUR */, callback);
2141
- return () => emitter.removeListener("blur" /* BLUR */, callback);
2142
- },
2143
- onOnline: (callback) => {
2144
- emitter.on("online" /* ONLINE */, callback);
2145
- return () => emitter.removeListener("online" /* ONLINE */, callback);
2146
- },
2147
- onOffline: (callback) => {
2148
- emitter.on("offline" /* OFFLINE */, callback);
2149
- return () => emitter.removeListener("offline" /* OFFLINE */, callback);
2150
- }
2151
- });
2152
-
2153
- // src/managers/app/app.manager.constants.ts
2154
- var AppEvents = /* @__PURE__ */ ((AppEvents2) => {
2155
- AppEvents2["FOCUS"] = "focus";
2156
- AppEvents2["BLUR"] = "blur";
2157
- AppEvents2["ONLINE"] = "online";
2158
- AppEvents2["OFFLINE"] = "offline";
2159
- return AppEvents2;
2160
- })(AppEvents || {});
2161
- var appManagerInitialOptions = {
2162
- initiallyFocused: true,
2163
- initiallyOnline: true,
2164
- focusEvent: (setFocused) => {
2165
- onDocumentEvent("visibilitychange", () => setFocused(true));
2166
- onWindowEvent("focus", () => setFocused(true));
2167
- onWindowEvent("blur", () => setFocused(false));
2168
- },
2169
- onlineEvent: (setOnline) => {
2170
- onWindowEvent("online", () => setOnline(true));
2171
- onWindowEvent("offline", () => setOnline(false));
2172
- }
2173
- };
2174
-
2175
- // src/managers/request/request.manager.ts
2176
- var RequestManager = class {
2177
- constructor() {
2178
- __publicField(this, "emitter", new EventEmitter());
2179
- __publicField(this, "events", getRequestManagerEvents(this.emitter));
2180
- __publicField(this, "abortControllers", /* @__PURE__ */ new Map());
2181
- __publicField(this, "addAbortController", (abortKey, requestId) => {
2182
- let abortGroup = this.abortControllers.get(abortKey);
2183
- if (!abortGroup) {
2184
- const newAbortGroup = /* @__PURE__ */ new Map();
2185
- abortGroup = newAbortGroup;
2186
- this.abortControllers.set(abortKey, newAbortGroup);
2187
- }
2188
- const abortController = abortGroup.get(requestId);
2189
- if (!abortController || abortController.signal.aborted) {
2190
- abortGroup.set(requestId, new AbortController());
2191
- }
2192
- });
2193
- __publicField(this, "getAbortController", (abortKey, requestId) => {
2194
- var _a;
2195
- return (_a = this.abortControllers.get(abortKey)) == null ? void 0 : _a.get(requestId);
2196
- });
2197
- __publicField(this, "removeAbortController", (abortKey, requestId) => {
2198
- var _a;
2199
- (_a = this.abortControllers.get(abortKey)) == null ? void 0 : _a.delete(requestId);
2200
- });
2201
- // Aborting
2202
- __publicField(this, "useAbortController", (abortKey, requestId) => {
2203
- var _a;
2204
- const controller = (_a = this.abortControllers.get(abortKey)) == null ? void 0 : _a.get(requestId);
2205
- controller == null ? void 0 : controller.abort();
2206
- });
2207
- __publicField(this, "abortByKey", (abortKey) => {
2208
- const controllers = this.abortControllers.get(abortKey);
2209
- if (controllers) {
2210
- const entries = Array.from(controllers.entries());
2211
- entries.forEach(([key]) => {
2212
- this.useAbortController(abortKey, key);
2213
- });
2214
- }
2215
- });
2216
- __publicField(this, "abortByRequestId", (abortKey, requestId) => {
2217
- this.useAbortController(abortKey, requestId);
2218
- });
2219
- __publicField(this, "abortAll", () => {
2220
- const entries = Array.from(this.abortControllers.entries());
2221
- entries.forEach(([abortKey, value]) => {
2222
- const controllers = Array.from(value.entries());
2223
- controllers.forEach(([requestId]) => {
2224
- this.useAbortController(abortKey, requestId);
2225
- });
2226
- });
2227
- });
2228
- var _a;
2229
- (_a = this.emitter) == null ? void 0 : _a.setMaxListeners(1e3);
2230
- }
2231
- };
2232
-
2233
- // src/managers/request/request.manager.utils.ts
2234
- var getLoadingKey = () => `loading-event-any`;
2235
- var getLoadingByQueryKey = (queryKey) => `${queryKey}-loading-event`;
2236
- var getLoadingByCacheKey = (cacheKey) => `${cacheKey}-loading-cache-event`;
2237
- var getLoadingByIdKey = (id) => `${id}-loading-event-by-id`;
2238
- var getRemoveKey = () => `remove-event-any`;
2239
- var getRemoveByQueryKey = (queryKey) => `${queryKey}-remove-event`;
2240
- var getRemoveByIdKey = (id) => `${id}-remove-event-by-id`;
2241
- var getAbortKey = () => `request-abort-any`;
2242
- var getAbortByAbortKey = (abortKey) => `${abortKey}-request-abort`;
2243
- var getAbortByIdKey = (id) => `${id}-request-abort-by-id`;
2244
- var getResponseKey = () => `response-any`;
2245
- var getResponseByCacheKey = (cacheKey) => `${cacheKey}-response`;
2246
- var getResponseByIdKey = (id) => `${id}-response-by-id`;
2247
- var getRequestStartKey = () => `request-start-any`;
2248
- var getRequestStarByQueryKey = (queryKey) => `${queryKey}-request-start`;
2249
- var getRequestStartByIdKey = (id) => `${id}-request-start-by-id`;
2250
- var getResponseStartKey = () => `response-start-any`;
2251
- var getResponseStartByQueryKey = (queryKey) => `${queryKey}-response-start`;
2252
- var getResponseStartByIdKey = (id) => `${id}-response-start-by-id`;
2253
- var getUploadProgressKey = () => `request-progress-any`;
2254
- var getUploadProgressByQueryKey = (queryKey) => `${queryKey}-request-progress`;
2255
- var getUploadProgressByIdKey = (id) => `${id}-request-progress-by-id`;
2256
- var getDownloadProgressKey = () => `response-progress-any`;
2257
- var getDownloadProgressByQueryKey = (queryKey) => `${queryKey}-response-progress`;
2258
- var getDownloadProgressByIdKey = (id) => `${id}-response-progress-by-id`;
2259
- var getRequestDeduplicatedKey = () => `request-deduplicated-any`;
2260
- var getRequestDeduplicatedByQueryKey = (queryKey) => `${queryKey}-query-request-deduplicated`;
2261
- var getRequestDeduplicatedByCacheKey = (cacheKey) => `${cacheKey}-cache-request-deduplicated`;
2262
- var getRequestDeduplicatedByIdKey = (id) => `${id}-request-deduplicated-by-id`;
2263
-
2264
- // src/managers/request/request.manager.events.ts
2265
- var getRequestManagerEvents = (emitter) => ({
2266
- /**
2267
- * Emiter
2268
- */
2269
- // Deduplicated
2270
- emitDeduplicated: (data, isTriggeredExternally = false) => {
2271
- emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);
2272
- emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);
2273
- emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
2274
- emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2275
- },
2276
- // Loading
2277
- emitLoading: (data, isTriggeredExternally = false) => {
2278
- emitter.emit(getLoadingKey(), data, isTriggeredExternally);
2279
- emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);
2280
- emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
2281
- emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2282
- },
2283
- // Start
2284
- emitRequestStart: (data, isTriggeredExternally = false) => {
2285
- emitter.emit(getRequestStartKey(), data, isTriggeredExternally);
2286
- emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);
2287
- emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2288
- },
2289
- emitResponseStart: (data, isTriggeredExternally = false) => {
2290
- emitter.emit(getResponseStartKey(), data, isTriggeredExternally);
2291
- emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);
2292
- emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2293
- },
2294
- // Progress
2295
- emitUploadProgress: (data, isTriggeredExternally = false) => {
2296
- emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);
2297
- emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);
2298
- emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2299
- },
2300
- emitDownloadProgress: (data, isTriggeredExternally = false) => {
2301
- emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);
2302
- emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);
2303
- emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2304
- },
2305
- // Response
2306
- emitResponse: (data, isTriggeredExternally = false) => {
2307
- emitter.emit(getResponseKey(), data, isTriggeredExternally);
2308
- emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);
2309
- emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
2310
- },
2311
- // Abort
2312
- emitAbort: (data, isTriggeredExternally = false) => {
2313
- emitter.emit(getAbortKey(), data, isTriggeredExternally);
2314
- emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);
2315
- emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);
2316
- },
2317
- // Remove
2318
- emitRemove: (data, isTriggeredExternally = false) => {
2319
- emitter.emit(getRemoveKey(), data, isTriggeredExternally);
2320
- emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);
2321
- emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);
2322
- },
2323
- /**
2324
- * Listeners
2325
- */
2326
- // Deduplicated
2327
- onDeduplicated: (callback) => {
2328
- emitter.on(getRequestDeduplicatedKey(), callback);
2329
- return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);
2330
- },
2331
- onDeduplicatedByQueue: (queryKey, callback) => {
2332
- emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);
2333
- return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);
2334
- },
2335
- onDeduplicatedByCache: (cacheKey, callback) => {
2336
- emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);
2337
- return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);
2338
- },
2339
- onDeduplicatedById: (requestId, callback) => {
2340
- emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);
2341
- return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);
2342
- },
2343
- // Loading
2344
- onLoading: (callback) => {
2345
- emitter.on(getLoadingKey(), callback);
2346
- return () => emitter.removeListener(getLoadingKey(), callback);
2347
- },
2348
- onLoadingByQueue: (queryKey, callback) => {
2349
- emitter.on(getLoadingByQueryKey(queryKey), callback);
2350
- return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);
2351
- },
2352
- onLoadingByCache: (cacheKey, callback) => {
2353
- emitter.on(getLoadingByCacheKey(cacheKey), callback);
2354
- return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);
2355
- },
2356
- onLoadingById: (requestId, callback) => {
2357
- emitter.on(getLoadingByIdKey(requestId), callback);
2358
- return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);
2359
- },
2360
- // Request Start
2361
- onRequestStart: (callback) => {
2362
- emitter.on(getRequestStartKey(), callback);
2363
- return () => emitter.removeListener(getRequestStartKey(), callback);
2364
- },
2365
- onRequestStartByQueue: (queryKey, callback) => {
2366
- emitter.on(getRequestStarByQueryKey(queryKey), callback);
2367
- return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);
2368
- },
2369
- onRequestStartById: (requestId, callback) => {
2370
- emitter.on(getRequestStartByIdKey(requestId), callback);
2371
- return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);
2372
- },
2373
- // Response Start
2374
- onResponseStart: (callback) => {
2375
- emitter.on(getResponseStartKey(), callback);
2376
- return () => emitter.removeListener(getResponseStartKey(), callback);
2377
- },
2378
- onResponseStartByQueue: (queryKey, callback) => {
2379
- emitter.on(getResponseStartByQueryKey(queryKey), callback);
2380
- return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);
2381
- },
2382
- onResponseStartById: (requestId, callback) => {
2383
- emitter.on(getResponseStartByIdKey(requestId), callback);
2384
- return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);
2385
- },
2386
- // Progress
2387
- onUploadProgress: (callback) => {
2388
- emitter.on(getUploadProgressKey(), callback);
2389
- return () => emitter.removeListener(getUploadProgressKey(), callback);
2390
- },
2391
- onUploadProgressByQueue: (queryKey, callback) => {
2392
- emitter.on(getUploadProgressByQueryKey(queryKey), callback);
2393
- return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);
2394
- },
2395
- onUploadProgressById: (requestId, callback) => {
2396
- emitter.on(getUploadProgressByIdKey(requestId), callback);
2397
- return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);
2398
- },
2399
- onDownloadProgress: (callback) => {
2400
- emitter.on(getDownloadProgressKey(), callback);
2401
- return () => emitter.removeListener(getDownloadProgressKey(), callback);
2402
- },
2403
- onDownloadProgressByQueue: (queryKey, callback) => {
2404
- emitter.on(getDownloadProgressByQueryKey(queryKey), callback);
2405
- return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);
2406
- },
2407
- onDownloadProgressById: (requestId, callback) => {
2408
- emitter.on(getDownloadProgressByIdKey(requestId), callback);
2409
- return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);
2410
- },
2411
- // Response
2412
- onResponse: (callback) => {
2413
- emitter.on(getResponseKey(), callback);
2414
- return () => emitter.removeListener(getResponseKey(), callback);
2415
- },
2416
- onResponseByCache: (cacheKey, callback) => {
2417
- emitter.on(getResponseByCacheKey(cacheKey), callback);
2418
- return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);
2419
- },
2420
- onResponseById: (requestId, callback) => {
2421
- emitter.on(getResponseByIdKey(requestId), callback);
2422
- return () => emitter.removeListener(getResponseByIdKey(requestId), callback);
2423
- },
2424
- // Abort
2425
- onAbort: (callback) => {
2426
- emitter.on(getAbortKey(), callback);
2427
- return () => emitter.removeListener(getAbortKey(), callback);
2428
- },
2429
- onAbortByKey: (abortKey, callback) => {
2430
- emitter.on(getAbortByAbortKey(abortKey), callback);
2431
- return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);
2432
- },
2433
- onAbortById: (requestId, callback) => {
2434
- emitter.on(getAbortByIdKey(requestId), callback);
2435
- return () => emitter.removeListener(getAbortByIdKey(requestId), callback);
2436
- },
2437
- // Remove
2438
- onRemove: (callback) => {
2439
- emitter.on(getRemoveKey(), callback);
2440
- return () => emitter.removeListener(getRemoveKey(), callback);
2441
- },
2442
- onRemoveByQueue: (queryKey, callback) => {
2443
- emitter.on(getRemoveByQueryKey(queryKey), callback);
2444
- return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);
2445
- },
2446
- onRemoveById: (requestId, callback) => {
2447
- emitter.on(getRemoveByIdKey(requestId), callback);
2448
- return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);
2449
- }
2450
- });
2451
-
2452
- // src/managers/logger/logger.manager.ts
2453
- var import_events2 = __toESM(require("events"));
2454
- var LoggerManager = class {
2455
- constructor(options) {
2456
- this.options = options;
2457
- __publicField(this, "logger");
2458
- __publicField(this, "level");
2459
- __publicField(this, "modules");
2460
- __publicField(this, "emitter", new import_events2.default());
2461
- __publicField(this, "client");
2462
- __publicField(this, "setSeverity", (level) => {
2463
- this.level = level;
2464
- });
2465
- __publicField(this, "setModules", (modules) => {
2466
- this.modules = modules;
2467
- });
2468
- __publicField(this, "initialize", (client, module2) => {
2469
- this.client = client;
2470
- return {
2471
- error: (data) => this.log(__spreadProps(__spreadValues({}, data), { level: "error", module: module2 })),
2472
- warning: (data) => this.log(__spreadProps(__spreadValues({}, data), { level: "warning", module: module2 })),
2473
- info: (data) => this.log(__spreadProps(__spreadValues({}, data), { level: "info", module: module2 })),
2474
- debug: (data) => this.log(__spreadProps(__spreadValues({}, data), { level: "debug", module: module2 }))
2475
- };
2476
- });
2477
- __publicField(this, "log", (data) => {
2478
- if (!this.client.debug) {
2479
- return;
2480
- }
2481
- if (logLevelOrder.indexOf(this.level) <= logLevelOrder.indexOf(data.level)) {
2482
- return;
2483
- }
2484
- if (this.modules && !this.modules.includes(data.module)) {
2485
- return;
2486
- }
2487
- this.logger(data);
2488
- });
2489
- var _a, _b, _c, _d;
2490
- (_a = this.emitter) == null ? void 0 : _a.setMaxListeners(1e3);
2491
- this.logger = ((_b = this.options) == null ? void 0 : _b.logger) || logger;
2492
- this.level = ((_c = this.options) == null ? void 0 : _c.level) || "warning";
2493
- this.modules = (_d = this.options) == null ? void 0 : _d.modules;
2494
- }
2495
- };
2496
-
2497
- // src/managers/logger/logger.manager.utils.ts
2498
- var getTime = () => {
2499
- const d = /* @__PURE__ */ new Date();
2500
- return `${d.toLocaleTimeString()}`;
2501
- };
2502
- var getModuleName = (data) => {
2503
- if (data.type === "request" || data.type === "response") {
2504
- return `${data.extra.request.endpoint}`;
2505
- }
2506
- return `[${data.module}]`;
2507
- };
2508
- var logger = (log) => {
2509
- var _a;
2510
- const styles = loggerStyles[log.level];
2511
- const color = loggerColors[log.level];
2512
- const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;
2513
- const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;
2514
- const style2 = `${styles}${color}font-weight:600;`;
2515
- const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;
2516
- if (log.extra ? (_a = Object.keys(log.extra)) == null ? void 0 : _a.length : false) {
2517
- console.groupCollapsed(message, style1, style2, style3);
2518
- console.log(log.extra);
2519
- console.groupEnd();
2520
- } else {
2521
- console.log(message, styles);
2522
- }
2523
- };
2524
-
2525
- // src/managers/logger/logger.manager.constants.ts
2526
- var logLevelOrder = ["error", "warning", "info", "debug"];
2527
- var defaultStyles = "padding:2px 5px;";
2528
- var loggerStyles = {
2529
- error: `${defaultStyles};background:#db252520;`,
2530
- warning: `${defaultStyles};background:#e1941e20;`,
2531
- info: `${defaultStyles};background:#1e74e120;`,
2532
- debug: `${defaultStyles};background:#00000020;`
2533
- };
2534
- var loggerColors = {
2535
- error: "color:#ff3737;",
2536
- warning: "color:#ffc107;",
2537
- info: "color:#34a8ff;",
2538
- debug: "color:#cccccc;"
2539
- };
2540
-
2541
- // src/adapter/adapter.utils.ts
2542
- var TimeoutError = class extends Error {
2543
- constructor() {
2544
- super("Request timeout");
2545
- this.name = "TimeoutError";
2546
- }
2547
- };
2548
- var AbortError = class extends Error {
2549
- constructor() {
2550
- super("Request aborted");
2551
- this.name = "AbortError";
2552
- }
2553
- };
2554
- var DeletedError = class extends Error {
2555
- constructor() {
2556
- super("Request deleted");
2557
- this.name = "DeletedError";
2558
- }
2559
- };
2560
- var RequestProcessingError = class extends Error {
2561
- constructor(description) {
2562
- super("Request processing error");
2563
- __publicField(this, "description");
2564
- this.description = description;
2565
- this.name = "RequestProcessingError";
2566
- }
2567
- };
2568
- var UnexpectedError = class extends Error {
2569
- constructor(description) {
2570
- super("Unexpected error");
2571
- __publicField(this, "description");
2572
- this.description = description;
2573
- this.name = "UnexpectedError";
2574
- }
2575
- };
2576
- var getErrorMessage = (errorCase) => {
2577
- if (errorCase === "timeout") {
2578
- return new TimeoutError();
2579
- }
2580
- if (errorCase === "abort") {
2581
- return new AbortError();
2582
- }
2583
- if (errorCase === "deleted") {
2584
- return new DeletedError();
2585
- }
2586
- if (errorCase === "processing") {
2587
- return new RequestProcessingError();
2588
- }
2589
- return new UnexpectedError();
2590
- };
2591
- var stringifyValue = (response) => {
2592
- try {
2593
- return JSON.stringify(response);
2594
- } catch (err) {
2595
- return "";
2596
- }
2597
- };
2598
- var getAdapterHeaders = (request) => {
2599
- const isFormData = hasWindow() && request.payload instanceof FormData;
2600
- const isObject = typeof request.payload === "object" && request.payload !== null;
2601
- const headers = {};
2602
- if (!isFormData && isObject) headers["Content-Type"] = "application/json";
2603
- Object.assign(headers, request.headers);
2604
- return headers;
2605
- };
2606
- var getAdapterPayload = (data) => {
2607
- const isFormData = hasWindow() && data instanceof FormData;
2608
- if (isFormData) return data;
2609
- return stringifyValue(data);
2610
- };
2611
-
2612
- // src/adapter/adapter.ts
2613
- var defaultMapper = (value) => value;
2614
- var Adapter = class {
2615
- constructor(options) {
2616
- this.options = options;
2617
- /** Fetching function */
2618
- __publicField(this, "unstable_fetcher");
2619
- /**
2620
- * ********************
2621
- * Defaults
2622
- * ********************
2623
- */
2624
- __publicField(this, "name");
2625
- __publicField(this, "defaultMethod");
2626
- __publicField(this, "defaultExtra");
2627
- __publicField(this, "systemErrorStatus");
2628
- __publicField(this, "systemErrorExtra");
2629
- __publicField(this, "defaultRequestOptions");
2630
- __publicField(this, "logger");
2631
- __publicField(this, "initialized", false);
2632
- __publicField(this, "client");
2633
- __publicField(this, "unstable_onInitializeCallback");
2634
- __publicField(this, "unstable_queryParamsMapperConfig");
2635
- __publicField(this, "unstable_headerMapperConfig");
2636
- __publicField(this, "unstable_payloadMapperConfig");
2637
- __publicField(this, "unstable_endpointMapperConfig");
2638
- __publicField(this, "initialize", (client) => {
2639
- var _a;
2640
- this.logger = client.loggerManager.initialize(client, "Adapter");
2641
- this.initialized = true;
2642
- this.client = client;
2643
- (_a = this.unstable_onInitializeCallback) == null ? void 0 : _a.call(this, { client });
2644
- return this;
2645
- });
2646
- __publicField(this, "onInitialize", (callback) => {
2647
- this.unstable_onInitializeCallback = callback;
2648
- return this;
2649
- });
2650
- /**
2651
- * ********************
2652
- * Options Setters
2653
- * ********************
2654
- */
2655
- __publicField(this, "unstable_internalErrorMapping", (error) => error);
2656
- /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
2657
- __publicField(this, "unstable_headerMapper", getAdapterHeaders);
2658
- /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
2659
- __publicField(this, "unstable_payloadMapper", getAdapterPayload);
2660
- /** Method to get the endpoint for the adapter request. */
2661
- __publicField(this, "unstable_endpointMapper", defaultMapper);
2662
- /** Method to get request data and transform them to the required format. */
2663
- __publicField(this, "unstable_queryParamsMapper", defaultMapper);
2664
- /** Get default adapter options for the request. */
2665
- __publicField(this, "unstable_getAdapterDefaults");
2666
- /** Get default request options for the request. */
2667
- __publicField(this, "unstable_getRequestDefaults");
2668
- /**
2669
- * Get formatted endpoint name of the request.
2670
- * Helpful in displaying long endpoints like in case of graphql schemas etc.
2671
- */
2672
- __publicField(this, "unstable_devtoolsEndpointGetter", (endpoint) => endpoint);
2673
- /**
2674
- * ********************
2675
- * Methods
2676
- * ********************
2677
- */
2678
- __publicField(this, "setDefaultMethod", (method) => {
2679
- this.defaultMethod = method;
2680
- return this;
2681
- });
2682
- __publicField(this, "setDefaultExtra", (extra) => {
2683
- this.defaultExtra = extra;
2684
- return this;
2685
- });
2686
- __publicField(this, "setDevtoolsEndpointGetter", (callback) => {
2687
- this.unstable_devtoolsEndpointGetter = callback;
2688
- return this;
2689
- });
2690
- /**
2691
- * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
2692
- */
2693
- __publicField(this, "setRequestDefaults", (callback) => {
2694
- this.unstable_getRequestDefaults = callback;
2695
- return this;
2696
- });
2697
- /**
2698
- * Set the adapter default options added to every sent request
2699
- */
2700
- __publicField(this, "setAdapterDefaults", (callback) => {
2701
- this.unstable_getAdapterDefaults = callback;
2702
- return this;
2703
- });
2704
- __publicField(this, "setInternalErrorMapping", (callback) => {
2705
- this.unstable_internalErrorMapping = callback;
2706
- return this;
2707
- });
2708
- /**
2709
- * Set the custom header mapping function
2710
- */
2711
- __publicField(this, "setHeaderMapper", (headerMapper) => {
2712
- this.unstable_headerMapper = (req) => headerMapper(req, this.unstable_headerMapperConfig);
2713
- return this;
2714
- });
2715
- /**
2716
- * Set the request payload mapping function which gets triggered before request is send
2717
- */
2718
- __publicField(this, "setPayloadMapper", (payloadMapper) => {
2719
- this.unstable_payloadMapper = (req) => payloadMapper(
2720
- req,
2721
- this.unstable_payloadMapperConfig
2722
- );
2723
- return this;
2724
- });
2725
- /**
2726
- * Set the request payload mapping function which get triggered before request get sent
2727
- */
2728
- __publicField(this, "setEndpointMapper", (endpointMapper) => {
2729
- this.unstable_endpointMapper = (endpoint) => endpointMapper(
2730
- endpoint,
2731
- this.unstable_endpointMapperConfig
2732
- );
2733
- return this;
2734
- });
2735
- /**
2736
- * Set the query params mapping function which get triggered before request get sent
2737
- */
2738
- __publicField(this, "setQueryParamsMapper", (queryParamsMapper) => {
2739
- this.unstable_queryParamsMapper = (queryParams) => queryParamsMapper(
2740
- queryParams,
2741
- this.unstable_queryParamsMapperConfig
2742
- );
2743
- return this;
2744
- });
2745
- __publicField(this, "setQueryParamsMapperConfig", (config) => {
2746
- this.unstable_queryParamsMapperConfig = config;
2747
- return this;
2748
- });
2749
- __publicField(this, "setHeaderMapperConfig", (config) => {
2750
- this.unstable_headerMapperConfig = config;
2751
- return this;
2752
- });
2753
- __publicField(this, "setEndpointMapperConfig", (config) => {
2754
- this.unstable_endpointMapperConfig = config;
2755
- return this;
2756
- });
2757
- __publicField(this, "setPayloadMapperConfig", (config) => {
2758
- this.unstable_payloadMapperConfig = config;
2759
- return this;
2760
- });
2761
- this.name = options.name;
2762
- this.defaultMethod = options.defaultMethod;
2763
- this.defaultExtra = options.defaultExtra;
2764
- this.systemErrorStatus = options.systemErrorStatus;
2765
- this.systemErrorExtra = options.systemErrorExtra;
2766
- this.defaultRequestOptions = options.defaultRequestOptions;
2767
- }
2768
- /**
2769
- * ********************
2770
- * Fetching
2771
- * ********************
2772
- */
2773
- setFetcher(fetcher) {
2774
- this.unstable_fetcher = fetcher.bind(this);
2775
- return this;
2776
- }
2777
- fetch(request, requestId) {
2778
- return __async(this, null, function* () {
2779
- let startTime;
2780
- const execute = (resolve) => __async(this, null, function* () {
2781
- try {
2782
- if (!this.initialized) {
2783
- throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
2784
- }
2785
- if (!this.unstable_fetcher) {
2786
- throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
2787
- }
2788
- this.client.triggerPlugins("onAdapterFetch", {
2789
- adapter: this,
2790
- request,
2791
- requestId
2792
- });
2793
- const bindings = yield getAdapterBindings({
2794
- request,
2795
- requestId,
2796
- resolve,
2797
- internalErrorMapping: this.unstable_internalErrorMapping,
2798
- onStartTime: (time) => {
2799
- startTime = time;
2800
- }
2801
- });
2802
- if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) {
2803
- return mocker(bindings);
2804
- }
2805
- return this.unstable_fetcher(bindings);
2806
- } catch (error) {
2807
- const onError = getAdapterOnError({
2808
- request,
2809
- requestId,
2810
- startTime: startTime || Date.now(),
2811
- logger: this.logger,
2812
- resolve
2813
- });
2814
- return onError({
2815
- error: this.unstable_internalErrorMapping(error),
2816
- status: this.options.systemErrorStatus,
2817
- extra: this.options.systemErrorExtra
2818
- });
2819
- }
2820
- });
2821
- const promise = new Promise((resolve) => {
2822
- execute(resolve);
2823
- });
2824
- return promise;
2825
- });
2826
- }
2827
- };
2828
-
2829
- // src/http-adapter/http-adapter.utils.ts
2830
- var getResponseHeaders = (headersString) => {
2831
- const arr = headersString.trim().split(/[\r\n]+/);
2832
- const headers = {};
2833
- arr.forEach((line) => {
2834
- const parts = line.split(": ");
2835
- const header = parts.shift();
2836
- const value = parts.join(": ");
2837
- if (header) {
2838
- headers[header] = value;
2839
- }
2840
- });
2841
- return headers;
2842
- };
2843
- var parseResponse = (response) => {
2844
- try {
2845
- return JSON.parse(response);
2846
- } catch (err) {
2847
- return response;
2848
- }
2849
- };
2850
- var handleResponse = (responseChunks, responseType, responseEncoding) => {
2851
- const bufferedResponse = Buffer.concat(responseChunks);
2852
- switch (responseType) {
2853
- case "arraybuffer":
2854
- return bufferedResponse;
2855
- case "json":
2856
- return parseResponse(bufferedResponse.toString(responseEncoding));
2857
- default:
2858
- return bufferedResponse.toString(responseEncoding);
2859
- }
2860
- };
2861
- var parseErrorResponse = (response) => {
2862
- return response ? parseResponse(response) : getErrorMessage();
2863
- };
2864
- var isValidValue = (options) => {
2865
- return (value) => {
2866
- const { skipNull, skipEmptyString } = options;
2867
- if (skipEmptyString && value === void 0) {
2868
- return false;
2869
- }
2870
- if (skipEmptyString && value === "") {
2871
- return false;
2872
- }
2873
- if (skipNull && value === null) {
2874
- return false;
2875
- }
2876
- return true;
2877
- };
2878
- };
2879
- var encodeValue = (value, { encode, strict }) => {
2880
- if (encode && strict) {
2881
- return encodeURIComponent(value).replace(/[!'()*]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`);
2882
- }
2883
- if (encode) {
2884
- return encodeURIComponent(value);
2885
- }
2886
- return value;
2887
- };
2888
- var encodeParams = (key, value, options) => {
2889
- const shouldSkip = !isValidValue(options)(value);
2890
- if (!key || shouldSkip) {
2891
- return "";
2892
- }
2893
- const parsedValue = () => {
2894
- var _a, _b;
2895
- if (value instanceof Date) {
2896
- return ((_a = options.dateParser) == null ? void 0 : _a.call(options, value)) || value.toISOString();
2897
- }
2898
- if (typeof value === "object" && !Array.isArray(value)) {
2899
- return ((_b = options.objectParser) == null ? void 0 : _b.call(options, value)) || JSON.stringify(value);
2900
- }
2901
- return String(value);
2902
- };
2903
- return `${encodeValue(key, options)}=${encodeValue(parsedValue(), options)}`;
2904
- };
2905
- var encodeArray = (key, array, options) => {
2906
- const { arrayFormat, arraySeparator } = options;
2907
- return array.filter(isValidValue(options)).reduce((acc, value, index) => {
2908
- switch (arrayFormat) {
2909
- case "index": {
2910
- const keyValue = `${encodeValue(key, options)}[${encodeValue(String(index), options)}]=`;
2911
- acc.push(`${keyValue}${encodeValue(String(value), options)}`);
2912
- break;
2913
- }
2914
- case "bracket": {
2915
- const keyValue = `${encodeValue(key, options)}[]=`;
2916
- acc.push(`${keyValue}${encodeValue(String(value), options)}`);
2917
- break;
2918
- }
2919
- case "comma": {
2920
- const keyValue = !acc.length && `${encodeValue(key, options)}=` || "";
2921
- return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(",")];
2922
- }
2923
- case "separator": {
2924
- const keyValue = !acc.length && `${encodeValue(key, options)}=` || "";
2925
- return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
2926
- }
2927
- case "bracket-separator": {
2928
- const keyValue = !acc.length && `${encodeValue(key, options)}[]=` || "";
2929
- return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
2930
- }
2931
- default: {
2932
- const keyValue = `${encodeValue(key, options)}=`;
2933
- acc.push(`${keyValue}${encodeValue(String(value), options)}`);
2934
- }
2935
- }
2936
- return acc;
2937
- }, []).join("&");
2938
- };
2939
- var stringifyQueryParams = (queryParams, options = stringifyDefaultOptions) => {
2940
- if (!queryParams || !Object.keys(queryParams).length) {
2941
- return "";
2942
- }
2943
- if (typeof queryParams === "string") {
2944
- const hasQuestionMark = queryParams[0] === "?";
2945
- return hasQuestionMark ? queryParams : `?${queryParams}`;
2946
- }
2947
- const stringified = Object.entries(queryParams).map(([key, value]) => {
2948
- if (Array.isArray(value)) {
2949
- return encodeArray(key, value, options);
2950
- }
2951
- return encodeParams(key, value, options);
2952
- }).filter(Boolean).join("&");
2953
- if (stringified) {
2954
- return `?${stringified}`;
2955
- }
2956
- return "";
2957
- };
2958
-
2959
- // src/http-adapter/http-adapter.constants.ts
2960
- var defaultTimeout = 1e3 /* SEC */ * 5;
2961
- var xhrExtra = {
2962
- headers: {}
2963
- };
2964
-
2965
- // src/http-adapter/http-adapter.browser.ts
2966
- var getAdapter = () => new Adapter({
2967
- name: "http-browser",
2968
- defaultMethod: "GET" /* GET */,
2969
- defaultExtra: xhrExtra,
2970
- systemErrorStatus: 0,
2971
- systemErrorExtra: xhrExtra
2972
- }).setQueryParamsMapper(stringifyQueryParams).setFetcher(
2973
- (_0) => __async(null, [_0], function* ({
2974
- request,
2975
- adapterOptions,
2976
- headers,
2977
- payload,
2978
- onError,
2979
- onResponseEnd,
2980
- onTimeoutError,
2981
- onRequestEnd,
2982
- createAbortListener,
2983
- onResponseProgress,
2984
- onResponseStart,
2985
- onBeforeRequest,
2986
- onRequestStart,
2987
- onRequestProgress,
2988
- onSuccess
2989
- }) {
2990
- const { method, client, endpoint, queryParams } = request;
2991
- const queryString = queryParams ? stringifyQueryParams(queryParams) : "";
2992
- const fullUrl = `${client.url}${endpoint}${queryString}`;
2993
- const xhr = new XMLHttpRequest();
2994
- xhr.timeout = defaultTimeout;
2995
- const onAbort = () => xhr.abort();
2996
- if (adapterOptions) {
2997
- Object.entries(adapterOptions).forEach(([name, value]) => {
2998
- xhr[name] = value;
2999
- });
3000
- }
3001
- xhr.open(method, fullUrl, true);
3002
- Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));
3003
- const unmountListener = createAbortListener({ status: 0, extra: xhrExtra, onAbort });
3004
- xhr.upload.onprogress = onRequestProgress;
3005
- xhr.onloadstart = () => {
3006
- onRequestEnd();
3007
- onResponseStart();
3008
- };
3009
- xhr.onprogress = onResponseProgress;
3010
- xhr.onloadend = () => {
3011
- onResponseEnd();
3012
- unmountListener();
3013
- };
3014
- xhr.ontimeout = () => onTimeoutError({ status: 0, extra: xhrExtra });
3015
- xhr.onreadystatechange = (e) => {
3016
- const event = e;
3017
- const finishedState = 4;
3018
- if (event.target && event.target.readyState === finishedState) {
3019
- const { status } = event.target;
3020
- const success = String(status).startsWith("2") || String(status).startsWith("3");
3021
- const responseHeaders = getResponseHeaders(xhr.getAllResponseHeaders());
3022
- if (success) {
3023
- const data = parseResponse(event.target.response);
3024
- onSuccess({ data, status, extra: { headers: responseHeaders } });
3025
- } else {
3026
- const error = parseErrorResponse(event.target.response);
3027
- onError({ error, status, extra: { headers: responseHeaders } });
3028
- }
3029
- }
3030
- };
3031
- onBeforeRequest();
3032
- onRequestStart();
3033
- xhr.send(payload);
3034
- })
3035
- );
3036
-
3037
- // src/http-adapter/http-adapter.server.ts
3038
- var import_http3 = __toESM(require("http"));
3039
- var import_https = __toESM(require("https"));
3040
- var getAdapter2 = () => new Adapter({
3041
- name: "http-server",
3042
- defaultMethod: "GET" /* GET */,
3043
- defaultExtra: xhrExtra,
3044
- systemErrorStatus: 0,
3045
- systemErrorExtra: xhrExtra
3046
- }).setQueryParamsMapper(stringifyQueryParams).setFetcher(
3047
- (_0) => __async(null, [_0], function* ({
3048
- request,
3049
- adapterOptions,
3050
- adapter,
3051
- headers,
3052
- payload,
3053
- onError,
3054
- onResponseEnd,
3055
- onTimeoutError,
3056
- onRequestEnd,
3057
- createAbortListener,
3058
- getAbortController,
3059
- onResponseProgress,
3060
- onResponseStart,
3061
- onBeforeRequest,
3062
- onRequestStart,
3063
- onSuccess
3064
- }) {
3065
- var _a;
3066
- const { method, client, endpoint, queryParams } = request;
3067
- const { url } = client;
3068
- const httpClient = client.url.includes("https://") ? import_https.default : import_http3.default;
3069
- const options = {
3070
- method,
3071
- headers,
3072
- timeout: defaultTimeout,
3073
- signal: (_a = getAbortController()) == null ? void 0 : _a.signal
3074
- };
3075
- if (adapterOptions) {
3076
- Object.entries(adapterOptions).forEach(([name, value]) => {
3077
- options[name] = value;
3078
- });
3079
- }
3080
- onBeforeRequest();
3081
- if (payload) {
3082
- const payloadAsAny = payload;
3083
- const isString = typeof payloadAsAny === "string";
3084
- const isBuffer = Buffer.isBuffer(payloadAsAny);
3085
- let contentLength;
3086
- if (isString) {
3087
- contentLength = Buffer.byteLength(payloadAsAny);
3088
- } else if (isBuffer) {
3089
- contentLength = payloadAsAny.length;
3090
- } else {
3091
- contentLength = Buffer.byteLength(JSON.stringify(payloadAsAny));
3092
- }
3093
- options.headers["Content-Length"] = contentLength;
3094
- }
3095
- const queryString = queryParams ? stringifyQueryParams(queryParams) : "";
3096
- const fullUrl = `${url}${endpoint}${queryString}`;
3097
- const unmountListener = createAbortListener({
3098
- status: 0,
3099
- extra: xhrExtra
3100
- });
3101
- const httpRequest = httpClient.request(fullUrl, options, (response) => {
3102
- response.setEncoding("utf8");
3103
- onRequestStart();
3104
- let chunks = "";
3105
- const totalDownloadBytes = Number(response.headers["content-length"]);
3106
- let downloadedBytes = 0;
3107
- response.on("data", (chunk) => {
3108
- if (!chunks) {
3109
- onRequestEnd();
3110
- onResponseStart();
3111
- }
3112
- downloadedBytes += chunk.length;
3113
- chunks += chunk;
3114
- onResponseProgress({ total: totalDownloadBytes, loaded: downloadedBytes });
3115
- });
3116
- response.on("end", () => __async(null, null, function* () {
3117
- const { statusCode = adapter.systemErrorStatus } = response;
3118
- const success = String(statusCode).startsWith("2") || String(statusCode).startsWith("3");
3119
- if (success) {
3120
- const data = parseResponse(chunks);
3121
- onSuccess({
3122
- data,
3123
- status: statusCode,
3124
- extra: { headers: response.headers }
3125
- });
3126
- } else {
3127
- const data = parseErrorResponse(chunks);
3128
- onError({
3129
- error: data,
3130
- status: statusCode,
3131
- extra: { headers: response.headers }
3132
- });
3133
- }
3134
- unmountListener();
3135
- onResponseEnd();
3136
- }));
3137
- });
3138
- httpRequest.on("timeout", () => onTimeoutError({ status: 0, extra: xhrExtra }));
3139
- httpRequest.on("error", (error) => onError({ error, status: 0, extra: xhrExtra }));
3140
- if (payload) {
3141
- httpRequest.write(payload);
3142
- }
3143
- httpRequest.end();
3144
- })
3145
- );
3146
-
3147
- // src/http-adapter/http-adapter.ts
3148
- var HttpAdapter = () => {
3149
- if (typeof XMLHttpRequest !== "undefined") {
3150
- return getAdapter();
3151
- }
3152
- return getAdapter2();
3153
- };
3154
-
3155
- // src/cache/cache.ts
3156
- var Cache = class {
3157
- constructor(options) {
3158
- this.options = options;
3159
- __publicField(this, "emitter", new EventEmitter());
3160
- __publicField(this, "events");
3161
- __publicField(this, "storage");
3162
- __publicField(this, "lazyStorage");
3163
- __publicField(this, "version");
3164
- __publicField(this, "garbageCollectors", /* @__PURE__ */ new Map());
3165
- __publicField(this, "logger");
3166
- __publicField(this, "client");
3167
- __publicField(this, "initialize", (client) => {
3168
- this.client = client;
3169
- this.logger = client.loggerManager.initialize(client, "Cache");
3170
- client.appManager.events.onOnline(() => {
3171
- [...this.storage.keys()].forEach(this.scheduleGarbageCollector);
3172
- });
3173
- [...this.storage.keys()].forEach(this.scheduleGarbageCollector);
3174
- return this;
3175
- });
3176
- /**
3177
- * Set the cache data to the storage
3178
- * @param request
3179
- * @param response
3180
- * @returns
3181
- */
3182
- __publicField(this, "set", (request, response) => {
3183
- var _a;
3184
- this.logger.debug({ title: "Processing cache response", type: "system", extra: { request, response } });
3185
- const { cacheKey, cache, staleTime, cacheTime } = request;
3186
- const previousCacheData = this.storage.get(cacheKey);
3187
- const processedResponse = typeof response === "function" ? response(previousCacheData || null) : response;
3188
- const data = getCacheData(previousCacheData, processedResponse);
3189
- const newCacheData = __spreadProps(__spreadValues({}, data), {
3190
- staleTime,
3191
- version: this.version,
3192
- cacheKey,
3193
- cacheTime,
3194
- cached: !!request.cache
3195
- });
3196
- if (processedResponse.success && cache) {
3197
- this.logger.debug({ title: "Saving response to cache storage", type: "system", extra: { request, data } });
3198
- this.storage.set(cacheKey, newCacheData);
3199
- (_a = this.lazyStorage) == null ? void 0 : _a.set(cacheKey, newCacheData);
3200
- this.client.triggerPlugins("onCacheItemChange", {
3201
- cache: this,
3202
- cacheKey,
3203
- prevData: previousCacheData || null,
3204
- newData: newCacheData
3205
- });
3206
- this.scheduleGarbageCollector(cacheKey);
3207
- } else {
3208
- this.logger.debug({ title: "Prevented saving response to cache", type: "system", extra: { request, data } });
3209
- }
3210
- this.logger.debug({ title: "Emitting cache response", type: "system", extra: { request, data } });
3211
- this.events.emitCacheData(
3212
- newCacheData
3213
- );
3214
- });
3215
- /**
3216
- * Update the cache data with partial response data
3217
- * @param request
3218
- * @param partialResponse
3219
- * @param isTriggeredExtrenally - informs whether an update was triggered due to internal logic or externally, e.g.
3220
- * via plugin.
3221
- * @returns
3222
- */
3223
- __publicField(this, "update", (request, partialResponse) => {
3224
- this.logger.debug({ title: "Processing cache update", type: "system", extra: { request, partialResponse } });
3225
- const { cacheKey } = request;
3226
- const cachedData = this.storage.get(cacheKey);
3227
- const processedResponse = typeof partialResponse === "function" ? partialResponse(cachedData || null) : partialResponse;
3228
- if (cachedData) {
3229
- this.set(request, __spreadValues(__spreadValues({}, cachedData), processedResponse));
3230
- }
3231
- });
3232
- /**
3233
- * Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.
3234
- * @param cacheKey
3235
- * @returns
3236
- */
3237
- __publicField(this, "get", (cacheKey) => {
3238
- this.getLazyResource(cacheKey);
3239
- const cachedData = this.storage.get(cacheKey);
3240
- return cachedData;
3241
- });
3242
- /**
3243
- * Get sync storage keys, lazyStorage keys will not be included
3244
- * @returns
3245
- */
3246
- __publicField(this, "keys", () => {
3247
- const values = this.storage.keys();
3248
- return Array.from(values);
3249
- });
3250
- /**
3251
- * Delete record from storages and trigger invalidation event
3252
- * @param cacheKey
3253
- */
3254
- __publicField(this, "delete", (cacheKey) => {
3255
- var _a;
3256
- this.logger.debug({ title: "Deleting cache element", type: "system", extra: { cacheKey } });
3257
- this.storage.delete(cacheKey);
3258
- (_a = this.lazyStorage) == null ? void 0 : _a.delete(cacheKey);
3259
- this.client.triggerPlugins("onCacheItemDelete", {
3260
- cache: this,
3261
- cacheKey
3262
- });
3263
- this.events.emitDelete(cacheKey);
3264
- });
3265
- /**
3266
- * Invalidate cache by cacheKey or partial matching with RegExp
3267
- * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache
3268
- * @param key - cacheKey or Request instance or RegExp for partial matching
3269
- */
3270
- __publicField(this, "invalidate", (cacheKeys) => {
3271
- this.logger.debug({ title: "Revalidating cache element", type: "system", extra: { cacheKeys } });
3272
- const onInvalidate = (key) => {
3273
- const keys = Array.from(this.storage.keys());
3274
- const handleInvalidation = (cacheKey) => {
3275
- const value = this.storage.get(cacheKey);
3276
- if (value) {
3277
- this.storage.set(cacheKey, __spreadProps(__spreadValues({}, value), { staleTime: 0 }));
3278
- }
3279
- this.client.triggerPlugins("onCacheItemInvalidate", {
3280
- cache: this,
3281
- cacheKey
3282
- });
3283
- this.events.emitInvalidation(cacheKey);
3284
- };
3285
- if (key instanceof Request) {
3286
- handleInvalidation(key.cacheKey);
3287
- } else if (typeof key === "string") {
3288
- handleInvalidation(key);
3289
- } else if (keys.length) {
3290
- keys.forEach((entityKey) => {
3291
- if (key.test(entityKey)) {
3292
- handleInvalidation(entityKey);
3293
- }
3294
- });
3295
- }
3296
- };
3297
- if (Array.isArray(cacheKeys)) {
3298
- cacheKeys.forEach(onInvalidate.bind(this));
3299
- } else {
3300
- onInvalidate.bind(this)(cacheKeys);
3301
- }
3302
- });
3303
- /**
3304
- * Used to receive data from lazy storage
3305
- * @param cacheKey
3306
- */
3307
- __publicField(this, "getLazyResource", (cacheKey) => __async(this, null, function* () {
3308
- var _a, _b;
3309
- const data = yield (_a = this.lazyStorage) == null ? void 0 : _a.get(cacheKey);
3310
- const syncData = this.storage.get(cacheKey);
3311
- const hasLazyData = this.lazyStorage && data;
3312
- if (hasLazyData) {
3313
- const now = +/* @__PURE__ */ new Date();
3314
- const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;
3315
- const isStaleData = data.staleTime <= now - data.responseTimestamp;
3316
- const isValidLazyData = data.version === this.version;
3317
- if (!isValidLazyData) {
3318
- (_b = this.lazyStorage) == null ? void 0 : _b.delete(cacheKey);
3319
- }
3320
- if (isNewestData && !isStaleData && isValidLazyData) {
3321
- this.storage.set(cacheKey, data);
3322
- this.events.emitCacheData(__spreadProps(__spreadValues({}, data), { cacheKey, cached: true }));
3323
- return data;
3324
- }
3325
- }
3326
- const isValidData = (syncData == null ? void 0 : syncData.version) === this.version;
3327
- if (syncData && !isValidData) {
3328
- this.delete(cacheKey);
3329
- }
3330
- return syncData;
3331
- }));
3332
- /**
3333
- * Used to receive keys from sync storage and lazy storage
3334
- * @param cacheKey
3335
- */
3336
- __publicField(this, "getLazyKeys", () => __async(this, null, function* () {
3337
- var _a;
3338
- const keys = (yield (_a = this.lazyStorage) == null ? void 0 : _a.keys()) || [];
3339
- return [...new Set(keys)];
3340
- }));
3341
- /**
3342
- * Used to receive keys from sync storage and lazy storage
3343
- * @param cacheKey
3344
- */
3345
- __publicField(this, "getAllKeys", () => __async(this, null, function* () {
3346
- var _a;
3347
- const keys = yield (_a = this.lazyStorage) == null ? void 0 : _a.keys();
3348
- const asyncKeys = Array.from(keys || []);
3349
- const syncKeys = Array.from(this.storage.keys());
3350
- return [.../* @__PURE__ */ new Set([...asyncKeys, ...syncKeys])];
3351
- }));
3352
- /**
3353
- * Schedule garbage collection for given key
3354
- * @param cacheKey
3355
- * @returns
3356
- */
3357
- __publicField(this, "scheduleGarbageCollector", (cacheKey) => {
3358
- const cacheData = this.storage.get(cacheKey);
3359
- clearTimeout(this.garbageCollectors.get(cacheKey));
3360
- if (cacheData) {
3361
- const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - +/* @__PURE__ */ new Date();
3362
- if (cacheData.cacheTime === null) {
3363
- this.logger.debug({ title: "Cache time is null", type: "system", extra: { cacheKey } });
3364
- } else if (cacheData.cacheTime !== null && JSON.stringify(cacheData.cacheTime) === "null" || cacheData.cacheTime === Infinity) {
3365
- this.logger.debug({ title: "Cache time is Infinite", type: "system", extra: { cacheKey } });
3366
- } else if (timeLeft >= 0) {
3367
- this.garbageCollectors.set(
3368
- cacheKey,
3369
- setTimeout(() => {
3370
- if (this.client.appManager.isOnline) {
3371
- this.logger.info({ title: "Garbage collecting cache data", type: "system", extra: { cacheKey } });
3372
- this.delete(cacheKey);
3373
- }
3374
- }, timeLeft)
3375
- );
3376
- } else if (this.client.appManager.isOnline) {
3377
- this.logger.info({ title: "Garbage collecting cache data", type: "system", extra: { cacheKey } });
3378
- this.delete(cacheKey);
3379
- }
3380
- }
3381
- });
3382
- /**
3383
- * Clear cache storages
3384
- */
3385
- __publicField(this, "clear", () => __async(this, null, function* () {
3386
- this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));
3387
- this.storage.clear();
3388
- }));
3389
- var _a;
3390
- const { storage = /* @__PURE__ */ new Map(), lazyStorage, version = "0.0.1" } = options != null ? options : {};
3391
- (_a = this.emitter) == null ? void 0 : _a.setMaxListeners(1e3);
3392
- this.events = getCacheEvents(this.emitter);
3393
- this.storage = storage;
3394
- this.version = version;
3395
- this.lazyStorage = lazyStorage;
3396
- }
3397
- };
3398
-
3399
- // src/cache/cache.utils.ts
3400
- var getCacheData = (previousResponse, response) => {
3401
- const { data, success } = response;
3402
- const previousData = !success && previousResponse ? previousResponse.data : null;
3403
- const computedData = data || previousData;
3404
- return __spreadProps(__spreadValues({}, response), { data: computedData });
3405
- };
3406
- var getInvalidateKey = () => {
3407
- return `invalidate`;
3408
- };
3409
- var getInvalidateByKey = (key) => {
3410
- return `${key}_invalidate`;
3411
- };
3412
- var getDeleteKey = () => {
3413
- return `delete`;
3414
- };
3415
- var getDeleteByKey = (key) => {
3416
- return `${key}_delete`;
3417
- };
3418
- var getCacheByKey = (key) => {
3419
- return `${key}_cache`;
3420
- };
3421
- var getCacheKey = () => {
3422
- return `cache`;
3423
- };
3424
-
3425
- // src/cache/cache.events.ts
3426
- var getCacheEvents = (emitter) => ({
3427
- /**
3428
- * Set cache data
3429
- * @param data
3430
- */
3431
- emitCacheData: (data, isTriggeredExternally = false) => {
3432
- emitter.emit(getCacheKey(), data, isTriggeredExternally);
3433
- emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);
3434
- },
3435
- /**
3436
- * Invalidate cache values event
3437
- */
3438
- emitInvalidation: (cacheKey, isTriggeredExternally = false) => {
3439
- emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);
3440
- emitter.emit(getInvalidateByKey(cacheKey), isTriggeredExternally);
3441
- },
3442
- /**
3443
- * Delete of cache values
3444
- */
3445
- emitDelete: (cacheKey, isTriggeredExternally = false) => {
3446
- emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);
3447
- emitter.emit(getDeleteByKey(cacheKey), isTriggeredExternally);
3448
- },
3449
- /**
3450
- * Cache data listener
3451
- * @param callback
3452
- * @returns
3453
- */
3454
- onData: (callback) => {
3455
- emitter.on(getCacheKey(), callback);
3456
- return () => emitter.removeListener(getCacheKey(), callback);
3457
- },
3458
- /**
3459
- * Cache data listener
3460
- * @param cacheKey
3461
- * @param callback
3462
- * @returns
3463
- */
3464
- onDataByKey: (cacheKey, callback) => {
3465
- emitter.on(getCacheByKey(cacheKey), callback);
3466
- return () => emitter.removeListener(getCacheByKey(cacheKey), callback);
3467
- },
3468
- /**
3469
- * Cache invalidation listener
3470
- * @param callback
3471
- * @returns
3472
- */
3473
- onInvalidate: (callback) => {
3474
- emitter.on(getInvalidateKey(), callback);
3475
- return () => emitter.removeListener(getInvalidateKey(), callback);
3476
- },
3477
- /**
3478
- * Cache invalidation listener
3479
- * @param cacheKey
3480
- * @param callback
3481
- * @returns
3482
- */
3483
- onInvalidateByKey: (cacheKey, callback) => {
3484
- emitter.on(getInvalidateByKey(cacheKey), callback);
3485
- return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);
3486
- },
3487
- onDelete: (callback) => {
3488
- emitter.on(getDeleteKey(), callback);
3489
- return () => emitter.removeListener(getDeleteKey(), callback);
3490
- },
3491
- onDeleteByKey: (cacheKey, callback) => {
3492
- emitter.on(getDeleteByKey(cacheKey), callback);
3493
- return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);
3494
- }
3495
- });
3496
-
3497
- // src/client/client.utils.ts
3498
- var interceptRequest = (interceptors, request) => __async(null, null, function* () {
3499
- let newRequest = request;
3500
- if (!request.requestOptions.disableRequestInterceptors) {
3501
- for (const interceptor of interceptors) {
3502
- newRequest = yield interceptor(request);
3503
- if (!newRequest) throw new Error("Request modifier must return request");
3504
- }
3505
- }
3506
- return newRequest;
3507
- });
3508
- var interceptResponse = (interceptors, response, request) => __async(null, null, function* () {
3509
- let newResponse = response;
3510
- if (!request.requestOptions.disableResponseInterceptors) {
3511
- for (const interceptor of interceptors) {
3512
- newResponse = yield interceptor(response, request);
3513
- if (!newResponse) throw new Error("Response modifier must return data");
3514
- }
3515
- }
3516
- return newResponse;
3517
- });
3518
-
3519
- // src/client/client.ts
3520
- var Client = class {
3521
- constructor(options) {
3522
- this.options = options;
3523
- __publicField(this, "url");
3524
- __publicField(this, "debug");
3525
- // Private
3526
- __publicField(this, "unstable_onErrorCallbacks", []);
3527
- __publicField(this, "unstable_onSuccessCallbacks", []);
3528
- __publicField(this, "unstable_onResponseCallbacks", []);
3529
- __publicField(this, "unstable_onAuthCallbacks", []);
3530
- __publicField(this, "unstable_onRequestCallbacks", []);
3531
- // Managers
3532
- __publicField(this, "loggerManager", new LoggerManager());
3533
- __publicField(this, "requestManager", new RequestManager());
3534
- __publicField(this, "appManager");
3535
- // Config
3536
- __publicField(this, "adapter");
3537
- __publicField(this, "cache");
3538
- __publicField(this, "fetchDispatcher");
3539
- __publicField(this, "submitDispatcher");
3540
- __publicField(this, "isMockerEnabled", true);
3541
- // Registered requests effect
3542
- __publicField(this, "plugins", []);
3543
- /** @internal */
3544
- __publicField(this, "unstable_abortKeyMapper", getSimpleKey);
3545
- /** @internal */
3546
- __publicField(this, "unstable_cacheKeyMapper", getRequestKey);
3547
- /** @internal */
3548
- __publicField(this, "unstable_queryKeyMapper", getRequestKey);
3549
- /** @internal */
3550
- __publicField(this, "unstable_requestIdMapper", getUniqueRequestId);
3551
- // Logger
3552
- __publicField(this, "logger", this.loggerManager.initialize(this, "Client"));
3553
- /**
3554
- * This method enables the logger usage and display the logs in console
3555
- */
3556
- __publicField(this, "setDebug", (enabled) => {
3557
- this.debug = enabled;
3558
- return this;
3559
- });
3560
- /**
3561
- * Set the logger severity of the messages displayed to the console
3562
- */
3563
- __publicField(this, "setLogLevel", (severity) => {
3564
- this.loggerManager.setSeverity(severity);
3565
- return this;
3566
- });
3567
- /**
3568
- * Set the new logger instance to the Client
3569
- */
3570
- __publicField(this, "setLogger", (callback) => {
3571
- this.loggerManager = callback(this);
3572
- this.loggerManager.initialize(this, "Client");
3573
- return this;
3574
- });
3575
- /**
3576
- * Set globally if mocking should be enabled or disabled for all client requests.
3577
- * @param isMockerEnabled
3578
- */
3579
- __publicField(this, "setEnableGlobalMocking", (isMockerEnabled) => {
3580
- this.isMockerEnabled = isMockerEnabled;
3581
- return this;
3582
- });
3583
- /**
3584
- * Set custom http adapter to handle graphql, rest, firebase or others
3585
- */
3586
- __publicField(this, "setAdapter", (adapter) => {
3587
- this.adapter = adapter;
3588
- this.adapter.initialize(this);
3589
- return this;
3590
- });
3591
- /**
3592
- * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.
3593
- */
3594
- __publicField(this, "onAuth", (callback) => {
3595
- this.unstable_onAuthCallbacks.push(callback);
3596
- return this;
3597
- });
3598
- /**
3599
- * Method for removing listeners on auth.
3600
- * */
3601
- __publicField(this, "removeOnAuthInterceptors", (callbacks) => {
3602
- this.unstable_onAuthCallbacks = this.unstable_onAuthCallbacks.filter((callback) => !callbacks.includes(callback));
3603
- return this;
3604
- });
3605
- /**
3606
- * Method for intercepting error responses. It can be used for example to refresh tokens.
3607
- */
3608
- __publicField(this, "onError", (callback) => {
3609
- this.unstable_onErrorCallbacks.push(callback);
3610
- return this;
3611
- });
3612
- /**
3613
- * Method for removing listeners on error.
3614
- * */
3615
- __publicField(this, "removeOnErrorInterceptors", (callbacks) => {
3616
- this.unstable_onErrorCallbacks = this.unstable_onErrorCallbacks.filter((callback) => !callbacks.includes(callback));
3617
- return this;
3618
- });
3619
- /**
3620
- * Method for intercepting success responses.
3621
- */
3622
- __publicField(this, "onSuccess", (callback) => {
3623
- this.unstable_onSuccessCallbacks.push(callback);
3624
- return this;
3625
- });
3626
- /**
3627
- * Method for removing listeners on success.
3628
- * */
3629
- __publicField(this, "removeOnSuccessInterceptors", (callbacks) => {
3630
- this.unstable_onSuccessCallbacks = this.unstable_onSuccessCallbacks.filter(
3631
- (callback) => !callbacks.includes(callback)
3632
- );
3633
- return this;
3634
- });
3635
- /**
3636
- * Method of manipulating requests before sending the request.
3637
- */
3638
- __publicField(this, "onRequest", (callback) => {
3639
- this.unstable_onRequestCallbacks.push(callback);
3640
- return this;
3641
- });
3642
- /**
3643
- * Method for removing listeners on request.
3644
- * */
3645
- __publicField(this, "removeOnRequestInterceptors", (callbacks) => {
3646
- this.unstable_onRequestCallbacks = this.unstable_onRequestCallbacks.filter(
3647
- (callback) => !callbacks.includes(callback)
3648
- );
3649
- return this;
3650
- });
3651
- /**
3652
- * Method for intercepting any responses.
3653
- */
3654
- __publicField(this, "onResponse", (callback) => {
3655
- this.unstable_onResponseCallbacks.push(callback);
3656
- return this;
3657
- });
3658
- /**
3659
- * Method for removing listeners on request.
3660
- * */
3661
- __publicField(this, "removeOnResponseInterceptors", (callbacks) => {
3662
- this.unstable_onResponseCallbacks = this.unstable_onResponseCallbacks.filter(
3663
- (callback) => !callbacks.includes(callback)
3664
- );
3665
- return this;
3666
- });
3667
- /**
3668
- * Add persistent plugins which trigger on the request lifecycle
3669
- */
3670
- __publicField(this, "addPlugin", (plugin) => {
3671
- this.plugins.push(plugin);
3672
- plugin.initialize(this);
3673
- plugin.trigger("onMount", { client: this });
3674
- return this;
3675
- });
3676
- /**
3677
- * Remove plugins from Client
3678
- */
3679
- __publicField(this, "removePlugin", (plugin) => {
3680
- const pluginCount = this.plugins.length;
3681
- this.plugins = this.plugins.filter((p) => p !== plugin);
3682
- if (this.plugins.length !== pluginCount) {
3683
- plugin.trigger("onUnmount", { client: this });
3684
- }
3685
- return this;
3686
- });
3687
- __publicField(this, "triggerPlugins", (key, data) => {
3688
- if (!this.plugins.length) {
3689
- return this;
3690
- }
3691
- this.plugins.forEach((plugin) => {
3692
- plugin.trigger(key, data);
3693
- });
3694
- return this;
3695
- });
3696
- /**
3697
- * Key setters
3698
- */
3699
- __publicField(this, "setAbortKeyMapper", (callback) => {
3700
- this.unstable_abortKeyMapper = callback;
3701
- return this;
3702
- });
3703
- __publicField(this, "setCacheKeyMapper", (callback) => {
3704
- this.unstable_cacheKeyMapper = callback;
3705
- return this;
3706
- });
3707
- __publicField(this, "setQueryKeyMapper", (callback) => {
3708
- this.unstable_queryKeyMapper = callback;
3709
- return this;
3710
- });
3711
- __publicField(this, "setRequestIdMapper", (callback) => {
3712
- this.unstable_requestIdMapper = callback;
3713
- return this;
3714
- });
3715
- /**
3716
- * Helper used by http adapter to apply the modifications on response error
3717
- * @private
3718
- */
3719
- __publicField(this, "unstable_modifyAuth", (request) => __async(this, null, function* () {
3720
- return interceptRequest(this.unstable_onAuthCallbacks, request);
3721
- }));
3722
- /**
3723
- * Private helper to run async pre-request processing
3724
- * @private
3725
- */
3726
- __publicField(this, "unstable_modifyRequest", (request) => __async(this, null, function* () {
3727
- return interceptRequest(this.unstable_onRequestCallbacks, request);
3728
- }));
3729
- /**
3730
- * Private helper to run async on-error response processing
3731
- * @private
3732
- */
3733
- __publicField(this, "unstable_modifyErrorResponse", (response, request) => __async(this, null, function* () {
3734
- return interceptResponse(this.unstable_onErrorCallbacks, response, request);
3735
- }));
3736
- /**
3737
- * Private helper to run async on-success response processing
3738
- * @private
3739
- */
3740
- __publicField(this, "unstable_modifySuccessResponse", (response, request) => __async(this, null, function* () {
3741
- return interceptResponse(this.unstable_onSuccessCallbacks, response, request);
3742
- }));
3743
- /**
3744
- * Private helper to run async response processing
3745
- * @private
3746
- */
3747
- __publicField(this, "unstable_modifyResponse", (response, request) => __async(this, null, function* () {
3748
- return interceptResponse(this.unstable_onResponseCallbacks, response, request);
3749
- }));
3750
- /**
3751
- * Clears the Client instance and remove all listeners on it's dependencies
3752
- */
3753
- __publicField(this, "clear", () => {
3754
- const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
3755
- this.requestManager.abortControllers.clear();
3756
- this.fetchDispatcher.clear();
3757
- this.submitDispatcher.clear();
3758
- this.cache.clear();
3759
- this.requestManager.emitter.removeAllListeners();
3760
- this.fetchDispatcher.emitter.removeAllListeners();
3761
- this.submitDispatcher.emitter.removeAllListeners();
3762
- this.cache.emitter.removeAllListeners();
3763
- this.cache = (cache == null ? void 0 : cache()) || new Cache();
3764
- this.appManager = (appManager == null ? void 0 : appManager()) || new AppManager();
3765
- this.fetchDispatcher = (fetchDispatcher == null ? void 0 : fetchDispatcher()) || new Dispatcher();
3766
- this.submitDispatcher = (submitDispatcher == null ? void 0 : submitDispatcher()) || new Dispatcher();
3767
- this.appManager.initialize();
3768
- this.cache.initialize(this);
3769
- this.fetchDispatcher.initialize(this);
3770
- this.submitDispatcher.initialize(this);
3771
- });
3772
- /**
3773
- * Hydrate your SSR cache data
3774
- * @param hydrationData
3775
- * @param options
3776
- */
3777
- __publicField(this, "hydrate", (hydrationData, options) => {
3778
- hydrationData == null ? void 0 : hydrationData.forEach((item) => {
3779
- if (!item) return;
3780
- const _a = item, { cacheKey, response } = _a, fallbackOptions = __objRest(_a, ["cacheKey", "response"]);
3781
- const defaults = {
3782
- cache: true,
3783
- override: true
3784
- };
3785
- const config = typeof options === "function" ? __spreadValues(__spreadValues(__spreadValues({}, defaults), fallbackOptions), options(item)) : __spreadValues(__spreadValues(__spreadValues({}, defaults), fallbackOptions), options);
3786
- if (!config.override) {
3787
- const cachedData = this.cache.get(cacheKey);
3788
- if (cachedData) {
3789
- return;
3790
- }
3791
- }
3792
- const parsedData = parseResponse(response);
3793
- this.cache.set(__spreadProps(__spreadValues({}, config), { cacheKey }), parsedData);
3794
- });
3795
- });
3796
- /**
3797
- * Create requests based on the Client setup
3798
- *
3799
- * @template Response Your response
3800
- */
3801
- __publicField(this, "createRequest", (_USE_DOUBLE_INITIALIZATION) => {
3802
- return (params) => {
3803
- const endpoint = this.adapter.unstable_endpointMapper(params.endpoint);
3804
- const mappedParams = __spreadProps(__spreadValues({}, params), {
3805
- endpoint: String(endpoint)
3806
- });
3807
- const request = new Request(this, mappedParams);
3808
- this.plugins.forEach((plugin) => plugin.trigger("onRequestCreate", { request }));
3809
- return request;
3810
- };
3811
- });
3812
- const { url, appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
3813
- this.url = url;
3814
- this.adapter = HttpAdapter();
3815
- this.appManager = (appManager == null ? void 0 : appManager()) || new AppManager();
3816
- this.cache = (cache == null ? void 0 : cache()) || new Cache();
3817
- this.fetchDispatcher = (fetchDispatcher == null ? void 0 : fetchDispatcher()) || new Dispatcher();
3818
- this.submitDispatcher = (submitDispatcher == null ? void 0 : submitDispatcher()) || new Dispatcher();
3819
- this.adapter.initialize(this);
3820
- this.appManager.initialize();
3821
- this.cache.initialize(this);
3822
- this.fetchDispatcher.initialize(this);
3823
- this.submitDispatcher.initialize(this);
3824
- }
3825
- };
3826
-
3827
- // src/client/client.constants.ts
3828
- var stringifyDefaultOptions = {
3829
- strict: true,
3830
- encode: true,
3831
- arrayFormat: "bracket",
3832
- arraySeparator: "bracket",
3833
- sort: false,
3834
- skipNull: true,
3835
- skipEmptyString: true
3836
- };
3837
-
3838
- // src/client/client.create.ts
3839
- function createClient(options) {
3840
- return new Client(options);
3841
- }
3842
-
3843
- // src/sdk/sdk.ts
3844
- var getMethod = (key, options) => {
3845
- const { methodTransform = (method) => method.toUpperCase() } = options != null ? options : {};
3846
- return methodTransform(key);
3847
- };
3848
- var createRecursiveProxy = (client, path, options) => {
3849
- return new Proxy(() => {
3850
- }, {
3851
- get: (_target, key) => {
3852
- if (typeof key === "symbol" || key === "inspect") {
3853
- return void 0;
3854
- }
3855
- let isMethod = false;
3856
- let methodName = key;
3857
- let pathSegment = key;
3858
- if (key.startsWith("$")) {
3859
- isMethod = true;
3860
- methodName = key.slice(1);
3861
- pathSegment = `:${key.slice(1)}`;
3862
- } else if (options == null ? void 0 : options.camelCaseToKebabCase) {
3863
- pathSegment = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
3864
- }
3865
- const endpoint = `/${path.join("/")}`;
3866
- const method = getMethod(isMethod ? methodName : key, options);
3867
- const request = client.createRequest()({ endpoint, method });
3868
- const newPath = [...path, pathSegment];
3869
- const deeperProxy = createRecursiveProxy(client, newPath, options);
3870
- return new Proxy(request, {
3871
- get: (reqTarget, reqKey) => {
3872
- if (reqKey in reqTarget) {
3873
- return reqTarget[reqKey];
3874
- }
3875
- return deeperProxy[reqKey];
3876
- }
3877
- });
3878
- }
3879
- });
3880
- };
3881
- var createSdk = (client, options) => {
3882
- const _a = options != null ? options : {}, {
3883
- camelCaseToKebabCase = true,
3884
- methodTransform = (method) => method.toUpperCase()
3885
- } = _a, rest = __objRest(_a, [
3886
- "camelCaseToKebabCase",
3887
- "methodTransform"
3888
- ]);
3889
- return createRecursiveProxy(client, [], __spreadValues({ camelCaseToKebabCase, methodTransform }, rest));
3890
- };
3891
- // Annotate the CommonJS export names for ESM import in node:
3892
- 0 && (module.exports = {
3893
- AbortError,
3894
- Adapter,
3895
- AppEvents,
3896
- AppManager,
3897
- Cache,
3898
- Client,
3899
- DeletedError,
3900
- Dispatcher,
3901
- DispatcherMode,
3902
- EventEmitter,
3903
- HttpAdapter,
3904
- HttpMethods,
3905
- LoggerManager,
3906
- Plugin,
3907
- Request,
3908
- RequestManager,
3909
- RequestProcessingError,
3910
- Time,
3911
- TimeoutError,
3912
- UnexpectedError,
3913
- appManagerInitialOptions,
3914
- canRetryRequest,
3915
- createClient,
3916
- createSdk,
3917
- defaultMapper,
3918
- defaultTimeout,
3919
- getAbortByAbortKey,
3920
- getAbortByIdKey,
3921
- getAbortKey,
3922
- getAdapterBindings,
3923
- getAdapterHeaders,
3924
- getAdapterOnError,
3925
- getAdapterPayload,
3926
- getAppManagerEvents,
3927
- getCacheByKey,
3928
- getCacheData,
3929
- getCacheEvents,
3930
- getCacheKey,
3931
- getDeleteByKey,
3932
- getDeleteKey,
3933
- getDispatcherChangeByKey,
3934
- getDispatcherChangeKey,
3935
- getDispatcherDrainedByKey,
3936
- getDispatcherDrainedKey,
3937
- getDispatcherEvents,
3938
- getDispatcherStatusByKey,
3939
- getDispatcherStatusKey,
3940
- getDownloadProgressByIdKey,
3941
- getDownloadProgressByQueryKey,
3942
- getDownloadProgressKey,
3943
- getErrorMessage,
3944
- getInvalidateByKey,
3945
- getInvalidateKey,
3946
- getIsEqualTimestamp,
3947
- getLoadingByCacheKey,
3948
- getLoadingByIdKey,
3949
- getLoadingByQueryKey,
3950
- getLoadingKey,
3951
- getProgressData,
3952
- getProgressValue,
3953
- getRemoveByIdKey,
3954
- getRemoveByQueryKey,
3955
- getRemoveKey,
3956
- getRequestDeduplicatedByCacheKey,
3957
- getRequestDeduplicatedByIdKey,
3958
- getRequestDeduplicatedByQueryKey,
3959
- getRequestDeduplicatedKey,
3960
- getRequestDispatcher,
3961
- getRequestEta,
3962
- getRequestKey,
3963
- getRequestManagerEvents,
3964
- getRequestStarByQueryKey,
3965
- getRequestStartByIdKey,
3966
- getRequestStartKey,
3967
- getRequestType,
3968
- getResponseByCacheKey,
3969
- getResponseByIdKey,
3970
- getResponseHeaders,
3971
- getResponseKey,
3972
- getResponseStartByIdKey,
3973
- getResponseStartByQueryKey,
3974
- getResponseStartKey,
3975
- getSimpleKey,
3976
- getTime,
3977
- getUniqueRequestId,
3978
- getUploadProgressByIdKey,
3979
- getUploadProgressByQueryKey,
3980
- getUploadProgressKey,
3981
- handleResponse,
3982
- hasDocument,
3983
- hasWindow,
3984
- interceptRequest,
3985
- interceptResponse,
3986
- logLevelOrder,
3987
- logger,
3988
- loggerColors,
3989
- loggerStyles,
3990
- mocker,
3991
- onDocumentEvent,
3992
- onWindowEvent,
3993
- parseErrorResponse,
3994
- parseResponse,
3995
- sendRequest,
3996
- stringifyDefaultOptions,
3997
- stringifyKey,
3998
- stringifyQueryParams,
3999
- stringifyValue,
4000
- xhrExtra
4001
- });
4002
- //# sourceMappingURL=index.js.map