@hyper-fetch/core 6.0.1 → 7.0.1

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