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