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