@rabbitio/ui-kit 1.0.0-beta.37 → 1.0.0-beta.39

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.
@@ -1,6 +1,8 @@
1
1
  import React, { useState, useRef, useEffect, useCallback } from 'react';
2
2
  import { BigNumber } from 'bignumber.js';
3
3
  import axios from 'axios';
4
+ import { v4 } from 'uuid';
5
+ import Hashes from 'jshashes';
4
6
  import EventBusInstance from 'eventbusjs';
5
7
 
6
8
  function createCommonjsModule(fn) {
@@ -1621,7 +1623,7 @@ var Logger = /*#__PURE__*/function () {
1621
1623
  return Logger;
1622
1624
  }();
1623
1625
 
1624
- function _catch$4(body, recover) {
1626
+ function _catch$8(body, recover) {
1625
1627
  try {
1626
1628
  var result = body();
1627
1629
  } catch (e) {
@@ -1637,7 +1639,7 @@ function useCallHandlingErrors() {
1637
1639
  setState = _useState[1];
1638
1640
  return useCallback(function (functionToBeCalled, event) {
1639
1641
  try {
1640
- var _temp = _catch$4(function () {
1642
+ var _temp = _catch$8(function () {
1641
1643
  return Promise.resolve(functionToBeCalled(event)).then(function () {});
1642
1644
  }, function (error) {
1643
1645
  Logger.logError(error, (functionToBeCalled == null ? void 0 : functionToBeCalled.name) || "errorBoundaryTrigger", "Caught by ErrorBoundary");
@@ -1675,6 +1677,96 @@ function useReferredState(initialValue) {
1675
1677
  return [reference, setReferredState];
1676
1678
  }
1677
1679
 
1680
+ var handleClickOutside = function handleClickOutside(exceptionsRefs, callback) {
1681
+ function handleClick(event) {
1682
+ var isExceptionClicked = exceptionsRefs.find(function (ref) {
1683
+ return (ref == null ? void 0 : ref.current) && ref.current.contains(event.target);
1684
+ });
1685
+ if (!isExceptionClicked) {
1686
+ callback();
1687
+ }
1688
+ }
1689
+ document.addEventListener("click", handleClick);
1690
+ return function () {
1691
+ return document.removeEventListener("click", handleClick);
1692
+ };
1693
+ };
1694
+
1695
+ var PARAMETER_VALUES_SEPARATOR = "|*|"; // Sting that with high probability will not be in the user's data
1696
+
1697
+ /**
1698
+ * Adds specified parameter with values to the URL query string
1699
+ *
1700
+ * @param parameterName - String - name of the parameter
1701
+ * @param values - Array of String values
1702
+ * @param updateURLCallback - callback that will be called with the updated query string. Can be used to save it to URL
1703
+ */
1704
+ function saveQueryParameterAndValues(parameterName, values, updateURLCallback) {
1705
+ if (updateURLCallback === void 0) {
1706
+ updateURLCallback = function updateURLCallback(newQueryString) {};
1707
+ }
1708
+ var parametersAndValues = parseSearchString();
1709
+ parametersAndValues = parametersAndValues.filter(function (parameterAndValues) {
1710
+ return parameterAndValues[0] !== parameterName;
1711
+ });
1712
+ var parameterValuesForURL = encodeURIComponent(values.join(PARAMETER_VALUES_SEPARATOR));
1713
+ parametersAndValues.push([parameterName, parameterValuesForURL]);
1714
+ var newQueryString = "?" + parametersAndValues.map(function (parameterAndValues) {
1715
+ return parameterAndValues.join("=");
1716
+ }).join("&");
1717
+ updateURLCallback(newQueryString);
1718
+ return newQueryString;
1719
+ }
1720
+
1721
+ /**
1722
+ * Removes specified parameter with values from the URL query string
1723
+ *
1724
+ * @param parameterName - String - name of the parameter
1725
+ * @param updateURLCallback - callback that will be called with the updated query string. Can be used to save it to URL
1726
+ */
1727
+ // TODO: [tests, moderate] units required the same as or other functions in this module
1728
+ function removeQueryParameterAndValues(parameterName, updateURLCallback) {
1729
+ if (updateURLCallback === void 0) {
1730
+ updateURLCallback = function updateURLCallback(newQueryString) {};
1731
+ }
1732
+ var parametersAndValues = parseSearchString();
1733
+ parametersAndValues = parametersAndValues.filter(function (parameterAndValues) {
1734
+ return parameterAndValues[0] !== parameterName;
1735
+ });
1736
+ var newQueryString = "?" + parametersAndValues.map(function (parameterAndValues) {
1737
+ return parameterAndValues.join("=");
1738
+ }).join("&");
1739
+ updateURLCallback(newQueryString);
1740
+ return newQueryString;
1741
+ }
1742
+
1743
+ /**
1744
+ * Retrieves parameter values from the URL query string.
1745
+ *
1746
+ * If there are several parameters with the same name in the URL then all their values are returned
1747
+ *
1748
+ * @param name {string} - parameter name
1749
+ * @return {string[]} [] - if the parameter is not present in URL. [""] - if parameter present but has empty value
1750
+ */
1751
+ function getQueryParameterValues(name) {
1752
+ return parseSearchString().filter(function (parameterAndValue) {
1753
+ return parameterAndValue[0] === name;
1754
+ }).reduce(function (allValues, parameterAndValue) {
1755
+ var values = decodeURIComponent(parameterAndValue[1] || "").split(PARAMETER_VALUES_SEPARATOR);
1756
+ return [].concat(allValues, values);
1757
+ }, []);
1758
+ }
1759
+ function parseSearchString() {
1760
+ var _window$location$sear;
1761
+ var trimmed = (((_window$location$sear = window.location.search) == null ? void 0 : _window$location$sear.slice(1)) || "").trim();
1762
+ return trimmed && trimmed.split("&").map(function (parameterAndValue) {
1763
+ return parameterAndValue.split("=");
1764
+ }) || [];
1765
+ }
1766
+ function getQueryParameterSingleValue(name) {
1767
+ return (getQueryParameterValues(name) || [])[0];
1768
+ }
1769
+
1678
1770
  /**
1679
1771
  * This function improves the passed error object (its message) by adding the passed function name
1680
1772
  * and additional message to it.
@@ -1703,6 +1795,17 @@ function improvedErrorMessage(e, settingFunction, additionalMessage) {
1703
1795
  additionalMessage && (message += additionalMessage + " ");
1704
1796
  return message;
1705
1797
  }
1798
+ function logErrorOrOutputToConsole(e) {
1799
+ try {
1800
+ // TODO: [dev] remove this after few weeks of testing output in real life
1801
+ // eslint-disable-next-line no-console
1802
+ console.log("BEFORE SAFE", e);
1803
+ Logger.log("logErrorOrOutputToConsole", safeStringify(e));
1804
+ } catch (e) {
1805
+ // eslint-disable-next-line no-console
1806
+ console.log("logErrorOrOutputToConsole", e);
1807
+ }
1808
+ }
1706
1809
 
1707
1810
  var FiatCurrenciesService = /*#__PURE__*/function () {
1708
1811
  function FiatCurrenciesService() {}
@@ -2574,7 +2677,109 @@ var Cache = /*#__PURE__*/function () {
2574
2677
  return Cache;
2575
2678
  }();
2576
2679
 
2577
- function _catch$3(body, recover) {
2680
+ function _catch$7(body, recover) {
2681
+ try {
2682
+ var result = body();
2683
+ } catch (e) {
2684
+ return recover(e);
2685
+ }
2686
+ if (result && result.then) {
2687
+ return result.then(void 0, recover);
2688
+ }
2689
+ return result;
2690
+ }
2691
+ function postponeExecution(execution, timeoutMS) {
2692
+ if (timeoutMS === void 0) {
2693
+ timeoutMS = 1000;
2694
+ }
2695
+ return new Promise(function (resolve, reject) {
2696
+ setTimeout(function () {
2697
+ try {
2698
+ var _temp = _catch$7(function () {
2699
+ return Promise.resolve(execution()).then(function (_execution) {
2700
+ resolve(_execution);
2701
+ });
2702
+ }, function (e) {
2703
+ reject(e);
2704
+ });
2705
+ return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0);
2706
+ } catch (e) {
2707
+ return Promise.reject(e);
2708
+ }
2709
+ }, timeoutMS);
2710
+ });
2711
+ }
2712
+
2713
+ var AxiosAdapter = /*#__PURE__*/function () {
2714
+ function AxiosAdapter() {}
2715
+ AxiosAdapter.call = function call(method) {
2716
+ try {
2717
+ var _arguments = arguments;
2718
+ return Promise.resolve(axios[method].apply(axios, [].slice.call(_arguments, 1)));
2719
+ } catch (e) {
2720
+ return Promise.reject(e);
2721
+ }
2722
+ };
2723
+ AxiosAdapter.get = function get() {
2724
+ try {
2725
+ var _arguments2 = arguments;
2726
+ return Promise.resolve(axios.get.apply(axios, [].slice.call(_arguments2)));
2727
+ } catch (e) {
2728
+ return Promise.reject(e);
2729
+ }
2730
+ };
2731
+ AxiosAdapter.post = function post() {
2732
+ try {
2733
+ var _arguments3 = arguments;
2734
+ return Promise.resolve(axios.post.apply(axios, [].slice.call(_arguments3)));
2735
+ } catch (e) {
2736
+ return Promise.reject(e);
2737
+ }
2738
+ };
2739
+ AxiosAdapter.put = function put() {
2740
+ try {
2741
+ var _arguments4 = arguments;
2742
+ return Promise.resolve(axios.put.apply(axios, [].slice.call(_arguments4)));
2743
+ } catch (e) {
2744
+ return Promise.reject(e);
2745
+ }
2746
+ };
2747
+ AxiosAdapter["delete"] = function _delete() {
2748
+ try {
2749
+ var _arguments5 = arguments;
2750
+ return Promise.resolve(axios["delete"].apply(axios, [].slice.call(_arguments5)));
2751
+ } catch (e) {
2752
+ return Promise.reject(e);
2753
+ }
2754
+ };
2755
+ AxiosAdapter.patch = function patch() {
2756
+ try {
2757
+ var _arguments6 = arguments;
2758
+ return Promise.resolve(axios.patch.apply(axios, [].slice.call(_arguments6)));
2759
+ } catch (e) {
2760
+ return Promise.reject(e);
2761
+ }
2762
+ };
2763
+ AxiosAdapter.options = function options() {
2764
+ try {
2765
+ var _arguments7 = arguments;
2766
+ return Promise.resolve(axios.options.apply(axios, [].slice.call(_arguments7)));
2767
+ } catch (e) {
2768
+ return Promise.reject(e);
2769
+ }
2770
+ };
2771
+ AxiosAdapter.head = function head() {
2772
+ try {
2773
+ var _arguments8 = arguments;
2774
+ return Promise.resolve(axios.head.apply(axios, [].slice.call(_arguments8)));
2775
+ } catch (e) {
2776
+ return Promise.reject(e);
2777
+ }
2778
+ };
2779
+ return AxiosAdapter;
2780
+ }();
2781
+
2782
+ function _catch$6(body, recover) {
2578
2783
  try {
2579
2784
  var result = body();
2580
2785
  } catch (e) {
@@ -2590,7 +2795,7 @@ var EmailsApi = /*#__PURE__*/function () {
2590
2795
  EmailsApi.sendEmail = function sendEmail(subject, body) {
2591
2796
  try {
2592
2797
  var _this = this;
2593
- var _temp = _catch$3(function () {
2798
+ var _temp = _catch$6(function () {
2594
2799
  var url = window.location.protocol + "//" + window.location.host + "/api/v1/" + _this.serverEndpointEntity;
2595
2800
  return Promise.resolve(axios.post(url, {
2596
2801
  subject: subject,
@@ -2608,6 +2813,1825 @@ var EmailsApi = /*#__PURE__*/function () {
2608
2813
  }();
2609
2814
  EmailsApi.serverEndpointEntity = "emails";
2610
2815
 
2816
+ /**
2817
+ * This util helps to avoid duplicated calls to a shared resource.
2818
+ * It tracks is there currently active calculation for the specific cache id and make all other requests
2819
+ * with the same cache id waiting for this active calculation to be finished. When the calculation ends
2820
+ * the resolver allows all the waiting requesters to get the data from cache and start their own calculations.
2821
+ *
2822
+ * This class should be instantiated inside some other service where you need to request some resource concurrently.
2823
+ * Rules:
2824
+ * 1. When you need to make a request inside your main service call 'getCachedOrWaitForCachedOrAcquireLock'
2825
+ * on the instance of this class and await for the result. If the flag allowing to start calculation is true
2826
+ * then you can request data inside your main service. Otherwise you should use the cached data as an another
2827
+ * requester just finished the most resent requesting and there is actual data in the cache that
2828
+ * is returned to you here.
2829
+ * 1.1 Also you can acquire a lock directly if you don't want to get cached data. Use the corresponding method 'acquireLock'.
2830
+ *
2831
+ * 2. If you start requesting (when you successfully acquired the lock) then after receiving the result of your
2832
+ * requesting you should call the 'saveCachedData' so the retrieved data will appear in the cache.
2833
+ *
2834
+ * 3. If you successfully acquired the lock then you should after calling the 'saveCachedData' call
2835
+ * the 'releaseLock' - this is mandatory to release the lock and allow other requesters to perform their requests.
2836
+ * WARNING: If for any reason you forget to call this method then this class instance will wait perpetually for
2837
+ * the lock releasing and all your attempts to request the data will constantly fail. So usually call it
2838
+ * inside the 'finally' block.
2839
+ *
2840
+ * TODO: [tests, critical++] add unit tests - massively used logic and can produce sophisticated concurrency bugs
2841
+ */
2842
+
2843
+ function _settle$2(pact, state, value) {
2844
+ if (!pact.s) {
2845
+ if (value instanceof _Pact$2) {
2846
+ if (value.s) {
2847
+ if (state & 1) {
2848
+ state = value.s;
2849
+ }
2850
+ value = value.v;
2851
+ } else {
2852
+ value.o = _settle$2.bind(null, pact, state);
2853
+ return;
2854
+ }
2855
+ }
2856
+ if (value && value.then) {
2857
+ value.then(_settle$2.bind(null, pact, state), _settle$2.bind(null, pact, 2));
2858
+ return;
2859
+ }
2860
+ pact.s = state;
2861
+ pact.v = value;
2862
+ const observer = pact.o;
2863
+ if (observer) {
2864
+ observer(pact);
2865
+ }
2866
+ }
2867
+ }
2868
+
2869
+ /**
2870
+ * Util class to control access to a resource when it can be called in parallel for the same result.
2871
+ * (E.g. getting today coins-fiat rates from some API).
2872
+ */
2873
+ var _Pact$2 = /*#__PURE__*/function () {
2874
+ function _Pact() {}
2875
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
2876
+ var result = new _Pact();
2877
+ var state = this.s;
2878
+ if (state) {
2879
+ var callback = state & 1 ? onFulfilled : onRejected;
2880
+ if (callback) {
2881
+ try {
2882
+ _settle$2(result, 1, callback(this.v));
2883
+ } catch (e) {
2884
+ _settle$2(result, 2, e);
2885
+ }
2886
+ return result;
2887
+ } else {
2888
+ return this;
2889
+ }
2890
+ }
2891
+ this.o = function (_this) {
2892
+ try {
2893
+ var value = _this.v;
2894
+ if (_this.s & 1) {
2895
+ _settle$2(result, 1, onFulfilled ? onFulfilled(value) : value);
2896
+ } else if (onRejected) {
2897
+ _settle$2(result, 1, onRejected(value));
2898
+ } else {
2899
+ _settle$2(result, 2, value);
2900
+ }
2901
+ } catch (e) {
2902
+ _settle$2(result, 2, e);
2903
+ }
2904
+ };
2905
+ return result;
2906
+ };
2907
+ return _Pact;
2908
+ }();
2909
+ function _isSettledPact$2(thenable) {
2910
+ return thenable instanceof _Pact$2 && thenable.s & 1;
2911
+ }
2912
+ function _for$1(test, update, body) {
2913
+ var stage;
2914
+ for (;;) {
2915
+ var shouldContinue = test();
2916
+ if (_isSettledPact$2(shouldContinue)) {
2917
+ shouldContinue = shouldContinue.v;
2918
+ }
2919
+ if (!shouldContinue) {
2920
+ return result;
2921
+ }
2922
+ if (shouldContinue.then) {
2923
+ stage = 0;
2924
+ break;
2925
+ }
2926
+ var result = body();
2927
+ if (result && result.then) {
2928
+ if (_isSettledPact$2(result)) {
2929
+ result = result.s;
2930
+ } else {
2931
+ stage = 1;
2932
+ break;
2933
+ }
2934
+ }
2935
+ if (update) {
2936
+ var updateValue = update();
2937
+ if (updateValue && updateValue.then && !_isSettledPact$2(updateValue)) {
2938
+ stage = 2;
2939
+ break;
2940
+ }
2941
+ }
2942
+ }
2943
+ var pact = new _Pact$2();
2944
+ var reject = _settle$2.bind(null, pact, 2);
2945
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
2946
+ return pact;
2947
+ function _resumeAfterBody(value) {
2948
+ result = value;
2949
+ do {
2950
+ if (update) {
2951
+ updateValue = update();
2952
+ if (updateValue && updateValue.then && !_isSettledPact$2(updateValue)) {
2953
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
2954
+ return;
2955
+ }
2956
+ }
2957
+ shouldContinue = test();
2958
+ if (!shouldContinue || _isSettledPact$2(shouldContinue) && !shouldContinue.v) {
2959
+ _settle$2(pact, 1, result);
2960
+ return;
2961
+ }
2962
+ if (shouldContinue.then) {
2963
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2964
+ return;
2965
+ }
2966
+ result = body();
2967
+ if (_isSettledPact$2(result)) {
2968
+ result = result.v;
2969
+ }
2970
+ } while (!result || !result.then);
2971
+ result.then(_resumeAfterBody).then(void 0, reject);
2972
+ }
2973
+ function _resumeAfterTest(shouldContinue) {
2974
+ if (shouldContinue) {
2975
+ result = body();
2976
+ if (result && result.then) {
2977
+ result.then(_resumeAfterBody).then(void 0, reject);
2978
+ } else {
2979
+ _resumeAfterBody(result);
2980
+ }
2981
+ } else {
2982
+ _settle$2(pact, 1, result);
2983
+ }
2984
+ }
2985
+ function _resumeAfterUpdate() {
2986
+ if (shouldContinue = test()) {
2987
+ if (shouldContinue.then) {
2988
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2989
+ } else {
2990
+ _resumeAfterTest(shouldContinue);
2991
+ }
2992
+ } else {
2993
+ _settle$2(pact, 1, result);
2994
+ }
2995
+ }
2996
+ }
2997
+ function _catch$5(body, recover) {
2998
+ try {
2999
+ var result = body();
3000
+ } catch (e) {
3001
+ return recover(e);
3002
+ }
3003
+ if (result && result.then) {
3004
+ return result.then(void 0, recover);
3005
+ }
3006
+ return result;
3007
+ }
3008
+ var CacheAndConcurrentRequestsResolver = /*#__PURE__*/function () {
3009
+ /**
3010
+ * @param bio {string} unique identifier for the exact service
3011
+ * @param cache {Cache} cache
3012
+ * @param cacheTtl {number|null} time to live for cache ms. 0 or null means the cache cannot expire
3013
+ * @param [maxCallAttemptsToWaitForAlreadyRunningRequest=100] {number} number of request allowed to do waiting for
3014
+ * result before we fail the original request. Use custom value only if you need to make the attempts count
3015
+ * and polling interval changes.
3016
+ * @param [timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished=1000] {number}
3017
+ * timeout ms for polling for a result. if you change maxCallAttemptsToWaitForAlreadyRunningRequest
3018
+ * then this parameter maybe also require the custom value.
3019
+ * @param [removeExpiredCacheAutomatically=true] {boolean}
3020
+ */
3021
+ function CacheAndConcurrentRequestsResolver(bio, cache, cacheTtl, removeExpiredCacheAutomatically, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished) {
3022
+ if (removeExpiredCacheAutomatically === void 0) {
3023
+ removeExpiredCacheAutomatically = true;
3024
+ }
3025
+ if (maxCallAttemptsToWaitForAlreadyRunningRequest === void 0) {
3026
+ maxCallAttemptsToWaitForAlreadyRunningRequest = 100;
3027
+ }
3028
+ if (timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished === void 0) {
3029
+ timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished = 1000;
3030
+ }
3031
+ if (cacheTtl != null && cacheTtl < timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished * 2) {
3032
+ /*
3033
+ * During the lifetime of this service e.g. if the data is being retrieved slowly we can get
3034
+ * RACE CONDITION when we constantly retrieve data and during retrieval it is expired, so we are trying
3035
+ * to retrieve it again and again.
3036
+ * We have a protection mechanism that we will wait no more than
3037
+ * maxCallAttemptsToWaitForAlreadyRunningRequest * timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished
3038
+ * but this additional check is aimed to reduce potential loading time for some requests.
3039
+ */
3040
+ throw new Error("DEV: Wrong parameters passed to construct " + bio + " - TTL " + cacheTtl + " should be 2 times greater than " + timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished);
3041
+ }
3042
+ this._bio = bio;
3043
+ this._cache = cache;
3044
+ this._cacheTtlMs = cacheTtl != null ? cacheTtl : null;
3045
+ this._maxExecutionTimeMs = maxCallAttemptsToWaitForAlreadyRunningRequest * timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished;
3046
+ this._removeExpiredCacheAutomatically = removeExpiredCacheAutomatically;
3047
+ this._requestsManager = new ManagerOfRequestsToTheSameResource(bio, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished);
3048
+ }
3049
+
3050
+ /**
3051
+ * When using this service this is the major method you should call to get data by cache id.
3052
+ * This method checks is there cached data and ether
3053
+ * - returns you flag that you can start requesting data from the shared resource
3054
+ * - or if there is already started calculation waits until it is finished (removed from this service)
3055
+ * and returns you the retrieved data
3056
+ * - or just returns you the cached data
3057
+ *
3058
+ * 'canStartDataRetrieval' equal true means that the lock was acquired, and you should manually call 'saveCachedData'
3059
+ * if needed and then 'releaseLock' to mark this calculation as finished so other
3060
+ * requesters can take their share of the resource.
3061
+ *
3062
+ * @param cacheId {string}
3063
+ * @return {Promise<({
3064
+ * canStartDataRetrieval: true,
3065
+ * cachedData: any,
3066
+ * lockId: string
3067
+ * }|{
3068
+ * canStartDataRetrieval: false,
3069
+ * cachedData: any
3070
+ * })>}
3071
+ */
3072
+ var _proto = CacheAndConcurrentRequestsResolver.prototype;
3073
+ _proto.getCachedOrWaitForCachedOrAcquireLock = function getCachedOrWaitForCachedOrAcquireLock(cacheId) {
3074
+ try {
3075
+ var _this = this;
3076
+ return Promise.resolve(_catch$5(function () {
3077
+ function _temp2() {
3078
+ var _cached, _cached2;
3079
+ return calculationId ? {
3080
+ canStartDataRetrieval: true,
3081
+ cachedData: (_cached = cached) != null ? _cached : cachedDataBackupIsPresentButExpired,
3082
+ lockId: calculationId
3083
+ } : {
3084
+ canStartDataRetrieval: false,
3085
+ cachedData: (_cached2 = cached) != null ? _cached2 : cachedDataBackupIsPresentButExpired
3086
+ };
3087
+ }
3088
+ var startedAtTimestamp = Date.now();
3089
+ var cached = _this._cache.get(cacheId);
3090
+ var cachedDataBackupIsPresentButExpired = null;
3091
+ if (cached != null && !_this._removeExpiredCacheAutomatically) {
3092
+ var lastUpdateTimestamp = _this._cache.getLastUpdateTimestamp(cacheId);
3093
+ if ((lastUpdateTimestamp != null ? lastUpdateTimestamp : 0) + _this._cacheTtlMs < Date.now()) {
3094
+ /*
3095
+ * Here we are manually clearing 'cached' value retrieved from cache to force the data loading.
3096
+ * But we save its value first to the backup variable to be able to return this value if ongoing
3097
+ * requesting fails.
3098
+ */
3099
+ cachedDataBackupIsPresentButExpired = cached;
3100
+ cached = null;
3101
+ }
3102
+ }
3103
+ var calculationId = null;
3104
+ var isRetrievedCacheExpired = true;
3105
+ var isWaitingForActiveCalculationSucceeded;
3106
+ var weStillHaveSomeTimeToProceedExecution = true;
3107
+ var _temp = _for$1(function () {
3108
+ return calculationId == null && cached == null && !!isRetrievedCacheExpired && !!weStillHaveSomeTimeToProceedExecution;
3109
+ }, void 0, function () {
3110
+ return Promise.resolve(_this._requestsManager.startCalculationOrWaitForActiveToFinish(cacheId)).then(function (result) {
3111
+ calculationId = typeof result === "string" ? result : null;
3112
+ isWaitingForActiveCalculationSucceeded = typeof result === "boolean" ? result : null;
3113
+ cached = _this._cache.get(cacheId);
3114
+ isRetrievedCacheExpired = isWaitingForActiveCalculationSucceeded && cached == null;
3115
+ weStillHaveSomeTimeToProceedExecution = Date.now() - startedAtTimestamp < _this._maxExecutionTimeMs;
3116
+ });
3117
+ });
3118
+ return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
3119
+ }, function (e) {
3120
+ improveAndRethrow(e, _this._bio + ".getCachedOrWaitForCachedOrAcquireLock");
3121
+ }));
3122
+ } catch (e) {
3123
+ return Promise.reject(e);
3124
+ }
3125
+ }
3126
+ /**
3127
+ * Returns just the current cache value for the given id.
3128
+ * Doesn't wait for the active calculation, doesn't acquire lock, just retrieves the current cache as it is.
3129
+ *
3130
+ * @param cacheId {string}
3131
+ * @return {any}
3132
+ */
3133
+ ;
3134
+ _proto.getCached = function getCached(cacheId) {
3135
+ try {
3136
+ return this._cache.get(cacheId);
3137
+ } catch (e) {
3138
+ improveAndRethrow(e, "getCached");
3139
+ }
3140
+ };
3141
+ _proto._getTtl = function _getTtl() {
3142
+ return this._removeExpiredCacheAutomatically ? this._cacheTtlMs : null;
3143
+ }
3144
+
3145
+ /**
3146
+ * Directly acquires the lock despite on cached data availability.
3147
+ * So if this method returns result === true you can start the data retrieval.
3148
+ *
3149
+ * @param cacheId {string}
3150
+ * @return {Promise<{ result: true, lockId: string }|{ result: false }>}
3151
+ */;
3152
+ _proto.acquireLock = function acquireLock(cacheId) {
3153
+ try {
3154
+ var _this2 = this;
3155
+ return Promise.resolve(_catch$5(function () {
3156
+ return Promise.resolve(_this2._requestsManager.acquireLock(cacheId));
3157
+ }, function (e) {
3158
+ improveAndRethrow(e, "acquireLock");
3159
+ }));
3160
+ } catch (e) {
3161
+ return Promise.reject(e);
3162
+ }
3163
+ }
3164
+ /**
3165
+ * This method should be called only if you acquired a lock successfully.
3166
+ *
3167
+ * If the current lock id is not equal to the passed one the passed data will be ignored.
3168
+ * Or you can do the synchronous data merging on your side and pass the
3169
+ * wasDataMergedSynchronouslyWithMostRecentCacheState=true so your data will be stored
3170
+ * despite on the lockId.
3171
+ * WARNING: you should do this only if you are sure you perform the synchronous update.
3172
+ *
3173
+ * @param cacheId {string}
3174
+ * @param lockId {string}
3175
+ * @param data {any}
3176
+ * @param [sessionDependentData=true] {boolean}
3177
+ * @param [wasDataMergedSynchronouslyWithMostRecentCacheState=false]
3178
+ */
3179
+ ;
3180
+ _proto.saveCachedData = function saveCachedData(cacheId, lockId, data, sessionDependentData, wasDataMergedSynchronouslyWithMostRecentCacheState) {
3181
+ if (sessionDependentData === void 0) {
3182
+ sessionDependentData = true;
3183
+ }
3184
+ if (wasDataMergedSynchronouslyWithMostRecentCacheState === void 0) {
3185
+ wasDataMergedSynchronouslyWithMostRecentCacheState = false;
3186
+ }
3187
+ try {
3188
+ if (wasDataMergedSynchronouslyWithMostRecentCacheState || this._requestsManager.isTheLockActiveOne(cacheId, lockId)) {
3189
+ /* We save passed data only if the <caller> has the currently acquired lockId.
3190
+ * If the passed lockId is not the active one it means that other code cleared/stopped the lock
3191
+ * acquired by the <caller> recently due to some urgent/more prior changes.
3192
+ *
3193
+ * But we allow user to pass the 'wasDataMergedSynchronouslyWithMostRecentCacheState' flag
3194
+ * that tells us that the user had taken the most recent cache value and merged his new data
3195
+ * with that cached value (AFTER possibly performing async data retrieval). This means that we
3196
+ * can ignore the fact that his lockId is no more relevant and save the passed data
3197
+ * as it is synchronously merged with the most recent cached data. (Synchronously merged means that
3198
+ * the lost update cannot occur during the merge time as JS execute the synchronous functions\
3199
+ * till the end).
3200
+ */
3201
+ if (sessionDependentData) {
3202
+ this._cache.putSessionDependentData(cacheId, data, this._getTtl());
3203
+ } else {
3204
+ this._cache.put(cacheId, data, this._getTtl());
3205
+ }
3206
+ }
3207
+ } catch (e) {
3208
+ improveAndRethrow(e, this._bio + ".saveCachedData");
3209
+ }
3210
+ }
3211
+
3212
+ /**
3213
+ * Should be called then and only then if you successfully acquired a lock with the lock id.
3214
+ *
3215
+ * @param cacheId {string}
3216
+ * @param lockId {string}
3217
+ */;
3218
+ _proto.releaseLock = function releaseLock(cacheId, lockId) {
3219
+ try {
3220
+ if (this._requestsManager.isTheLockActiveOne(cacheId, lockId)) {
3221
+ this._requestsManager.finishActiveCalculation(cacheId);
3222
+ }
3223
+ } catch (e) {
3224
+ improveAndRethrow(e, this._bio + ".releaseLock");
3225
+ }
3226
+ }
3227
+
3228
+ /**
3229
+ * Actualized currently present cached data by key. Applies the provided function to the cached data.
3230
+ *
3231
+ * @param cacheId {string} id of cache entry
3232
+ * @param synchronousCurrentCacheProcessor (function|null} synchronous function accepting cache entry. Should return
3233
+ * an object in following format:
3234
+ * {
3235
+ * isModified: boolean,
3236
+ * data: any
3237
+ * }
3238
+ * the flag signals whether data was changed during the processing or not
3239
+ * @param [sessionDependent=true] {boolean} whether to mark the cache entry as session-dependent
3240
+ */;
3241
+ _proto.actualizeCachedData = function actualizeCachedData(cacheId, synchronousCurrentCacheProcessor, sessionDependent) {
3242
+ if (sessionDependent === void 0) {
3243
+ sessionDependent = true;
3244
+ }
3245
+ try {
3246
+ var cached = this._cache.get(cacheId);
3247
+ var result = synchronousCurrentCacheProcessor(cached);
3248
+ if (result != null && result.isModified && (result == null ? void 0 : result.data) != null) {
3249
+ if (sessionDependent) {
3250
+ this._cache.putSessionDependentData(cacheId, result == null ? void 0 : result.data, this._getTtl());
3251
+ } else {
3252
+ this._cache.put(cacheId, result == null ? void 0 : result.data, this._getTtl());
3253
+ }
3254
+
3255
+ /* Here we call the lock releasing to ensure the currently active calculation will be ignored.
3256
+ * This is needed to ensure no 'lost update'.
3257
+ * Lost update can occur if we change data in this method and after that some calculation finishes
3258
+ * having the earlier data as its base to calculate its data set result. And the earlier data
3259
+ * has no changes applied inside this method, so we will lose them.
3260
+ *
3261
+ * This is not so good solution: ideally, we should acquire lock before performing any data updating.
3262
+ * But the goal of this method is to provide an instant ability to update the cached data.
3263
+ * And if we start acquiring the lock here the data update can be postponed significantly.
3264
+ * And this kills the desired nature of this method.
3265
+ * So we better lose some data retrieval (means abusing the resource a bit) than lose
3266
+ * the instant update expected after this method execution.
3267
+ */
3268
+ this._requestsManager.finishActiveCalculation(cacheId);
3269
+ }
3270
+ } catch (e) {
3271
+ improveAndRethrow(e, this._bio + ".actualizeCachedData");
3272
+ }
3273
+ };
3274
+ _proto.invalidate = function invalidate(key) {
3275
+ this._cache.invalidate(key);
3276
+ this._requestsManager.finishActiveCalculation(key);
3277
+ };
3278
+ _proto.invalidateContaining = function invalidateContaining(keyPart) {
3279
+ this._cache.invalidateContaining(keyPart);
3280
+ this._requestsManager.finishAllActiveCalculations(keyPart);
3281
+ };
3282
+ _proto.markAsExpiredButDontRemove = function markAsExpiredButDontRemove(key) {
3283
+ if (this._removeExpiredCacheAutomatically) {
3284
+ this._cache.markCacheItemAsExpiredButDontRemove(key, this._cacheTtlMs);
3285
+ } else {
3286
+ this._cache.setLastUpdateTimestamp(key, Date.now() - this._cacheTtlMs - 1);
3287
+ }
3288
+ this._requestsManager.finishAllActiveCalculations(key);
3289
+ };
3290
+ return CacheAndConcurrentRequestsResolver;
3291
+ }();
3292
+ var ManagerOfRequestsToTheSameResource = /*#__PURE__*/function () {
3293
+ /**
3294
+ * @param bio {string} resource-related identifier for logging
3295
+ * @param [maxPollsCount=100] {number} max number of attempts to wait when waiting for a lock acquisition
3296
+ * @param [timeoutDuration=1000] {number} timeout between the polls for a lock acquisition
3297
+ */
3298
+ function ManagerOfRequestsToTheSameResource(bio, maxPollsCount, timeoutDuration) {
3299
+ if (maxPollsCount === void 0) {
3300
+ maxPollsCount = 100;
3301
+ }
3302
+ if (timeoutDuration === void 0) {
3303
+ timeoutDuration = 1000;
3304
+ }
3305
+ this.bio = bio;
3306
+ this.maxPollsCount = maxPollsCount;
3307
+ this.timeoutDuration = timeoutDuration;
3308
+ this._activeCalculationsIds = new Map();
3309
+ this._nextCalculationIds = new Map();
3310
+ }
3311
+
3312
+ /**
3313
+ * If there is no active calculation just creates uuid and returns it.
3314
+ * If there is active calculation waits until it removed from the active calculation uuid variable.
3315
+ *
3316
+ * @param requestHash {string}
3317
+ * @return {Promise<string|boolean>} returns uuid of new active calculation or true if waiting for active
3318
+ * calculation succeed or false if max attempts count exceeded
3319
+ */
3320
+ var _proto2 = ManagerOfRequestsToTheSameResource.prototype;
3321
+ _proto2.startCalculationOrWaitForActiveToFinish = function startCalculationOrWaitForActiveToFinish(requestHash) {
3322
+ try {
3323
+ var _exit;
3324
+ var _this3 = this;
3325
+ var _temp3 = _catch$5(function () {
3326
+ var activeCalculationIdForHash = _this3._activeCalculationsIds.get(requestHash);
3327
+ if (activeCalculationIdForHash == null) {
3328
+ var id = v4();
3329
+ _this3._activeCalculationsIds.set(requestHash, id);
3330
+ _exit = 1;
3331
+ return id;
3332
+ }
3333
+ return Promise.resolve(_this3._waitForCalculationIdToFinish(requestHash, activeCalculationIdForHash, 0)).then(function (_await$_this3$_waitFo) {
3334
+ _exit = 1;
3335
+ return _await$_this3$_waitFo;
3336
+ });
3337
+ }, function (e) {
3338
+ Logger.logError(e, "startCalculationOrWaitForActiveToFinish_" + _this3.bio);
3339
+ });
3340
+ return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function (_result3) {
3341
+ return _exit ? _result3 : null;
3342
+ }) : _exit ? _temp3 : null);
3343
+ } catch (e) {
3344
+ return Promise.reject(e);
3345
+ }
3346
+ }
3347
+ /**
3348
+ * Acquires lock to the resource by the provided hash.
3349
+ *
3350
+ * @param requestHash {string}
3351
+ * @return {Promise<{ result: true, lockId: string }|{ result: false }>} result is true if the lock is successfully
3352
+ * acquired, false if the max allowed time to wait for acquisition expired or any unexpected error occurs
3353
+ * during the waiting.
3354
+ */
3355
+ ;
3356
+ _proto2.acquireLock = function acquireLock(requestHash) {
3357
+ try {
3358
+ var _this4 = this;
3359
+ return Promise.resolve(_catch$5(function () {
3360
+ var _this4$_nextCalculati;
3361
+ var activeId = _this4._activeCalculationsIds.get(requestHash);
3362
+ var nextId = v4();
3363
+ if (activeId == null) {
3364
+ _this4._activeCalculationsIds.set(requestHash, nextId);
3365
+ return {
3366
+ result: true,
3367
+ lockId: nextId
3368
+ };
3369
+ }
3370
+ var currentNext = (_this4$_nextCalculati = _this4._nextCalculationIds.get(requestHash)) != null ? _this4$_nextCalculati : [];
3371
+ currentNext.push(nextId);
3372
+ _this4._nextCalculationIds.set(requestHash, currentNext);
3373
+ return Promise.resolve(_this4._waitForCalculationIdToFinish(requestHash, activeId, 0, nextId)).then(function (waitingResult) {
3374
+ return {
3375
+ result: waitingResult,
3376
+ lockId: waitingResult ? nextId : undefined
3377
+ };
3378
+ });
3379
+ }, function (e) {
3380
+ improveAndRethrow(e, "acquireLock");
3381
+ }));
3382
+ } catch (e) {
3383
+ return Promise.reject(e);
3384
+ }
3385
+ }
3386
+ /**
3387
+ * Clears active calculation id.
3388
+ * WARNING: if you forget to call this method the start* one will perform maxPollsCount attempts before finishing
3389
+ * @param requestHash {string} hash of request. Helps to distinct the request for the same resource but
3390
+ * having different request parameters and hold a dedicated calculation id per this hash
3391
+ */
3392
+ ;
3393
+ _proto2.finishActiveCalculation = function finishActiveCalculation(requestHash) {
3394
+ if (requestHash === void 0) {
3395
+ requestHash = "default";
3396
+ }
3397
+ try {
3398
+ var _this$_nextCalculatio;
3399
+ this._activeCalculationsIds["delete"](requestHash);
3400
+ var next = (_this$_nextCalculatio = this._nextCalculationIds.get(requestHash)) != null ? _this$_nextCalculatio : [];
3401
+ if (next.length) {
3402
+ this._activeCalculationsIds.set(requestHash, next[0]);
3403
+ this._nextCalculationIds.set(requestHash, next.slice(1));
3404
+ }
3405
+ } catch (e) {
3406
+ improveAndRethrow(e, "finishActiveCalculation");
3407
+ }
3408
+ };
3409
+ _proto2.finishAllActiveCalculations = function finishAllActiveCalculations(keyPart) {
3410
+ var _this5 = this;
3411
+ if (keyPart === void 0) {
3412
+ keyPart = "";
3413
+ }
3414
+ try {
3415
+ Array.from(this._activeCalculationsIds.keys()).forEach(function (hash) {
3416
+ if (typeof hash === "string" && new RegExp(keyPart).test(hash)) {
3417
+ _this5.finishActiveCalculation(hash);
3418
+ }
3419
+ });
3420
+ } catch (e) {
3421
+ improveAndRethrow(e, "finishAllActiveCalculations");
3422
+ }
3423
+ }
3424
+
3425
+ /**
3426
+ * @param requestHash {string}
3427
+ * @param lockId {string}
3428
+ * @return {boolean}
3429
+ */;
3430
+ _proto2.isTheLockActiveOne = function isTheLockActiveOne(requestHash, lockId) {
3431
+ try {
3432
+ return this._activeCalculationsIds.get(requestHash) === lockId;
3433
+ } catch (e) {
3434
+ improveAndRethrow(e, "isTheLockActiveOne");
3435
+ }
3436
+ }
3437
+
3438
+ /**
3439
+ * @param requestHash {string}
3440
+ * @param activeCalculationId {string|null}
3441
+ * @param [attemptIndex=0] {number}
3442
+ * @param waitForCalculationId {string|null} if you want to wait for an exact id to appear as active then pass this parameter
3443
+ * @return {Promise<boolean>} true
3444
+ * - if the given calculation id is no more an active one
3445
+ * - or it is equal to waitForCalculationId
3446
+ * false
3447
+ * - if waiting period exceeds the max allowed waiting time or unexpected error occurs
3448
+ * @private
3449
+ */;
3450
+ _proto2._waitForCalculationIdToFinish = function _waitForCalculationIdToFinish(requestHash, activeCalculationId, attemptIndex, waitForCalculationId) {
3451
+ if (attemptIndex === void 0) {
3452
+ attemptIndex = 0;
3453
+ }
3454
+ if (waitForCalculationId === void 0) {
3455
+ waitForCalculationId = null;
3456
+ }
3457
+ try {
3458
+ var _this6 = this;
3459
+ try {
3460
+ if (attemptIndex + 1 > _this6.maxPollsCount) {
3461
+ // Max number of polls for active calculation id change is achieved. So we return false.
3462
+ return Promise.resolve(false);
3463
+ }
3464
+ var currentId = _this6._activeCalculationsIds.get(requestHash);
3465
+ if (waitForCalculationId == null ? currentId !== activeCalculationId : currentId === waitForCalculationId) {
3466
+ /* We return true depending on the usage of this function:
3467
+ * 1. if there is calculation id that we should wait for to become an active then we return true only
3468
+ * if this id becomes the active one.
3469
+ *
3470
+ * Theoretically we can fail to wait for the desired calculation id. This can be caused by wrong use of
3471
+ * this service or by any other mistakes/errors. But this waiting function will return false anyway if
3472
+ * the number of polls done exceeds the max allowed.
3473
+ *
3474
+ * 2. if we just wait for the currently active calculation id to be finished then we return true
3475
+ * when we notice that the current active id differs from the original passed into this function.
3476
+ */
3477
+ return Promise.resolve(true);
3478
+ } else {
3479
+ /* The original calculation id is still the active one, so we are scheduling a new attempt to check
3480
+ * whether the active calculation id changed or not in timeoutDuration milliseconds.
3481
+ */
3482
+ var it = _this6;
3483
+ return Promise.resolve(new Promise(function (resolve, reject) {
3484
+ setTimeout(function () {
3485
+ try {
3486
+ resolve(it._waitForCalculationIdToFinish(requestHash, activeCalculationId, attemptIndex + 1));
3487
+ } catch (e) {
3488
+ reject(e);
3489
+ }
3490
+ }, _this6.timeoutDuration);
3491
+ }));
3492
+ }
3493
+ } catch (e) {
3494
+ Logger.logError(e, "_waitForCalculationIdToFinish", "Failed to wait for active calculation id change.");
3495
+ return Promise.resolve(false);
3496
+ }
3497
+ } catch (e) {
3498
+ return Promise.reject(e);
3499
+ }
3500
+ };
3501
+ return ManagerOfRequestsToTheSameResource;
3502
+ }();
3503
+
3504
+ // TODO: [refactoring, low] Consider removing this logic task_id=c360f2af75764bde8badd9ff1cc00d48
3505
+ var ConcurrentCalculationsMetadataHolder = /*#__PURE__*/function () {
3506
+ function ConcurrentCalculationsMetadataHolder() {
3507
+ this._calculations = {};
3508
+ }
3509
+ var _proto = ConcurrentCalculationsMetadataHolder.prototype;
3510
+ _proto.startCalculation = function startCalculation(domain, calculationsHistoryMaxLength) {
3511
+ if (calculationsHistoryMaxLength === void 0) {
3512
+ calculationsHistoryMaxLength = 100;
3513
+ }
3514
+ if (!this._calculations[domain]) {
3515
+ this._calculations[domain] = [];
3516
+ }
3517
+ if (this._calculations[domain].length > calculationsHistoryMaxLength) {
3518
+ this._calculations[domain] = this._calculations[domain].slice(Math.round(calculationsHistoryMaxLength * 0.2));
3519
+ }
3520
+ var newCalculation = {
3521
+ startTimestamp: Date.now(),
3522
+ endTimestamp: null,
3523
+ uuid: v4()
3524
+ };
3525
+ this._calculations[domain].push(newCalculation);
3526
+ return newCalculation.uuid;
3527
+ };
3528
+ _proto.endCalculation = function endCalculation(domain, uuid, isFailed) {
3529
+ if (isFailed === void 0) {
3530
+ isFailed = false;
3531
+ }
3532
+ try {
3533
+ var _calculation$endTimes, _calculation$startTim, _calculation$uuid;
3534
+ var calculation = this._calculations[domain].find(function (calculation) {
3535
+ return (calculation == null ? void 0 : calculation.uuid) === uuid;
3536
+ });
3537
+ if (calculation) {
3538
+ calculation.endTimestamp = Date.now();
3539
+ calculation.isFiled = isFailed;
3540
+ }
3541
+ var elapsed = ((((_calculation$endTimes = calculation == null ? void 0 : calculation.endTimestamp) != null ? _calculation$endTimes : 0) - ((_calculation$startTim = calculation == null ? void 0 : calculation.startTimestamp) != null ? _calculation$startTim : 0)) / 1000).toFixed(1);
3542
+ Logger.log("endCalculation", elapsed + " ms: " + domain + "." + ((_calculation$uuid = calculation == null ? void 0 : calculation.uuid) != null ? _calculation$uuid : "").slice(0, 7));
3543
+ return calculation;
3544
+ } catch (e) {
3545
+ Logger.logError(e, "endCalculation");
3546
+ }
3547
+ };
3548
+ _proto.isCalculationLate = function isCalculationLate(domain, uuid) {
3549
+ var queue = this._calculations[domain];
3550
+ var analysingCalculation = queue.find(function (item) {
3551
+ return item.uuid === uuid;
3552
+ });
3553
+ return analysingCalculation && !!queue.find(function (calculation) {
3554
+ return calculation.endTimestamp != null && calculation.startTimestamp > analysingCalculation.startTimestamp;
3555
+ });
3556
+ };
3557
+ _proto.printCalculationsWaitingMoreThanSpecifiedSeconds = function printCalculationsWaitingMoreThanSpecifiedSeconds(waitingLastsMs) {
3558
+ var _this = this;
3559
+ if (waitingLastsMs === void 0) {
3560
+ waitingLastsMs = 2000;
3561
+ }
3562
+ var calculations = Object.keys(this._calculations).map(function (domain) {
3563
+ return _this._calculations[domain].map(function (c) {
3564
+ return _extends({}, c, {
3565
+ domain: domain
3566
+ });
3567
+ });
3568
+ }).flat().filter(function (c) {
3569
+ return c.endTimestamp === null && Date.now() - c.startTimestamp > waitingLastsMs;
3570
+ });
3571
+ Logger.log("printCalculationsWaitingMoreThanSpecifiedSeconds", "Calculations waiting more than " + (waitingLastsMs / 1000).toFixed(1) + "s:\n" + calculations.map(function (c) {
3572
+ return c.domain + "." + c.uuid.slice(0, 8) + ": " + (Date.now() - c.startTimestamp) + "\n";
3573
+ }));
3574
+ };
3575
+ return ConcurrentCalculationsMetadataHolder;
3576
+ }();
3577
+ var concurrentCalculationsMetadataHolder = new ConcurrentCalculationsMetadataHolder();
3578
+
3579
+ var ExternalServicesStatsCollector = /*#__PURE__*/function () {
3580
+ function ExternalServicesStatsCollector() {
3581
+ this.stats = new Map();
3582
+ }
3583
+ var _proto = ExternalServicesStatsCollector.prototype;
3584
+ _proto.externalServiceFailed = function externalServiceFailed(serviceUrl, message) {
3585
+ try {
3586
+ var processMessage = function processMessage(stat, errorMessage) {
3587
+ var _stat$errors, _errorMessage;
3588
+ var errors = (_stat$errors = stat.errors) != null ? _stat$errors : {};
3589
+ errorMessage = (_errorMessage = errorMessage) != null ? _errorMessage : "";
3590
+ if (errorMessage.match(/.*network.+error.*/i)) {
3591
+ errors["networkError"] = (errors["networkError"] || 0) + 1;
3592
+ } else if (errorMessage.match(/.*timeout.+exceeded.*/i)) {
3593
+ errors["timeoutExceeded"] = (errors["timeoutExceeded"] || 0) + 1;
3594
+ } else if (errors["other"]) {
3595
+ errors["other"].push(message);
3596
+ } else {
3597
+ errors["other"] = [message];
3598
+ }
3599
+ stat.errors = errors;
3600
+ };
3601
+ if (this.stats.has(serviceUrl)) {
3602
+ var stat = this.stats.get(serviceUrl);
3603
+ stat.callsCount += 1;
3604
+ stat.failsCount += 1;
3605
+ processMessage(stat, message);
3606
+ } else {
3607
+ this.stats.set(serviceUrl, {
3608
+ callsCount: 1,
3609
+ failsCount: 1
3610
+ });
3611
+ processMessage(this.stats.get(serviceUrl), message);
3612
+ }
3613
+ } catch (e) {
3614
+ improveAndRethrow(e, "externalServiceFailed");
3615
+ }
3616
+ };
3617
+ _proto.externalServiceCalledWithoutError = function externalServiceCalledWithoutError(serviceUrl) {
3618
+ try {
3619
+ if (this.stats.has(serviceUrl)) {
3620
+ var stat = this.stats.get(serviceUrl);
3621
+ stat.callsCount += 1;
3622
+ } else {
3623
+ this.stats.set(serviceUrl, {
3624
+ callsCount: 1,
3625
+ failsCount: 0
3626
+ });
3627
+ }
3628
+ } catch (e) {
3629
+ improveAndRethrow(e, "externalServiceCalledWithoutError");
3630
+ }
3631
+ }
3632
+
3633
+ /**
3634
+ * Returns statistics about external services failures.
3635
+ * Provides how many calls were performed and what the percent of failed calls. Also returns errors stat.
3636
+ *
3637
+ * @return {Array<object>} Array of objects of type { failsPerCent: number, calls: number }
3638
+ * sorted by the highest fails percent desc
3639
+ */;
3640
+ _proto.getStats = function getStats() {
3641
+ var _this = this;
3642
+ try {
3643
+ return Array.from(this.stats.keys()).map(function (key) {
3644
+ var _stat$errors2;
3645
+ var stat = _this.stats.get(key);
3646
+ return {
3647
+ url: key,
3648
+ failsPerCent: (stat.failsCount / stat.callsCount * 100).toFixed(2),
3649
+ calls: stat.callsCount,
3650
+ errors: (_stat$errors2 = stat.errors) != null ? _stat$errors2 : []
3651
+ };
3652
+ }).sort(function (s1, s2) {
3653
+ return s1.failsPerCent - s2.failsPerCent;
3654
+ });
3655
+ } catch (e) {
3656
+ Logger.logError(e, "getStats");
3657
+ }
3658
+ };
3659
+ return ExternalServicesStatsCollector;
3660
+ }();
3661
+
3662
+ /**
3663
+ * TODO: [refactoring, critical] update backend copy of this service. Also there is a task to extract this
3664
+ * service and other related to it stuff to dedicated npm package task_id=b008ee5e4a3f42c08c73831c4bb3db4e
3665
+ *
3666
+ * Template service needed to avoid duplication of the same logic when we need to call
3667
+ * external APIs to retrieve some data. The idea is to use several API providers to retrieve the same data. It helps to
3668
+ * improve the reliability of a data retrieval.
3669
+ */
3670
+
3671
+ function _catch$4(body, recover) {
3672
+ try {
3673
+ var result = body();
3674
+ } catch (e) {
3675
+ return recover(e);
3676
+ }
3677
+ if (result && result.then) {
3678
+ return result.then(void 0, recover);
3679
+ }
3680
+ return result;
3681
+ }
3682
+ function _settle$1(pact, state, value) {
3683
+ if (!pact.s) {
3684
+ if (value instanceof _Pact$1) {
3685
+ if (value.s) {
3686
+ if (state & 1) {
3687
+ state = value.s;
3688
+ }
3689
+ value = value.v;
3690
+ } else {
3691
+ value.o = _settle$1.bind(null, pact, state);
3692
+ return;
3693
+ }
3694
+ }
3695
+ if (value && value.then) {
3696
+ value.then(_settle$1.bind(null, pact, state), _settle$1.bind(null, pact, 2));
3697
+ return;
3698
+ }
3699
+ pact.s = state;
3700
+ pact.v = value;
3701
+ var observer = pact.o;
3702
+ if (observer) {
3703
+ observer(pact);
3704
+ }
3705
+ }
3706
+ }
3707
+ var _Pact$1 = /*#__PURE__*/function () {
3708
+ function _Pact() {}
3709
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
3710
+ var result = new _Pact();
3711
+ var state = this.s;
3712
+ if (state) {
3713
+ var callback = state & 1 ? onFulfilled : onRejected;
3714
+ if (callback) {
3715
+ try {
3716
+ _settle$1(result, 1, callback(this.v));
3717
+ } catch (e) {
3718
+ _settle$1(result, 2, e);
3719
+ }
3720
+ return result;
3721
+ } else {
3722
+ return this;
3723
+ }
3724
+ }
3725
+ this.o = function (_this) {
3726
+ try {
3727
+ var value = _this.v;
3728
+ if (_this.s & 1) {
3729
+ _settle$1(result, 1, onFulfilled ? onFulfilled(value) : value);
3730
+ } else if (onRejected) {
3731
+ _settle$1(result, 1, onRejected(value));
3732
+ } else {
3733
+ _settle$1(result, 2, value);
3734
+ }
3735
+ } catch (e) {
3736
+ _settle$1(result, 2, e);
3737
+ }
3738
+ };
3739
+ return result;
3740
+ };
3741
+ return _Pact;
3742
+ }();
3743
+ function _isSettledPact$1(thenable) {
3744
+ return thenable instanceof _Pact$1 && thenable.s & 1;
3745
+ }
3746
+ function _for(test, update, body) {
3747
+ var stage;
3748
+ for (;;) {
3749
+ var shouldContinue = test();
3750
+ if (_isSettledPact$1(shouldContinue)) {
3751
+ shouldContinue = shouldContinue.v;
3752
+ }
3753
+ if (!shouldContinue) {
3754
+ return result;
3755
+ }
3756
+ if (shouldContinue.then) {
3757
+ stage = 0;
3758
+ break;
3759
+ }
3760
+ var result = body();
3761
+ if (result && result.then) {
3762
+ if (_isSettledPact$1(result)) {
3763
+ result = result.s;
3764
+ } else {
3765
+ stage = 1;
3766
+ break;
3767
+ }
3768
+ }
3769
+ if (update) {
3770
+ var updateValue = update();
3771
+ if (updateValue && updateValue.then && !_isSettledPact$1(updateValue)) {
3772
+ stage = 2;
3773
+ break;
3774
+ }
3775
+ }
3776
+ }
3777
+ var pact = new _Pact$1();
3778
+ var reject = _settle$1.bind(null, pact, 2);
3779
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
3780
+ return pact;
3781
+ function _resumeAfterBody(value) {
3782
+ result = value;
3783
+ do {
3784
+ if (update) {
3785
+ updateValue = update();
3786
+ if (updateValue && updateValue.then && !_isSettledPact$1(updateValue)) {
3787
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
3788
+ return;
3789
+ }
3790
+ }
3791
+ shouldContinue = test();
3792
+ if (!shouldContinue || _isSettledPact$1(shouldContinue) && !shouldContinue.v) {
3793
+ _settle$1(pact, 1, result);
3794
+ return;
3795
+ }
3796
+ if (shouldContinue.then) {
3797
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3798
+ return;
3799
+ }
3800
+ result = body();
3801
+ if (_isSettledPact$1(result)) {
3802
+ result = result.v;
3803
+ }
3804
+ } while (!result || !result.then);
3805
+ result.then(_resumeAfterBody).then(void 0, reject);
3806
+ }
3807
+ function _resumeAfterTest(shouldContinue) {
3808
+ if (shouldContinue) {
3809
+ result = body();
3810
+ if (result && result.then) {
3811
+ result.then(_resumeAfterBody).then(void 0, reject);
3812
+ } else {
3813
+ _resumeAfterBody(result);
3814
+ }
3815
+ } else {
3816
+ _settle$1(pact, 1, result);
3817
+ }
3818
+ }
3819
+ function _resumeAfterUpdate() {
3820
+ if (shouldContinue = test()) {
3821
+ if (shouldContinue.then) {
3822
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3823
+ } else {
3824
+ _resumeAfterTest(shouldContinue);
3825
+ }
3826
+ } else {
3827
+ _settle$1(pact, 1, result);
3828
+ }
3829
+ }
3830
+ }
3831
+ function _finallyRethrows$1(body, finalizer) {
3832
+ try {
3833
+ var result = body();
3834
+ } catch (e) {
3835
+ return finalizer(true, e);
3836
+ }
3837
+ if (result && result.then) {
3838
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
3839
+ }
3840
+ return finalizer(false, result);
3841
+ }
3842
+ function _do(body, test) {
3843
+ var awaitBody;
3844
+ do {
3845
+ var result = body();
3846
+ if (result && result.then) {
3847
+ if (_isSettledPact$1(result)) {
3848
+ result = result.v;
3849
+ } else {
3850
+ awaitBody = true;
3851
+ break;
3852
+ }
3853
+ }
3854
+ var shouldContinue = test();
3855
+ if (_isSettledPact$1(shouldContinue)) {
3856
+ shouldContinue = shouldContinue.v;
3857
+ }
3858
+ if (!shouldContinue) {
3859
+ return result;
3860
+ }
3861
+ } while (!shouldContinue.then);
3862
+ var pact = new _Pact$1();
3863
+ var reject = _settle$1.bind(null, pact, 2);
3864
+ (awaitBody ? result.then(_resumeAfterBody) : shouldContinue.then(_resumeAfterTest)).then(void 0, reject);
3865
+ return pact;
3866
+ function _resumeAfterBody(value) {
3867
+ result = value;
3868
+ for (;;) {
3869
+ shouldContinue = test();
3870
+ if (_isSettledPact$1(shouldContinue)) {
3871
+ shouldContinue = shouldContinue.v;
3872
+ }
3873
+ if (!shouldContinue) {
3874
+ break;
3875
+ }
3876
+ if (shouldContinue.then) {
3877
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3878
+ return;
3879
+ }
3880
+ result = body();
3881
+ if (result && result.then) {
3882
+ if (_isSettledPact$1(result)) {
3883
+ result = result.v;
3884
+ } else {
3885
+ result.then(_resumeAfterBody).then(void 0, reject);
3886
+ return;
3887
+ }
3888
+ }
3889
+ }
3890
+ _settle$1(pact, 1, result);
3891
+ }
3892
+ function _resumeAfterTest(shouldContinue) {
3893
+ if (shouldContinue) {
3894
+ do {
3895
+ result = body();
3896
+ if (result && result.then) {
3897
+ if (_isSettledPact$1(result)) {
3898
+ result = result.v;
3899
+ } else {
3900
+ result.then(_resumeAfterBody).then(void 0, reject);
3901
+ return;
3902
+ }
3903
+ }
3904
+ shouldContinue = test();
3905
+ if (_isSettledPact$1(shouldContinue)) {
3906
+ shouldContinue = shouldContinue.v;
3907
+ }
3908
+ if (!shouldContinue) {
3909
+ _settle$1(pact, 1, result);
3910
+ return;
3911
+ }
3912
+ } while (!shouldContinue.then);
3913
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3914
+ } else {
3915
+ _settle$1(pact, 1, result);
3916
+ }
3917
+ }
3918
+ }
3919
+ function _forTo$1(array, body, check) {
3920
+ var i = -1,
3921
+ pact,
3922
+ reject;
3923
+ function _cycle(result) {
3924
+ try {
3925
+ while (++i < array.length && (!check || !check())) {
3926
+ result = body(i);
3927
+ if (result && result.then) {
3928
+ if (_isSettledPact$1(result)) {
3929
+ result = result.v;
3930
+ } else {
3931
+ result.then(_cycle, reject || (reject = _settle$1.bind(null, pact = new _Pact$1(), 2)));
3932
+ return;
3933
+ }
3934
+ }
3935
+ }
3936
+ if (pact) {
3937
+ _settle$1(pact, 1, result);
3938
+ } else {
3939
+ pact = result;
3940
+ }
3941
+ } catch (e) {
3942
+ _settle$1(pact || (pact = new _Pact$1()), 2, e);
3943
+ }
3944
+ }
3945
+ _cycle();
3946
+ return pact;
3947
+ }
3948
+ var RobustExternalAPICallerService = /*#__PURE__*/function () {
3949
+ RobustExternalAPICallerService.getStats = function getStats() {
3950
+ this.statsCollector.getStats();
3951
+ }
3952
+
3953
+ /**
3954
+ * @param bio {string} service name for logging
3955
+ * @param providersData {ExternalApiProvider[]} array of providers
3956
+ * @param [logger] {function} function to be used for logging
3957
+ */;
3958
+ function RobustExternalAPICallerService(bio, providersData, logger) {
3959
+ providersData.forEach(function (provider) {
3960
+ if (!provider.endpoint && provider.endpoint !== "" || !provider.httpMethod) {
3961
+ throw new Error("Wrong format of providers data for: " + JSON.stringify(provider));
3962
+ }
3963
+ });
3964
+
3965
+ // We add niceFactor - just number to order the providers array by. It is helpful to call
3966
+ // less robust APIs only if more robust fails
3967
+ this.providers = providersData;
3968
+ providersData.forEach(function (provider) {
3969
+ return provider.resetNiceFactor();
3970
+ });
3971
+ this.bio = bio;
3972
+ this._logger = Logger.logError;
3973
+ }
3974
+ var _proto = RobustExternalAPICallerService.prototype;
3975
+ /**
3976
+ * Performs data retrieval from external APIs. Tries providers till the data is retrieved.
3977
+ *
3978
+ * @param parametersValues {array} array of values of the parameters for URL query string [and/or body]
3979
+ * @param timeoutMS {number} http timeout to wait for response. If provider has its specific timeout value then it is used
3980
+ * @param [cancelToken] {object|undefined} axios token to force-cancel requests from high-level code
3981
+ * @param [attemptsCount] {number|undefined} number of attempts to be performed
3982
+ * @param [doNotFailForNowData] {boolean|undefined} pass true if you do not want us to throw an error if we retrieved null data from all the providers
3983
+ * @return {Promise<any>} resolving to retrieved data (or array of results if specific provider requires
3984
+ * several requests. NOTE: we flatten nested arrays - results of each separate request done for the specific provider)
3985
+ * @throws Error if requests to all providers are failed
3986
+ */
3987
+ _proto.callExternalAPI = function callExternalAPI(parametersValues, timeoutMS, cancelToken, attemptsCount, doNotFailForNowData) {
3988
+ if (parametersValues === void 0) {
3989
+ parametersValues = [];
3990
+ }
3991
+ if (timeoutMS === void 0) {
3992
+ timeoutMS = 3500;
3993
+ }
3994
+ if (cancelToken === void 0) {
3995
+ cancelToken = null;
3996
+ }
3997
+ if (attemptsCount === void 0) {
3998
+ attemptsCount = 1;
3999
+ }
4000
+ if (doNotFailForNowData === void 0) {
4001
+ doNotFailForNowData = false;
4002
+ }
4003
+ try {
4004
+ var _this = this;
4005
+ var result;
4006
+ var calculationUuid = concurrentCalculationsMetadataHolder.startCalculation(_this.bio);
4007
+ return Promise.resolve(_finallyRethrows$1(function () {
4008
+ return _catch$4(function () {
4009
+ function _temp5() {
4010
+ var _result2, _result3;
4011
+ if (((_result2 = result) == null ? void 0 : _result2.data) == null) {
4012
+ // TODO: [feature, moderate] looks like we should not fail for null data as it is strange - the provider will fail when processing data internally
4013
+ var error = new Error("Failed to retrieve data. It means all attempts have been failed. DEV: add more attempts to this data retrieval");
4014
+ if (!doNotFailForNowData) {
4015
+ throw error;
4016
+ } else {
4017
+ _this._logger(error, _this.bio + ".callExternalAPI");
4018
+ }
4019
+ }
4020
+ return (_result3 = result) == null ? void 0 : _result3.data;
4021
+ }
4022
+ var i = 0;
4023
+ var _temp4 = _for(function () {
4024
+ var _result4, _result5;
4025
+ return (i < attemptsCount || !!((_result4 = result) != null && _result4.shouldBeForceRetried)) && ((_result5 = result) == null ? void 0 : _result5.data) == null;
4026
+ }, function () {
4027
+ return ++i;
4028
+ }, function () {
4029
+ /**
4030
+ * We use rpsFactor to improve re-attempting to call the providers if the last attempt resulted with
4031
+ * the fail due to abused RPSes of some (most part of) providers.
4032
+ * The _performCallAttempt in such a case will return increased rpsFactor inside the result object.
4033
+ */
4034
+ var rpsFactor = result ? result.rpsFactor : RobustExternalAPICallerService.defaultRPSFactor;
4035
+ result = null;
4036
+ var _temp3 = _catch$4(function () {
4037
+ function _temp2() {
4038
+ var _result$errors;
4039
+ if ((_result$errors = result.errors) != null && _result$errors.length) {
4040
+ var errors = result.errors;
4041
+ _this._logger(new Error("Failed at attempt " + i + ". " + errors.length + " errors. Messages: " + safeStringify(errors.map(function (error) {
4042
+ return error.message;
4043
+ })) + ": " + safeStringify(errors) + "."), _this.bio + ".callExternalAPI", "", true);
4044
+ }
4045
+ }
4046
+ var _temp = function (_result6) {
4047
+ if (i === 0 && !((_result6 = result) != null && _result6.shouldBeForceRetried)) {
4048
+ return Promise.resolve(_this._performCallAttempt(parametersValues, timeoutMS, cancelToken, rpsFactor, doNotFailForNowData)).then(function (_this$_performCallAtt) {
4049
+ result = _this$_performCallAtt;
4050
+ });
4051
+ } else {
4052
+ var maxRps = Math.max.apply(Math, _this.providers.map(function (provider) {
4053
+ var _provider$getRps;
4054
+ return (_provider$getRps = provider.getRps()) != null ? _provider$getRps : 0;
4055
+ }));
4056
+ var waitingTimeMs = maxRps ? 1000 / (maxRps / rpsFactor) : 0;
4057
+ return Promise.resolve(new Promise(function (resolve, reject) {
4058
+ setTimeout(function () {
4059
+ try {
4060
+ var _temp6 = _catch$4(function () {
4061
+ return Promise.resolve(_this._performCallAttempt(parametersValues, timeoutMS, cancelToken, rpsFactor, doNotFailForNowData)).then(function (_this$_performCallAtt2) {
4062
+ resolve(_this$_performCallAtt2);
4063
+ });
4064
+ }, function (e) {
4065
+ reject(e);
4066
+ });
4067
+ return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0);
4068
+ } catch (e) {
4069
+ return Promise.reject(e);
4070
+ }
4071
+ }, waitingTimeMs);
4072
+ })).then(function (_Promise) {
4073
+ result = _Promise;
4074
+ });
4075
+ }
4076
+ }();
4077
+ return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
4078
+ }, function (e) {
4079
+ _this._logger(e, _this.bio + ".callExternalAPI", "Failed to perform external providers calling");
4080
+ });
4081
+ if (_temp3 && _temp3.then) return _temp3.then(function () {});
4082
+ });
4083
+ return _temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4);
4084
+ }, function (e) {
4085
+ improveAndRethrow(e, _this.bio + ".callExternalAPI");
4086
+ });
4087
+ }, function (_wasThrown, _result) {
4088
+ concurrentCalculationsMetadataHolder.endCalculation(_this.bio, calculationUuid);
4089
+ if (_wasThrown) throw _result;
4090
+ return _result;
4091
+ }));
4092
+ } catch (e) {
4093
+ return Promise.reject(e);
4094
+ }
4095
+ };
4096
+ _proto._performCallAttempt = function _performCallAttempt(parametersValues, timeoutMS, cancelToken, rpsFactor, doNotFailForNowData) {
4097
+ try {
4098
+ var _temp15 = function _temp15() {
4099
+ var _data;
4100
+ // If we are declining more than 50% of providers (by exceeding RPS) then we note that it better to retry the whole process of providers requesting
4101
+ var shouldBeForceRetried = data == null && countOfRequestsDeclinedByRps > Math.floor(providers.length * 0.5);
4102
+ var rpsMultiplier = shouldBeForceRetried ? RobustExternalAPICallerService.rpsMultiplier : 1;
4103
+ return {
4104
+ data: (_data = data) != null ? _data : null,
4105
+ shouldBeForceRetried: shouldBeForceRetried,
4106
+ rpsFactor: rpsFactor * rpsMultiplier,
4107
+ errors: errors
4108
+ };
4109
+ };
4110
+ var _this2 = this;
4111
+ var providers = _this2._reorderProvidersByNiceFactor();
4112
+ var data = undefined,
4113
+ providerIndex = 0,
4114
+ countOfRequestsDeclinedByRps = 0,
4115
+ errors = [];
4116
+ var _temp14 = _for(function () {
4117
+ return !data && providerIndex < providers.length;
4118
+ }, void 0, function () {
4119
+ var provider = providers[providerIndex];
4120
+ if (provider.isRpsExceeded()) {
4121
+ /**
4122
+ * Current provider's RPS is exceeded, so we try next provider. Also, we count such cases to make
4123
+ * a decision about the force-retry need.
4124
+ */
4125
+ ++providerIndex;
4126
+ ++countOfRequestsDeclinedByRps;
4127
+ return;
4128
+ }
4129
+ var _temp13 = _finallyRethrows$1(function () {
4130
+ return _catch$4(function () {
4131
+ var _provider$specificHea;
4132
+ function _temp12() {
4133
+ if (iterationsData.length) {
4134
+ if (httpMethods.length > 1) {
4135
+ data = provider.incorporateIterationsData(iterationsData);
4136
+ } else {
4137
+ data = iterationsData[0];
4138
+ }
4139
+ } else if (!doNotFailForNowData) {
4140
+ RobustExternalAPICallerService.statsCollector.externalServiceFailed(provider.getApiGroupId(), "Response data was null for some reason");
4141
+ punishProvider(provider);
4142
+ }
4143
+ }
4144
+ var axiosConfig = _extends({}, cancelToken ? {
4145
+ cancelToken: cancelToken
4146
+ } : {}, {
4147
+ timeout: provider.timeout || timeoutMS,
4148
+ headers: (_provider$specificHea = provider.specificHeaders) != null ? _provider$specificHea : {}
4149
+ });
4150
+ var httpMethods = Array.isArray(provider.httpMethod) ? provider.httpMethod : [provider.httpMethod];
4151
+ var iterationsData = [];
4152
+ var _temp11 = _forTo$1(httpMethods, function (subRequestIndex) {
4153
+ function _temp10() {
4154
+ var responsesDataForPages = responsesForPages.map(function (response) {
4155
+ return provider.getDataByResponse(response, parametersValues, subRequestIndex, iterationsData);
4156
+ });
4157
+ var allData = responsesDataForPages;
4158
+ if (Array.isArray(responsesDataForPages[0])) {
4159
+ allData = responsesDataForPages.flat();
4160
+ } else if (responsesDataForPages.length === 1) {
4161
+ allData = responsesDataForPages[0];
4162
+ }
4163
+ iterationsData.push(allData);
4164
+ }
4165
+ var query = provider.composeQueryString(parametersValues, subRequestIndex);
4166
+ var endpoint = "" + provider.endpoint + query;
4167
+ var axiosParams = [endpoint, axiosConfig];
4168
+ if (["post", "put", "patch"].find(function (method) {
4169
+ return method === httpMethods[subRequestIndex];
4170
+ })) {
4171
+ var _provider$composeBody;
4172
+ var body = (_provider$composeBody = provider.composeBody(parametersValues, subRequestIndex)) != null ? _provider$composeBody : null;
4173
+ axiosParams.splice(1, 0, body);
4174
+ }
4175
+ var pageNumber = 0;
4176
+ var responsesForPages = [];
4177
+ var hasNextPage = provider.doesSupportPagination();
4178
+ var _temp9 = _do(function () {
4179
+ function _temp8() {
4180
+ if (hasNextPage) {
4181
+ hasNextPage = !provider.checkWhetherResponseIsForLastPage(responsesForPages[pageNumber - 1], responsesForPages[pageNumber], pageNumber, subRequestIndex);
4182
+ }
4183
+ pageNumber++;
4184
+ }
4185
+ var _temp7 = function () {
4186
+ if (subRequestIndex === 0 && pageNumber === 0) {
4187
+ provider.actualizeLastCalledTimestamp();
4188
+ return Promise.resolve(AxiosAdapter.call.apply(AxiosAdapter, [httpMethods[subRequestIndex]].concat(axiosParams))).then(function (_AxiosAdapter$call) {
4189
+ responsesForPages[pageNumber] = _AxiosAdapter$call;
4190
+ RobustExternalAPICallerService.statsCollector.externalServiceCalledWithoutError(provider.getApiGroupId());
4191
+ });
4192
+ } else {
4193
+ if (pageNumber > 0) {
4194
+ var actualizedParams = provider.changeQueryParametersForPageNumber(parametersValues, responsesForPages[pageNumber - 1], pageNumber, subRequestIndex);
4195
+ var _query = provider.composeQueryString(actualizedParams, subRequestIndex);
4196
+ axiosParams[0] = "" + provider.endpoint + _query;
4197
+ }
4198
+ /**
4199
+ * For second and more request we postpone each request to not exceed RPS
4200
+ * of current provider. We use rpsFactor to dynamically increase the rps to avoid
4201
+ * too frequent calls if we continue failing to retrieve the data due to RPS exceeding.
4202
+ * TODO: [dev] test RPS factor logic (units or integration)
4203
+ */
4204
+
4205
+ var waitingTimeMS = provider.getRps() ? 1000 / (provider.getRps() / rpsFactor) : 0;
4206
+ var postponeUntilRpsExceeded = function postponeUntilRpsExceeded(recursionLevel) {
4207
+ if (recursionLevel === void 0) {
4208
+ recursionLevel = 0;
4209
+ }
4210
+ try {
4211
+ return Promise.resolve(postponeExecution(function () {
4212
+ try {
4213
+ var _temp17 = function _temp17(_result8) {
4214
+ if (_exit) return _result8;
4215
+ provider.actualizeLastCalledTimestamp();
4216
+ return Promise.resolve(AxiosAdapter.call.apply(AxiosAdapter, [httpMethods[subRequestIndex]].concat(axiosParams)));
4217
+ };
4218
+ var _exit;
4219
+ var maxCountOfPostponingAttempts = 2;
4220
+ var _temp16 = function () {
4221
+ if (provider.isRpsExceeded() && recursionLevel < maxCountOfPostponingAttempts) {
4222
+ return Promise.resolve(postponeUntilRpsExceeded(recursionLevel + 1)).then(function (_await$postponeUntilR) {
4223
+ _exit = 1;
4224
+ return _await$postponeUntilR;
4225
+ });
4226
+ }
4227
+ }();
4228
+ return Promise.resolve(_temp16 && _temp16.then ? _temp16.then(_temp17) : _temp17(_temp16));
4229
+ } catch (e) {
4230
+ return Promise.reject(e);
4231
+ }
4232
+ }, waitingTimeMS));
4233
+ } catch (e) {
4234
+ return Promise.reject(e);
4235
+ }
4236
+ };
4237
+ return Promise.resolve(postponeUntilRpsExceeded()).then(function (_postponeUntilRpsExce) {
4238
+ responsesForPages[pageNumber] = _postponeUntilRpsExce;
4239
+ });
4240
+ }
4241
+ }();
4242
+ return _temp7 && _temp7.then ? _temp7.then(_temp8) : _temp8(_temp7);
4243
+ }, function () {
4244
+ return !!hasNextPage;
4245
+ });
4246
+ return _temp9 && _temp9.then ? _temp9.then(_temp10) : _temp10(_temp9);
4247
+ });
4248
+ return _temp11 && _temp11.then ? _temp11.then(_temp12) : _temp12(_temp11);
4249
+ }, function (e) {
4250
+ punishProvider(provider);
4251
+ RobustExternalAPICallerService.statsCollector.externalServiceFailed(provider.getApiGroupId(), e == null ? void 0 : e.message);
4252
+ errors.push(e);
4253
+ });
4254
+ }, function (_wasThrown2, _result7) {
4255
+ providerIndex++;
4256
+ if (_wasThrown2) throw _result7;
4257
+ return _result7;
4258
+ });
4259
+ if (_temp13 && _temp13.then) return _temp13.then(function () {});
4260
+ });
4261
+ return Promise.resolve(_temp14 && _temp14.then ? _temp14.then(_temp15) : _temp15(_temp14));
4262
+ } catch (e) {
4263
+ return Promise.reject(e);
4264
+ }
4265
+ };
4266
+ _proto._reorderProvidersByNiceFactor = function _reorderProvidersByNiceFactor() {
4267
+ var providersCopy = [].concat(this.providers);
4268
+ return providersCopy.sort(function (p1, p2) {
4269
+ return p2.niceFactor - p1.niceFactor;
4270
+ });
4271
+ };
4272
+ return RobustExternalAPICallerService;
4273
+ }();
4274
+ RobustExternalAPICallerService.statsCollector = new ExternalServicesStatsCollector();
4275
+ RobustExternalAPICallerService.defaultRPSFactor = 1;
4276
+ RobustExternalAPICallerService.rpsMultiplier = 1.05;
4277
+ function punishProvider(provider) {
4278
+ provider.niceFactor = provider.niceFactor - 1;
4279
+ }
4280
+
4281
+ /**
4282
+ * Extended edit of RobustExternalApiCallerService supporting cache and management of concurrent requests
4283
+ * to the same resource.
4284
+ * TODO: [tests, critical] Massively used logic
4285
+ */
4286
+
4287
+ function _catch$3(body, recover) {
4288
+ try {
4289
+ var result = body();
4290
+ } catch (e) {
4291
+ return recover(e);
4292
+ }
4293
+ if (result && result.then) {
4294
+ return result.then(void 0, recover);
4295
+ }
4296
+ return result;
4297
+ }
4298
+ function _finallyRethrows(body, finalizer) {
4299
+ try {
4300
+ var result = body();
4301
+ } catch (e) {
4302
+ return finalizer(true, e);
4303
+ }
4304
+ if (result && result.then) {
4305
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
4306
+ }
4307
+ return finalizer(false, result);
4308
+ }
4309
+ var CachedRobustExternalApiCallerService = /*#__PURE__*/function () {
4310
+ /**
4311
+ * @param bio {string} unique service identifier
4312
+ * @param cache {Cache} cache instance
4313
+ * @param providersData {ExternalApiProvider[]} array of providers
4314
+ * @param [cacheTtlMs=10000] {number} time to live for cache ms
4315
+ * @param [maxCallAttemptsToWaitForAlreadyRunningRequest=50] {number} see details in CacheAndConcurrentRequestsResolver
4316
+ * @param [timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished=3000] {number} see details in CacheAndConcurrentRequestsResolver
4317
+ * @param [removeExpiredCacheAutomatically=true] {boolean} whether to remove cached data automatically when ttl exceeds
4318
+ * @param [mergeCachedAndNewlyRetrievedData=null] {function} function accepting cached data, newly retrieved data and id field name for list items
4319
+ * and merging them. use if needed
4320
+ */
4321
+ function CachedRobustExternalApiCallerService(bio, cache, providersData, cacheTtlMs, removeExpiredCacheAutomatically, mergeCachedAndNewlyRetrievedData, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished) {
4322
+ if (cacheTtlMs === void 0) {
4323
+ cacheTtlMs = 10000;
4324
+ }
4325
+ if (removeExpiredCacheAutomatically === void 0) {
4326
+ removeExpiredCacheAutomatically = true;
4327
+ }
4328
+ if (mergeCachedAndNewlyRetrievedData === void 0) {
4329
+ mergeCachedAndNewlyRetrievedData = null;
4330
+ }
4331
+ if (maxCallAttemptsToWaitForAlreadyRunningRequest === void 0) {
4332
+ maxCallAttemptsToWaitForAlreadyRunningRequest = 100;
4333
+ }
4334
+ if (timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished === void 0) {
4335
+ timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished = 1000;
4336
+ }
4337
+ this._provider = new RobustExternalAPICallerService("cached_" + bio, providersData, Logger.logError);
4338
+ this._cacheTtlMs = cacheTtlMs;
4339
+ this._cahceAndRequestsResolver = new CacheAndConcurrentRequestsResolver(bio, cache, cacheTtlMs, removeExpiredCacheAutomatically, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished);
4340
+ this._cahceIds = [];
4341
+ this._mergeCachedAndNewlyRetrievedData = mergeCachedAndNewlyRetrievedData;
4342
+ }
4343
+
4344
+ /**
4345
+ * Calls the external API or returns data from cache. Just waits if the same data already requested.
4346
+ *
4347
+ * @param parametersValues {array} array of values of the parameters for URL query string [and/or body]
4348
+ * @param timeoutMS {number} http timeout to wait for response. If provider has its specific timeout value then it is used
4349
+ * @param [cancelToken] {object|undefined} axios token to force-cancel requests from high-level code
4350
+ * @param [attemptsCount] {number|undefined} number of attempts to be performed
4351
+ * @param [customHashFunctionForParams] {function|undefined} function without params calculating the hash to be
4352
+ * added to bio of the service to compose a unique parameters-specific cache id
4353
+ * @param [doNotFailForNowData] {boolean|undefined} pass true if you do not want us to throw an error if we retrieved null data from all the providers
4354
+ * @return {Promise<any>} resolving to retrieved data (or array of results if specific provider requires
4355
+ * several requests. NOTE: we flatten nested arrays - results of each separate request done for the specific provider)
4356
+ * @throws Error if requests to all providers are failed
4357
+ */
4358
+ var _proto = CachedRobustExternalApiCallerService.prototype;
4359
+ _proto.callExternalAPICached = function callExternalAPICached(parametersValues, timeoutMS, cancelToken, attemptsCount, customHashFunctionForParams, doNotFailForNowData) {
4360
+ if (parametersValues === void 0) {
4361
+ parametersValues = [];
4362
+ }
4363
+ if (timeoutMS === void 0) {
4364
+ timeoutMS = 3500;
4365
+ }
4366
+ if (cancelToken === void 0) {
4367
+ cancelToken = null;
4368
+ }
4369
+ if (attemptsCount === void 0) {
4370
+ attemptsCount = 1;
4371
+ }
4372
+ if (customHashFunctionForParams === void 0) {
4373
+ customHashFunctionForParams = null;
4374
+ }
4375
+ if (doNotFailForNowData === void 0) {
4376
+ doNotFailForNowData = false;
4377
+ }
4378
+ try {
4379
+ var _this = this;
4380
+ var loggerSource = _this._provider.bio + ".callExternalAPICached";
4381
+ var cacheId;
4382
+ var result;
4383
+ return Promise.resolve(_finallyRethrows(function () {
4384
+ return _catch$3(function () {
4385
+ cacheId = _this._calculateCacheId(parametersValues, customHashFunctionForParams);
4386
+ return Promise.resolve(_this._cahceAndRequestsResolver.getCachedOrWaitForCachedOrAcquireLock(cacheId)).then(function (_this$_cahceAndReques) {
4387
+ var _result2, _result4;
4388
+ result = _this$_cahceAndReques;
4389
+ return (_result2 = result) != null && _result2.canStartDataRetrieval ? Promise.resolve(_this._provider.callExternalAPI(parametersValues, timeoutMS, cancelToken, attemptsCount, doNotFailForNowData)).then(function (data) {
4390
+ var canPerformMerge = typeof _this._mergeCachedAndNewlyRetrievedData === "function";
4391
+ if (canPerformMerge) {
4392
+ var mostRecentCached = _this._cahceAndRequestsResolver.getCached(cacheId);
4393
+ data = _this._mergeCachedAndNewlyRetrievedData(mostRecentCached, data, parametersValues);
4394
+ }
4395
+ if (data != null) {
4396
+ var _result3;
4397
+ _this._cahceAndRequestsResolver.saveCachedData(cacheId, (_result3 = result) == null ? void 0 : _result3.lockId, data, true, canPerformMerge);
4398
+ _this._cahceIds.indexOf(cacheId) < 0 && _this._cahceIds.push(cacheId);
4399
+ }
4400
+ return data;
4401
+ }) : (_result4 = result) == null ? void 0 : _result4.cachedData;
4402
+ });
4403
+ }, function (e) {
4404
+ improveAndRethrow(e, loggerSource);
4405
+ });
4406
+ }, function (_wasThrown, _result) {
4407
+ var _result5;
4408
+ _this._cahceAndRequestsResolver.releaseLock(cacheId, (_result5 = result) == null ? void 0 : _result5.lockId);
4409
+ if (_wasThrown) throw _result;
4410
+ return _result;
4411
+ }));
4412
+ } catch (e) {
4413
+ return Promise.reject(e);
4414
+ }
4415
+ };
4416
+ _proto.invalidateCaches = function invalidateCaches() {
4417
+ var _this2 = this;
4418
+ this._cahceIds.forEach(function (key) {
4419
+ return _this2._cahceAndRequestsResolver.invalidate(key);
4420
+ });
4421
+ };
4422
+ _proto.actualizeCachedData = function actualizeCachedData(params, synchronousCurrentCacheProcessor, customHashFunctionForParams, sessionDependent, actualizedAtTimestamp) {
4423
+ if (customHashFunctionForParams === void 0) {
4424
+ customHashFunctionForParams = null;
4425
+ }
4426
+ if (sessionDependent === void 0) {
4427
+ sessionDependent = true;
4428
+ }
4429
+ var cacheId = this._calculateCacheId(params, customHashFunctionForParams);
4430
+ this._cahceAndRequestsResolver.actualizeCachedData(cacheId, synchronousCurrentCacheProcessor, sessionDependent);
4431
+ };
4432
+ _proto.markCacheAsExpiredButDontRemove = function markCacheAsExpiredButDontRemove(parametersValues, customHashFunctionForParams) {
4433
+ try {
4434
+ this._cahceAndRequestsResolver.markAsExpiredButDontRemove(this._calculateCacheId(parametersValues, customHashFunctionForParams));
4435
+ } catch (e) {
4436
+ improveAndRethrow(e, "markCacheAsExpiredButDontRemove");
4437
+ }
4438
+ };
4439
+ _proto._calculateCacheId = function _calculateCacheId(parametersValues, customHashFunctionForParams) {
4440
+ if (customHashFunctionForParams === void 0) {
4441
+ customHashFunctionForParams = null;
4442
+ }
4443
+ try {
4444
+ var hash = typeof customHashFunctionForParams === "function" ? customHashFunctionForParams(parametersValues) : !parametersValues ? "" : new Hashes.SHA512().hex(safeStringify(parametersValues));
4445
+ return this._provider.bio + "-" + hash;
4446
+ } catch (e) {
4447
+ improveAndRethrow(e, this._provider.bio + "_calculateCacheId");
4448
+ }
4449
+ };
4450
+ return CachedRobustExternalApiCallerService;
4451
+ }();
4452
+
4453
+ /**
4454
+ * Utils class needed to perform cancelling of axios request inside some process.
4455
+ * Provides cancel state and axios token for HTTP requests
4456
+ */
4457
+ var CancelProcessing = /*#__PURE__*/function () {
4458
+ function CancelProcessing() {
4459
+ this._cancelToken = axios.CancelToken.source();
4460
+ this._isCanceled = false;
4461
+ }
4462
+ var _proto = CancelProcessing.prototype;
4463
+ _proto.cancel = function cancel() {
4464
+ this._isCanceled = true;
4465
+ this._cancelToken.cancel();
4466
+ };
4467
+ _proto.isCanceled = function isCanceled() {
4468
+ return this._isCanceled;
4469
+ };
4470
+ _proto.getToken = function getToken() {
4471
+ return this._cancelToken.token;
4472
+ };
4473
+ CancelProcessing.instance = function instance() {
4474
+ return new CancelProcessing();
4475
+ };
4476
+ return CancelProcessing;
4477
+ }();
4478
+
4479
+ var ExternalApiProvider = /*#__PURE__*/function () {
4480
+ /**
4481
+ * Creates an instance of external api provider.
4482
+ *
4483
+ * If you need sub-request then use 'subRequestIndex' to check current request index in functions below.
4484
+ * Also use array for 'httpMethod'.
4485
+ *
4486
+ * If the endpoint of dedicated provider has pagination then you should customize the behavior using
4487
+ * "changeQueryParametersForPageNumber", "checkWhetherResponseIsForLastPage".
4488
+ *
4489
+ * We perform RPS counting all over the App to avoid blocking our clients due to abuses of the providers.
4490
+ *
4491
+ * @param endpoint {string} URL to the provider's endpoint. Note: you can customize it using composeQueryString
4492
+ * @param [httpMethod] {string|string[]} one of "get", "post", "put", "patch", "delete" or an array of these values
4493
+ * for request having sub-requests
4494
+ * @param [timeout] {number} number of milliseconds to wait for the response
4495
+ * @param [apiGroup] {ApiGroup} singleton object containing parameters of API group. Helpful when you use the same
4496
+ * api for different providers to avoid hardcoding RPS inside each provider what can cause mistakes
4497
+ * @param [specificHeaders] {Object} contains specific keys (headers) and values (their content) if needed for this provider
4498
+ * @param [maxPageLength] {number} optional number of items per page if the request supports pagination
4499
+ */
4500
+ function ExternalApiProvider(endpoint, httpMethod, timeout, apiGroup, specificHeaders, maxPageLength) {
4501
+ var _maxPageLength, _specificHeaders;
4502
+ if (specificHeaders === void 0) {
4503
+ specificHeaders = {};
4504
+ }
4505
+ if (maxPageLength === void 0) {
4506
+ maxPageLength = Number.MAX_SAFE_INTEGER;
4507
+ }
4508
+ this.endpoint = endpoint;
4509
+ this.httpMethod = httpMethod != null ? httpMethod : "get";
4510
+ // TODO: [refactoring, critical] We have two timeouts for robust data retrieval - here and inside the service method call, need to remain the only
4511
+ this.timeout = timeout != null ? timeout : 10000;
4512
+ // TODO: [refactoring, critical] We need single place for all RPSes as we use them as hardcoded constants now inside different services
4513
+ this.apiGroup = apiGroup;
4514
+ this.maxPageLength = (_maxPageLength = maxPageLength) != null ? _maxPageLength : Number.MAX_SAFE_INTEGER;
4515
+ this.niceFactor = 1;
4516
+ this.specificHeaders = (_specificHeaders = specificHeaders) != null ? _specificHeaders : {};
4517
+ }
4518
+ var _proto = ExternalApiProvider.prototype;
4519
+ _proto.getRps = function getRps() {
4520
+ var _this$apiGroup$rps;
4521
+ return (_this$apiGroup$rps = this.apiGroup.rps) != null ? _this$apiGroup$rps : 2;
4522
+ };
4523
+ _proto.isRpsExceeded = function isRpsExceeded() {
4524
+ return this.apiGroup.isRpsExceeded();
4525
+ };
4526
+ _proto.actualizeLastCalledTimestamp = function actualizeLastCalledTimestamp() {
4527
+ this.apiGroup.actualizeLastCalledTimestamp();
4528
+ };
4529
+ _proto.getApiGroupId = function getApiGroupId() {
4530
+ return this.apiGroup.id;
4531
+ }
4532
+
4533
+ /**
4534
+ * Some endpoint can require several sub requests. Example is one request to get confirmed transactions
4535
+ * and another request for unconfirmed transactions. You should override this method to return true for such requests.
4536
+ *
4537
+ * @return {boolean} true if this provider requires several requests to retrieve the data
4538
+ */;
4539
+ _proto.doesRequireSubRequests = function doesRequireSubRequests() {
4540
+ return false;
4541
+ }
4542
+
4543
+ /**
4544
+ * Some endpoint support pagination. Override this method if so and implement corresponding methods.
4545
+ *
4546
+ * @return {boolean} true if this provider requires several requests to retrieve the data
4547
+ */;
4548
+ _proto.doesSupportPagination = function doesSupportPagination() {
4549
+ return false;
4550
+ }
4551
+
4552
+ /**
4553
+ * Composes a query string to be added to the endpoint of this provider.
4554
+ *
4555
+ * @param params {any[]} params array passed to the RobustExternalAPICallerService
4556
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4557
+ * @returns {string} query string to be concatenated with endpoint
4558
+ */;
4559
+ _proto.composeQueryString = function composeQueryString(params, subRequestIndex) {
4560
+ return "";
4561
+ }
4562
+
4563
+ /**
4564
+ * Composes a body to be added to the request
4565
+ *
4566
+ * @param params {any[]} params array passed to the RobustExternalAPICallerService
4567
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4568
+ * @returns {string}
4569
+ */;
4570
+ _proto.composeBody = function composeBody(params, subRequestIndex) {
4571
+ return "";
4572
+ }
4573
+
4574
+ /**
4575
+ * Extracts data from the response and returns it
4576
+ *
4577
+ * @param response {Object} HTTP response returned by provider
4578
+ * @param [params] {any[]} params array passed to the RobustExternalAPICallerService
4579
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4580
+ * @param iterationsData {any[]} array of data retrieved from previous sub-requests
4581
+ * @returns {any}
4582
+ */;
4583
+ _proto.getDataByResponse = function getDataByResponse(response, params, subRequestIndex, iterationsData) {
4584
+ return [];
4585
+ }
4586
+
4587
+ /**
4588
+ * Function changing the query string according to page number and previous response
4589
+ * Only for endpoints supporting pagination
4590
+ *
4591
+ * @param params {any[]} params array passed to the RobustExternalAPICallerService
4592
+ * @param previousResponse {Object} HTTP response returned by provider for previous call (previous page)
4593
+ * @param pageNumber {number} new page number. We count from 0. You need to manually increment with 1 if your
4594
+ * provider counts pages starting with 1
4595
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4596
+ * @returns {any[]}
4597
+ */;
4598
+ _proto.changeQueryParametersForPageNumber = function changeQueryParametersForPageNumber(params, previousResponse, pageNumber, subRequestIndex) {
4599
+ return params;
4600
+ }
4601
+
4602
+ /**
4603
+ * Function checking whether the response is for the last page to stop requesting for a next page.
4604
+ * Only for endpoints supporting pagination.
4605
+ *
4606
+ * @param previousResponse {Object} HTTP response returned by provider for previous call (previous page)
4607
+ * @param currentResponse {Object} HTTP response returned by provider for current call (current page, next after the previous)
4608
+ * @param currentPageNumber {number} current page number (for current response)
4609
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4610
+ * @returns {boolean}
4611
+ */;
4612
+ _proto.checkWhetherResponseIsForLastPage = function checkWhetherResponseIsForLastPage(previousResponse, currentResponse, currentPageNumber, subRequestIndex) {
4613
+ return true;
4614
+ }
4615
+
4616
+ /**
4617
+ * Resets the nice factor to default value
4618
+ */;
4619
+ _proto.resetNiceFactor = function resetNiceFactor() {
4620
+ this.niceFactor = 1;
4621
+ }
4622
+
4623
+ /**
4624
+ * Internal method used for requests requiring sub-requests.
4625
+ *
4626
+ * @param iterationsData {any[]} iterations data retrieved from getDataByResponse called per sub-request.
4627
+ * @return {any} by default flatten the passed iterations data array. Should be redefined if you need another logic.
4628
+ */;
4629
+ _proto.incorporateIterationsData = function incorporateIterationsData(iterationsData) {
4630
+ return iterationsData.flat();
4631
+ };
4632
+ return ExternalApiProvider;
4633
+ }();
4634
+
2611
4635
  var ExistingSwap =
2612
4636
  /**
2613
4637
  * @param swapId {string}
@@ -4580,5 +6604,5 @@ PublicSwapService.PUBLIC_SWAP_DETAILS_FAIL_REASONS = {
4580
6604
  };
4581
6605
  PublicSwapService._fiatDecimalsCount = FiatCurrenciesService.getCurrencyDecimalCountByCode("USD");
4582
6606
 
4583
- export { AmountUtils, AssetIcon, BaseSwapCreationInfo, Blockchain, Button, Cache, Coin, EmailsApi, ExistingSwap, ExistingSwapWithFiatData, FiatCurrenciesService, LoadingDots, Logger, LogsStorage, Protocol, PublicSwapService, SupportChat, SwapProvider, SwapUtils, SwapspaceSwapProvider, improveAndRethrow, safeStringify, useCallHandlingErrors, useReferredState };
6607
+ export { AmountUtils, AssetIcon, AxiosAdapter, BaseSwapCreationInfo, Blockchain, Button, Cache, CacheAndConcurrentRequestsResolver, CachedRobustExternalApiCallerService, CancelProcessing, Coin, EmailsApi, ExistingSwap, ExistingSwapWithFiatData, ExternalApiProvider, FiatCurrenciesService, LoadingDots, Logger, LogsStorage, Protocol, PublicSwapService, RobustExternalAPICallerService, SupportChat, SwapProvider, SwapUtils, SwapspaceSwapProvider, getQueryParameterSingleValue, getQueryParameterValues, handleClickOutside, improveAndRethrow, logErrorOrOutputToConsole, postponeExecution, removeQueryParameterAndValues, safeStringify, saveQueryParameterAndValues, useCallHandlingErrors, useReferredState };
4584
6608
  //# sourceMappingURL=index.module.js.map