@aws-amplify/core 6.0.1-console-preview.5f040a2.0 → 6.0.1-console-preview.23dc225.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/lib/Cache/StorageCache.d.ts +14 -31
  2. package/lib/Cache/StorageCache.js +97 -102
  3. package/lib/Cache/StorageCache.native.d.ts +19 -0
  4. package/lib/Cache/StorageCache.native.js +164 -0
  5. package/lib/Cache/{AsyncStorageCache.d.ts → StorageCacheCommon.d.ts} +124 -99
  6. package/lib/Cache/{AsyncStorageCache.js → StorageCacheCommon.js} +497 -432
  7. package/lib/Cache/constants.d.ts +6 -0
  8. package/lib/Cache/constants.js +17 -0
  9. package/lib/Cache/index.d.ts +2 -0
  10. package/lib/Cache/index.js +7 -0
  11. package/lib/Cache/types/cache.d.ts +38 -0
  12. package/lib/Cache/types/index.d.ts +1 -1
  13. package/lib/Cache/types/index.js +1 -1
  14. package/lib/Cache/{Utils → utils}/CacheList.d.ts +1 -1
  15. package/lib/Cache/{Utils → utils}/CacheList.js +2 -1
  16. package/lib/Cache/utils/cacheHelpers.d.ts +14 -0
  17. package/lib/Cache/utils/cacheHelpers.js +51 -0
  18. package/lib/Cache/{Utils → utils}/errorHelpers.d.ts +0 -1
  19. package/lib/Cache/{Utils → utils}/errorHelpers.js +0 -4
  20. package/lib/Cache/utils/index.d.ts +2 -0
  21. package/lib/Cache/utils/index.js +12 -0
  22. package/lib/Hub/index.d.ts +7 -0
  23. package/lib/Hub/index.js +8 -1
  24. package/lib/Platform/customUserAgent.d.ts +16 -0
  25. package/lib/Platform/customUserAgent.js +70 -0
  26. package/lib/Platform/index.js +10 -1
  27. package/lib/Platform/types.d.ts +33 -1
  28. package/lib/Platform/types.js +1 -0
  29. package/lib/Platform/version.d.ts +1 -1
  30. package/lib/Platform/version.js +1 -1
  31. package/lib/Reachability/Reachability.d.ts +1 -0
  32. package/lib/Reachability/Reachability.js +36 -0
  33. package/lib/Signer/Signer.js +3 -2
  34. package/lib/awsClients/cognitoIdentity/base.js +2 -1
  35. package/lib/awsClients/pinpoint/base.js +2 -1
  36. package/lib/awsClients/pinpoint/getInAppMessages.js +2 -1
  37. package/lib/awsClients/pinpoint/putEvents.js +2 -1
  38. package/lib/awsClients/pinpoint/updateEndpoint.js +2 -1
  39. package/lib/clients/middleware/signing/signer/signatureV4/index.d.ts +0 -1
  40. package/lib/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  41. package/lib/clients/middleware/signing/signer/signatureV4/presignUrl.js +2 -1
  42. package/lib/index.d.ts +2 -5
  43. package/lib/index.js +3 -6
  44. package/lib/libraryUtils.d.ts +7 -5
  45. package/lib/libraryUtils.js +11 -6
  46. package/lib/parseAWSExports.js +75 -14
  47. package/lib/providers/pinpoint/apis/flushEvents.d.ts +2 -2
  48. package/lib/providers/pinpoint/apis/record.js +3 -3
  49. package/lib/providers/pinpoint/apis/updateEndpoint.js +6 -6
  50. package/lib/singleton/API/types.d.ts +4 -3
  51. package/lib/singleton/Amplify.d.ts +2 -2
  52. package/lib/singleton/Amplify.js +6 -5
  53. package/lib/singleton/Auth/types.d.ts +28 -1
  54. package/lib/singleton/Cache/types.d.ts +18 -0
  55. package/lib/singleton/Cache/types.js +4 -0
  56. package/lib/singleton/types.d.ts +3 -1
  57. package/lib/storage/DefaultStorage.js +1 -1
  58. package/lib/storage/utils.d.ts +1 -1
  59. package/lib/storage/utils.js +3 -3
  60. package/lib/tsconfig.tsbuildinfo +1 -1
  61. package/lib/utils/amplifyUrl/index.d.ts +13 -0
  62. package/lib/utils/amplifyUrl/index.js +10 -0
  63. package/lib/utils/amplifyUrl/polyfill.d.ts +0 -0
  64. package/lib/utils/amplifyUrl/polyfill.js +4 -0
  65. package/lib/utils/amplifyUrl/polyfill.native.d.ts +1 -0
  66. package/lib/utils/amplifyUuid/index.d.ts +3 -0
  67. package/lib/utils/amplifyUuid/index.js +9 -0
  68. package/lib/utils/amplifyUuid/polyfill.d.ts +0 -0
  69. package/lib/utils/amplifyUuid/polyfill.js +4 -0
  70. package/lib/utils/amplifyUuid/polyfill.native.d.ts +1 -0
  71. package/lib/utils/amplifyUuid/polyfill.native.js +6 -0
  72. package/lib/utils/deepFreeze.d.ts +1 -0
  73. package/lib/utils/deepFreeze.js +38 -0
  74. package/lib/{ClientDevice/android.d.ts → utils/getClientInfo/getClientInfo.android.d.ts} +1 -1
  75. package/lib/{ClientDevice/android.js → utils/getClientInfo/getClientInfo.android.js} +4 -4
  76. package/lib/{ClientDevice/browser.d.ts → utils/getClientInfo/getClientInfo.d.ts} +1 -9
  77. package/lib/{ClientDevice/ios.d.ts → utils/getClientInfo/getClientInfo.ios.d.ts} +1 -1
  78. package/lib/{ClientDevice/ios.js → utils/getClientInfo/getClientInfo.ios.js} +4 -4
  79. package/lib/{ClientDevice/browser.js → utils/getClientInfo/getClientInfo.js} +6 -18
  80. package/lib/utils/getClientInfo/index.d.ts +1 -0
  81. package/lib/utils/getClientInfo/index.js +7 -0
  82. package/lib/utils/index.d.ts +2 -0
  83. package/lib/utils/index.js +5 -1
  84. package/lib-esm/Cache/StorageCache.d.ts +14 -31
  85. package/lib-esm/Cache/StorageCache.js +97 -102
  86. package/lib-esm/Cache/StorageCache.native.d.ts +19 -0
  87. package/lib-esm/Cache/StorageCache.native.js +161 -0
  88. package/lib-esm/Cache/{AsyncStorageCache.d.ts → StorageCacheCommon.d.ts} +124 -99
  89. package/lib-esm/Cache/{AsyncStorageCache.js → StorageCacheCommon.js} +496 -430
  90. package/lib-esm/Cache/constants.d.ts +6 -0
  91. package/lib-esm/Cache/constants.js +14 -0
  92. package/lib-esm/Cache/index.d.ts +2 -0
  93. package/lib-esm/Cache/index.js +4 -0
  94. package/lib-esm/Cache/types/cache.d.ts +38 -0
  95. package/lib-esm/Cache/types/index.d.ts +1 -1
  96. package/lib-esm/Cache/types/index.js +1 -1
  97. package/lib-esm/Cache/{Utils → utils}/CacheList.d.ts +1 -1
  98. package/lib-esm/Cache/{Utils → utils}/CacheList.js +1 -1
  99. package/lib-esm/Cache/utils/cacheHelpers.d.ts +14 -0
  100. package/lib-esm/Cache/utils/cacheHelpers.js +44 -0
  101. package/lib-esm/Cache/{Utils → utils}/errorHelpers.d.ts +0 -1
  102. package/lib-esm/Cache/{Utils → utils}/errorHelpers.js +0 -4
  103. package/lib-esm/Cache/utils/index.d.ts +2 -0
  104. package/lib-esm/Cache/utils/index.js +4 -0
  105. package/lib-esm/Hub/index.d.ts +7 -0
  106. package/lib-esm/Hub/index.js +7 -0
  107. package/lib-esm/Platform/customUserAgent.d.ts +16 -0
  108. package/lib-esm/Platform/customUserAgent.js +65 -0
  109. package/lib-esm/Platform/index.js +10 -1
  110. package/lib-esm/Platform/types.d.ts +33 -1
  111. package/lib-esm/Platform/types.js +1 -0
  112. package/lib-esm/Platform/version.d.ts +1 -1
  113. package/lib-esm/Platform/version.js +1 -1
  114. package/lib-esm/Reachability/Reachability.d.ts +1 -0
  115. package/lib-esm/Reachability/Reachability.js +36 -0
  116. package/lib-esm/Signer/Signer.js +3 -2
  117. package/lib-esm/awsClients/cognitoIdentity/base.js +2 -1
  118. package/lib-esm/awsClients/pinpoint/base.js +2 -1
  119. package/lib-esm/awsClients/pinpoint/getInAppMessages.js +2 -1
  120. package/lib-esm/awsClients/pinpoint/putEvents.js +2 -1
  121. package/lib-esm/awsClients/pinpoint/updateEndpoint.js +2 -1
  122. package/lib-esm/clients/middleware/signing/signer/signatureV4/index.d.ts +0 -1
  123. package/lib-esm/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  124. package/lib-esm/clients/middleware/signing/signer/signatureV4/presignUrl.js +2 -1
  125. package/lib-esm/index.d.ts +2 -5
  126. package/lib-esm/index.js +1 -4
  127. package/lib-esm/libraryUtils.d.ts +7 -5
  128. package/lib-esm/libraryUtils.js +5 -3
  129. package/lib-esm/parseAWSExports.js +75 -14
  130. package/lib-esm/providers/pinpoint/apis/flushEvents.d.ts +2 -2
  131. package/lib-esm/providers/pinpoint/apis/record.js +3 -3
  132. package/lib-esm/providers/pinpoint/apis/updateEndpoint.js +6 -6
  133. package/lib-esm/singleton/API/types.d.ts +4 -3
  134. package/lib-esm/singleton/Amplify.d.ts +2 -2
  135. package/lib-esm/singleton/Amplify.js +6 -5
  136. package/lib-esm/singleton/Auth/types.d.ts +28 -1
  137. package/lib-esm/singleton/Cache/types.d.ts +18 -0
  138. package/lib-esm/singleton/Cache/types.js +3 -0
  139. package/lib-esm/singleton/types.d.ts +3 -1
  140. package/lib-esm/storage/DefaultStorage.js +2 -2
  141. package/lib-esm/storage/utils.d.ts +1 -1
  142. package/lib-esm/storage/utils.js +1 -1
  143. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  144. package/lib-esm/utils/amplifyUrl/index.d.ts +13 -0
  145. package/lib-esm/utils/amplifyUrl/index.js +6 -0
  146. package/lib-esm/utils/amplifyUuid/index.d.ts +3 -0
  147. package/lib-esm/utils/amplifyUuid/index.js +6 -0
  148. package/lib-esm/utils/amplifyUuid/polyfill.native.js +4 -0
  149. package/lib-esm/utils/deepFreeze.d.ts +1 -0
  150. package/lib-esm/utils/deepFreeze.js +34 -0
  151. package/lib-esm/{ClientDevice/android.d.ts → utils/getClientInfo/getClientInfo.android.d.ts} +1 -1
  152. package/lib-esm/{ClientDevice/android.js → utils/getClientInfo/getClientInfo.android.js} +2 -2
  153. package/lib-esm/{ClientDevice/browser.d.ts → utils/getClientInfo/getClientInfo.d.ts} +1 -9
  154. package/lib-esm/{ClientDevice/ios.d.ts → utils/getClientInfo/getClientInfo.ios.d.ts} +1 -1
  155. package/lib-esm/{ClientDevice/ios.js → utils/getClientInfo/getClientInfo.ios.js} +2 -2
  156. package/lib-esm/{ClientDevice/browser.js → utils/getClientInfo/getClientInfo.js} +4 -14
  157. package/lib-esm/utils/getClientInfo/index.d.ts +1 -0
  158. package/lib-esm/utils/getClientInfo/index.js +3 -0
  159. package/lib-esm/utils/index.d.ts +2 -0
  160. package/lib-esm/utils/index.js +2 -0
  161. package/package.json +7 -17
  162. package/src/Cache/StorageCache.native.ts +65 -0
  163. package/src/Cache/StorageCache.ts +61 -158
  164. package/src/Cache/StorageCacheCommon.ts +581 -0
  165. package/src/Cache/constants.ts +18 -0
  166. package/src/Cache/index.ts +6 -0
  167. package/src/Cache/types/cache.ts +51 -0
  168. package/src/Cache/types/index.ts +1 -1
  169. package/src/Cache/{Utils → utils}/CacheList.ts +185 -185
  170. package/src/Cache/utils/cacheHelpers.ts +52 -0
  171. package/src/Cache/{Utils → utils}/errorHelpers.ts +0 -4
  172. package/src/Cache/{Utils → utils}/index.ts +4 -5
  173. package/src/Hub/index.ts +8 -0
  174. package/src/Platform/customUserAgent.ts +75 -0
  175. package/src/Platform/index.ts +14 -1
  176. package/src/Platform/types.ts +45 -1
  177. package/src/Platform/version.ts +1 -1
  178. package/src/Reachability/Reachability.ts +14 -0
  179. package/src/Signer/Signer.ts +3 -2
  180. package/src/awsClients/cognitoIdentity/base.ts +4 -1
  181. package/src/awsClients/pinpoint/base.ts +2 -1
  182. package/src/awsClients/pinpoint/getInAppMessages.ts +2 -1
  183. package/src/awsClients/pinpoint/putEvents.ts +2 -1
  184. package/src/awsClients/pinpoint/updateEndpoint.ts +2 -1
  185. package/src/clients/middleware/signing/signer/signatureV4/index.ts +0 -2
  186. package/src/clients/middleware/signing/signer/signatureV4/presignUrl.ts +2 -1
  187. package/src/index.ts +3 -4
  188. package/src/libraryUtils.ts +17 -10
  189. package/src/parseAWSExports.ts +76 -13
  190. package/src/providers/pinpoint/apis/flushEvents.ts +2 -2
  191. package/src/providers/pinpoint/apis/record.ts +3 -3
  192. package/src/providers/pinpoint/apis/updateEndpoint.ts +6 -6
  193. package/src/singleton/API/types.ts +4 -3
  194. package/src/singleton/Amplify.ts +10 -8
  195. package/src/singleton/Auth/types.ts +50 -1
  196. package/src/singleton/Cache/types.ts +27 -0
  197. package/src/singleton/types.ts +3 -1
  198. package/src/storage/DefaultStorage.ts +2 -2
  199. package/src/storage/utils.ts +1 -1
  200. package/src/utils/amplifyUrl/index.ts +9 -0
  201. package/src/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.ts → utils/amplifyUrl/polyfill.native.ts} +1 -0
  202. package/src/utils/amplifyUuid/index.ts +9 -0
  203. package/src/utils/amplifyUuid/polyfill.native.ts +6 -0
  204. package/src/utils/amplifyUuid/polyfill.ts +4 -0
  205. package/src/utils/deepFreeze.ts +16 -0
  206. package/src/{ClientDevice/android.ts → utils/getClientInfo/getClientInfo.android.ts} +2 -2
  207. package/src/{ClientDevice/ios.ts → utils/getClientInfo/getClientInfo.ios.ts} +3 -3
  208. package/src/{ClientDevice/browser.ts → utils/getClientInfo/getClientInfo.ts} +4 -16
  209. package/src/utils/getClientInfo/index.ts +4 -0
  210. package/src/utils/index.ts +2 -0
  211. package/lib/Cache/BrowserStorageCache.d.ts +0 -166
  212. package/lib/Cache/BrowserStorageCache.js +0 -456
  213. package/lib/Cache/InMemoryCache.d.ts +0 -129
  214. package/lib/Cache/InMemoryCache.js +0 -342
  215. package/lib/Cache/Utils/CacheUtils.d.ts +0 -25
  216. package/lib/Cache/Utils/CacheUtils.js +0 -86
  217. package/lib/Cache/Utils/index.d.ts +0 -2
  218. package/lib/Cache/Utils/index.js +0 -16
  219. package/lib/Cache/reactnative.d.ts +0 -3
  220. package/lib/Cache/reactnative.js +0 -8
  221. package/lib/Cache/types/Cache.d.ts +0 -55
  222. package/lib/ClientDevice/index.d.ts +0 -23
  223. package/lib/ClientDevice/index.js +0 -18
  224. package/lib/ClientDevice/reactnative.d.ts +0 -7
  225. package/lib/ClientDevice/reactnative.js +0 -24
  226. package/lib-esm/Cache/BrowserStorageCache.d.ts +0 -166
  227. package/lib-esm/Cache/BrowserStorageCache.js +0 -453
  228. package/lib-esm/Cache/InMemoryCache.d.ts +0 -129
  229. package/lib-esm/Cache/InMemoryCache.js +0 -339
  230. package/lib-esm/Cache/Utils/CacheUtils.d.ts +0 -25
  231. package/lib-esm/Cache/Utils/CacheUtils.js +0 -79
  232. package/lib-esm/Cache/Utils/index.d.ts +0 -2
  233. package/lib-esm/Cache/Utils/index.js +0 -4
  234. package/lib-esm/Cache/reactnative.d.ts +0 -3
  235. package/lib-esm/Cache/reactnative.js +0 -6
  236. package/lib-esm/Cache/types/Cache.d.ts +0 -55
  237. package/lib-esm/ClientDevice/index.d.ts +0 -23
  238. package/lib-esm/ClientDevice/index.js +0 -15
  239. package/lib-esm/ClientDevice/reactnative.d.ts +0 -7
  240. package/lib-esm/ClientDevice/reactnative.js +0 -21
  241. package/src/Cache/AsyncStorageCache.ts +0 -495
  242. package/src/Cache/BrowserStorageCache.ts +0 -504
  243. package/src/Cache/CHANGELOG.md +0 -1239
  244. package/src/Cache/InMemoryCache.ts +0 -347
  245. package/src/Cache/Utils/CacheUtils.ts +0 -90
  246. package/src/Cache/reactnative.ts +0 -9
  247. package/src/Cache/types/Cache.ts +0 -75
  248. package/src/ClientDevice/index.ts +0 -14
  249. package/src/ClientDevice/reactnative.ts +0 -18
  250. package/lib/Cache/types/{Cache.js → cache.js} +0 -0
  251. package/lib/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.js → utils/amplifyUrl/polyfill.native.js} +1 -1
  252. /package/lib-esm/Cache/types/{Cache.js → cache.js} +0 -0
  253. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.d.ts → utils/amplifyUrl/polyfill.d.ts} +0 -0
  254. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.js → utils/amplifyUrl/polyfill.js} +0 -0
  255. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.d.ts → utils/amplifyUrl/polyfill.native.d.ts} +0 -0
  256. /package/lib-esm/{clients/middleware/signing/signer/signatureV4/polyfills/index.native.js → utils/amplifyUrl/polyfill.native.js} +0 -0
  257. /package/{lib/clients/middleware/signing/signer/signatureV4/polyfills/index.d.ts → lib-esm/utils/amplifyUuid/polyfill.d.ts} +0 -0
  258. /package/{lib/clients/middleware/signing/signer/signatureV4/polyfills/index.js → lib-esm/utils/amplifyUuid/polyfill.js} +0 -0
  259. /package/{lib/clients/middleware/signing/signer/signatureV4/polyfills/index.native.d.ts → lib-esm/utils/amplifyUuid/polyfill.native.d.ts} +0 -0
  260. /package/src/{clients/middleware/signing/signer/signatureV4/polyfills/index.ts → utils/amplifyUrl/polyfill.ts} +0 -0
@@ -1,20 +1,16 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- var __extends = (this && this.__extends) || (function () {
4
- var extendStatics = function (d, b) {
5
- extendStatics = Object.setPrototypeOf ||
6
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
8
- return extendStatics(d, b);
9
- };
10
- return function (d, b) {
11
- if (typeof b !== "function" && b !== null)
12
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
13
- extendStatics(d, b);
14
- function __() { this.constructor = d; }
15
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
3
+ var __assign = (this && this.__assign) || function () {
4
+ __assign = Object.assign || function(t) {
5
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
6
+ s = arguments[i];
7
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8
+ t[p] = s[p];
9
+ }
10
+ return t;
16
11
  };
17
- })();
12
+ return __assign.apply(this, arguments);
13
+ };
18
14
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
15
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
16
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -51,114 +47,326 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
51
47
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52
48
  }
53
49
  };
54
- import { loadAsyncStorage } from '@aws-amplify/react-native';
50
+ var __values = (this && this.__values) || function(o) {
51
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
52
+ if (m) return m.call(o);
53
+ if (o && typeof o.length === "number") return {
54
+ next: function () {
55
+ if (o && i >= o.length) o = void 0;
56
+ return { value: o && o[i++], done: !o };
57
+ }
58
+ };
59
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
60
+ };
61
+ import { Amplify } from '../singleton';
55
62
  import { ConsoleLogger as Logger } from '../Logger';
56
- import { StorageCache } from './StorageCache';
57
- import { defaultConfig, getCurrTime } from './Utils';
58
- import { getCurrSizeKey } from './Utils/CacheUtils';
59
- import { assert, CacheErrorCode } from './Utils/errorHelpers';
60
- var logger = new Logger('AsyncStorageCache');
61
- var AsyncStorage = loadAsyncStorage();
62
- /*
63
- * Customized cache which based on the AsyncStorage with LRU implemented
63
+ import { currentSizeKey, defaultConfig } from './constants';
64
+ import { getCurrentSizeKey, getCurrentTime, getByteLength } from './utils';
65
+ import { assert, CacheErrorCode } from './utils/errorHelpers';
66
+ var logger = new Logger('StorageCache');
67
+ /**
68
+ * Initialization of the cache
69
+ *
64
70
  */
65
- var AsyncStorageCache = /** @class */ (function (_super) {
66
- __extends(AsyncStorageCache, _super);
71
+ var StorageCacheCommon = /** @class */ (function () {
67
72
  /**
68
- * initialize the cache
73
+ * Initialize the cache
69
74
  *
70
- * @param {Object} config - the configuration of the cache
75
+ * @param config - Custom configuration for this instance.
71
76
  */
72
- function AsyncStorageCache(config) {
73
- var _this = _super.call(this, config) || this;
74
- _this.getItem = _this.getItem.bind(_this);
75
- _this.setItem = _this.setItem.bind(_this);
76
- _this.removeItem = _this.removeItem.bind(_this);
77
- logger.debug('Using AsyncStorageCache');
78
- return _this;
77
+ function StorageCacheCommon(_a) {
78
+ var config = _a.config, keyValueStorage = _a.keyValueStorage;
79
+ var _b;
80
+ var globalCacheConfig = (_b = Amplify.getConfig().Cache) !== null && _b !== void 0 ? _b : {};
81
+ this.config = __assign(__assign(__assign({}, defaultConfig), globalCacheConfig), config);
82
+ this.keyValueStorage = keyValueStorage;
83
+ this.sanitizeConfig();
79
84
  }
85
+ StorageCacheCommon.prototype.getModuleName = function () {
86
+ return 'Cache';
87
+ };
80
88
  /**
81
- * decrease current size of the cache
82
- * @private
83
- * @param amount - the amount of the cache size which needs to be decreased
89
+ * Set custom configuration for the cache instance.
90
+ *
91
+ * @param config - customized configuration (without keyPrefix, which can't be changed)
92
+ *
93
+ * @return - the current configuration
84
94
  */
85
- AsyncStorageCache.prototype._decreaseCurSizeInBytes = function (amount) {
95
+ StorageCacheCommon.prototype.configure = function (config) {
96
+ if (config) {
97
+ if (config.keyPrefix) {
98
+ logger.warn('keyPrefix can not be re-configured on an existing Cache instance.');
99
+ }
100
+ this.config = __assign(__assign({}, this.config), config);
101
+ }
102
+ this.sanitizeConfig();
103
+ return this.config;
104
+ };
105
+ /**
106
+ * return the current size of the cache
107
+ * @return {Promise}
108
+ */
109
+ StorageCacheCommon.prototype.getCurrentCacheSize = function () {
86
110
  return __awaiter(this, void 0, void 0, function () {
87
- var curSize;
111
+ var size;
88
112
  return __generator(this, function (_a) {
89
113
  switch (_a.label) {
90
- case 0: return [4 /*yield*/, this.getCacheCurSize()];
114
+ case 0: return [4 /*yield*/, this.getStorage().getItem(getCurrentSizeKey(this.config.keyPrefix))];
91
115
  case 1:
92
- curSize = _a.sent();
93
- return [4 /*yield*/, AsyncStorage.setItem(getCurrSizeKey(this.cacheConfig.keyPrefix), (curSize - amount).toString())];
116
+ size = _a.sent();
117
+ if (!!size) return [3 /*break*/, 3];
118
+ return [4 /*yield*/, this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), '0')];
94
119
  case 2:
95
120
  _a.sent();
96
- return [2 /*return*/];
121
+ size = '0';
122
+ _a.label = 3;
123
+ case 3: return [2 /*return*/, Number(size)];
97
124
  }
98
125
  });
99
126
  });
100
127
  };
101
128
  /**
102
- * increase current size of the cache
103
- * @private
104
- * @param amount - the amount of the cache szie which need to be increased
129
+ * Set item into cache. You can put number, string, boolean or object.
130
+ * The cache will first check whether has the same key.
131
+ * If it has, it will delete the old item and then put the new item in
132
+ * The cache will pop out items if it is full
133
+ * You can specify the cache item options. The cache will abort and output a warning:
134
+ * If the key is invalid
135
+ * If the size of the item exceeds itemMaxSize.
136
+ * If the value is undefined
137
+ * If incorrect cache item configuration
138
+ * If error happened with browser storage
139
+ *
140
+ * @param {String} key - the key of the item
141
+ * @param {Object} value - the value of the item
142
+ * @param {Object} [options] - optional, the specified meta-data
143
+ *
144
+ * @return {Promise}
105
145
  */
106
- AsyncStorageCache.prototype._increaseCurSizeInBytes = function (amount) {
146
+ StorageCacheCommon.prototype.setItem = function (key, value, options) {
107
147
  return __awaiter(this, void 0, void 0, function () {
108
- var curSize;
148
+ var cacheItemOptions, prefixedKey, item, val, validKeys, sizeToPop, e_1;
109
149
  return __generator(this, function (_a) {
110
150
  switch (_a.label) {
111
- case 0: return [4 /*yield*/, this.getCacheCurSize()];
151
+ case 0:
152
+ logger.debug("Set item: key is ".concat(key, ", value is ").concat(value, " with options: ").concat(options));
153
+ if (!key || key === currentSizeKey) {
154
+ logger.warn("Invalid key: should not be empty or reserved key: '".concat(currentSizeKey, "'"));
155
+ return [2 /*return*/];
156
+ }
157
+ if (typeof value === 'undefined') {
158
+ logger.warn("The value of item should not be undefined!");
159
+ return [2 /*return*/];
160
+ }
161
+ cacheItemOptions = {
162
+ priority: (options === null || options === void 0 ? void 0 : options.priority) !== undefined
163
+ ? options.priority
164
+ : this.config.defaultPriority,
165
+ expires: (options === null || options === void 0 ? void 0 : options.expires) !== undefined
166
+ ? options.expires
167
+ : this.config.defaultTTL + getCurrentTime(),
168
+ };
169
+ if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
170
+ logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
171
+ return [2 /*return*/];
172
+ }
173
+ prefixedKey = "".concat(this.config.keyPrefix).concat(key);
174
+ item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
175
+ // check whether this item is too big;
176
+ if (item.byteSize > this.config.itemMaxSize) {
177
+ logger.warn("Item with key: ".concat(key, " you are trying to put into is too big!"));
178
+ return [2 /*return*/];
179
+ }
180
+ _a.label = 1;
112
181
  case 1:
113
- curSize = _a.sent();
114
- return [4 /*yield*/, AsyncStorage.setItem(getCurrSizeKey(this.cacheConfig.keyPrefix), (curSize + amount).toString())];
182
+ _a.trys.push([1, 11, , 12]);
183
+ return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
115
184
  case 2:
185
+ val = _a.sent();
186
+ if (!val) return [3 /*break*/, 4];
187
+ return [4 /*yield*/, this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize)];
188
+ case 3:
116
189
  _a.sent();
117
- return [2 /*return*/];
190
+ _a.label = 4;
191
+ case 4: return [4 /*yield*/, this.isCacheFull(item.byteSize)];
192
+ case 5:
193
+ if (!_a.sent()) return [3 /*break*/, 10];
194
+ return [4 /*yield*/, this.clearInvalidAndGetRemainingKeys()];
195
+ case 6:
196
+ validKeys = _a.sent();
197
+ return [4 /*yield*/, this.isCacheFull(item.byteSize)];
198
+ case 7:
199
+ if (!_a.sent()) return [3 /*break*/, 10];
200
+ return [4 /*yield*/, this.sizeToPop(item.byteSize)];
201
+ case 8:
202
+ sizeToPop = _a.sent();
203
+ return [4 /*yield*/, this.popOutItems(validKeys, sizeToPop)];
204
+ case 9:
205
+ _a.sent();
206
+ _a.label = 10;
207
+ case 10:
208
+ // put item in the cache
209
+ return [2 /*return*/, this.setCacheItem(prefixedKey, item)];
210
+ case 11:
211
+ e_1 = _a.sent();
212
+ logger.warn("setItem failed! ".concat(e_1));
213
+ return [3 /*break*/, 12];
214
+ case 12: return [2 /*return*/];
118
215
  }
119
216
  });
120
217
  });
121
218
  };
122
219
  /**
123
- * update the visited time if item has been visited
124
- * @private
125
- * @param item - the item which need to be refreshed
126
- * @param prefixedKey - the key of the item
220
+ * Get item from cache. It will return null if item doesn’t exist or it has been expired.
221
+ * If you specified callback function in the options,
222
+ * then the function will be executed if no such item in the cache
223
+ * and finally put the return value into cache.
224
+ * Please make sure the callback function will return the value you want to put into the cache.
225
+ * The cache will abort output a warning:
226
+ * If the key is invalid
227
+ * If error happened with AsyncStorage
228
+ *
229
+ * @param {String} key - the key of the item
230
+ * @param {Object} [options] - the options of callback function
127
231
  *
128
- * @return the refreshed item
232
+ * @return {Promise} - return a promise resolves to be the value of the item
129
233
  */
130
- AsyncStorageCache.prototype._refreshItem = function (item, prefixedKey) {
234
+ StorageCacheCommon.prototype.getItem = function (key, options) {
131
235
  return __awaiter(this, void 0, void 0, function () {
236
+ var cached, prefixedKey, item, val, e_2;
132
237
  return __generator(this, function (_a) {
133
238
  switch (_a.label) {
134
239
  case 0:
135
- item.visitedTime = getCurrTime();
136
- return [4 /*yield*/, AsyncStorage.setItem(prefixedKey, JSON.stringify(item))];
240
+ logger.debug("Get item: key is ".concat(key, " with options ").concat(options));
241
+ if (!key || key === currentSizeKey) {
242
+ logger.warn("Invalid key: should not be empty or reserved key: '".concat(currentSizeKey, "'"));
243
+ return [2 /*return*/, null];
244
+ }
245
+ prefixedKey = "".concat(this.config.keyPrefix).concat(key);
246
+ _a.label = 1;
137
247
  case 1:
248
+ _a.trys.push([1, 11, , 12]);
249
+ return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
250
+ case 2:
251
+ cached = _a.sent();
252
+ if (!(cached != null)) return [3 /*break*/, 7];
253
+ return [4 /*yield*/, this.isExpired(prefixedKey)];
254
+ case 3:
255
+ if (!_a.sent()) return [3 /*break*/, 5];
256
+ // if expired, remove that item and return null
257
+ return [4 /*yield*/, this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize)];
258
+ case 4:
259
+ // if expired, remove that item and return null
138
260
  _a.sent();
139
- return [2 /*return*/, item];
261
+ return [3 /*break*/, 7];
262
+ case 5: return [4 /*yield*/, this.updateVisitedTime(JSON.parse(cached), prefixedKey)];
263
+ case 6:
264
+ item = _a.sent();
265
+ return [2 /*return*/, item.data];
266
+ case 7:
267
+ if (!(options === null || options === void 0 ? void 0 : options.callback)) return [3 /*break*/, 10];
268
+ val = options.callback();
269
+ if (!(val !== null)) return [3 /*break*/, 9];
270
+ return [4 /*yield*/, this.setItem(key, val, options)];
271
+ case 8:
272
+ _a.sent();
273
+ _a.label = 9;
274
+ case 9: return [2 /*return*/, val];
275
+ case 10: return [2 /*return*/, null];
276
+ case 11:
277
+ e_2 = _a.sent();
278
+ logger.warn("getItem failed! ".concat(e_2));
279
+ return [2 /*return*/, null];
280
+ case 12: return [2 /*return*/];
140
281
  }
141
282
  });
142
283
  });
143
284
  };
144
285
  /**
145
- * check wether item is expired
146
- * @private
286
+ * remove item from the cache
287
+ * The cache will abort output a warning:
288
+ * If error happened with AsyncStorage
289
+ * @param {String} key - the key of the item
290
+ * @return {Promise}
291
+ */
292
+ StorageCacheCommon.prototype.removeItem = function (key) {
293
+ return __awaiter(this, void 0, void 0, function () {
294
+ var prefixedKey, val, e_3;
295
+ return __generator(this, function (_a) {
296
+ switch (_a.label) {
297
+ case 0:
298
+ logger.debug("Remove item: key is ".concat(key));
299
+ if (!key || key === currentSizeKey) {
300
+ logger.warn("Invalid key: should not be empty or reserved key: '".concat(currentSizeKey, "'"));
301
+ return [2 /*return*/];
302
+ }
303
+ prefixedKey = "".concat(this.config.keyPrefix).concat(key);
304
+ _a.label = 1;
305
+ case 1:
306
+ _a.trys.push([1, 5, , 6]);
307
+ return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
308
+ case 2:
309
+ val = _a.sent();
310
+ if (!val) return [3 /*break*/, 4];
311
+ return [4 /*yield*/, this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize)];
312
+ case 3:
313
+ _a.sent();
314
+ _a.label = 4;
315
+ case 4: return [3 /*break*/, 6];
316
+ case 5:
317
+ e_3 = _a.sent();
318
+ logger.warn("removeItem failed! ".concat(e_3));
319
+ return [3 /*break*/, 6];
320
+ case 6: return [2 /*return*/];
321
+ }
322
+ });
323
+ });
324
+ };
325
+ /**
326
+ * Return all the keys owned by this cache.
327
+ * Will return an empty array if error occurred.
328
+ *
329
+ * @return {Promise}
330
+ */
331
+ StorageCacheCommon.prototype.getAllKeys = function () {
332
+ return __awaiter(this, void 0, void 0, function () {
333
+ var e_4;
334
+ return __generator(this, function (_a) {
335
+ switch (_a.label) {
336
+ case 0:
337
+ _a.trys.push([0, 2, , 3]);
338
+ return [4 /*yield*/, this.getAllCacheKeys()];
339
+ case 1: return [2 /*return*/, _a.sent()];
340
+ case 2:
341
+ e_4 = _a.sent();
342
+ logger.warn("getAllkeys failed! ".concat(e_4));
343
+ return [2 /*return*/, []];
344
+ case 3: return [2 /*return*/];
345
+ }
346
+ });
347
+ });
348
+ };
349
+ StorageCacheCommon.prototype.getStorage = function () {
350
+ return this.keyValueStorage;
351
+ };
352
+ /**
353
+ * check whether item is expired
354
+ *
147
355
  * @param key - the key of the item
148
356
  *
149
357
  * @return true if the item is expired.
150
358
  */
151
- AsyncStorageCache.prototype._isExpired = function (key) {
359
+ StorageCacheCommon.prototype.isExpired = function (key) {
152
360
  return __awaiter(this, void 0, void 0, function () {
153
361
  var text, item;
154
362
  return __generator(this, function (_a) {
155
363
  switch (_a.label) {
156
- case 0: return [4 /*yield*/, AsyncStorage.getItem(key)];
364
+ case 0: return [4 /*yield*/, this.getStorage().getItem(key)];
157
365
  case 1:
158
366
  text = _a.sent();
159
367
  assert(text !== null, CacheErrorCode.NoCacheItem, "Key: ".concat(key));
160
368
  item = JSON.parse(text);
161
- if (getCurrTime() >= item.expires) {
369
+ if (getCurrentTime() >= item.expires) {
162
370
  return [2 /*return*/, true];
163
371
  }
164
372
  return [2 /*return*/, false];
@@ -168,36 +376,36 @@ var AsyncStorageCache = /** @class */ (function (_super) {
168
376
  };
169
377
  /**
170
378
  * delete item from cache
171
- * @private
379
+ *
172
380
  * @param prefixedKey - the key of the item
173
381
  * @param size - optional, the byte size of the item
174
382
  */
175
- AsyncStorageCache.prototype._removeItem = function (prefixedKey, size) {
383
+ StorageCacheCommon.prototype.removeCacheItem = function (prefixedKey, size) {
176
384
  return __awaiter(this, void 0, void 0, function () {
177
- var config, itemSize, removeItemError_1;
385
+ var item, itemSize, removeItemError_1;
178
386
  return __generator(this, function (_a) {
179
387
  switch (_a.label) {
180
- case 0: return [4 /*yield*/, AsyncStorage.getItem(prefixedKey)];
388
+ case 0: return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
181
389
  case 1:
182
- config = _a.sent();
183
- assert(!!config, CacheErrorCode.NoCacheItem, "Key: ".concat(prefixedKey));
184
- itemSize = size !== null && size !== void 0 ? size : JSON.parse(config).byteSize;
390
+ item = _a.sent();
391
+ assert(item !== null, CacheErrorCode.NoCacheItem, "Key: ".concat(prefixedKey));
392
+ itemSize = size !== null && size !== void 0 ? size : JSON.parse(item).byteSize;
185
393
  // first try to update the current size of the cache
186
- return [4 /*yield*/, this._decreaseCurSizeInBytes(itemSize)];
394
+ return [4 /*yield*/, this.decreaseCurrentSizeInBytes(itemSize)];
187
395
  case 2:
188
396
  // first try to update the current size of the cache
189
397
  _a.sent();
190
398
  _a.label = 3;
191
399
  case 3:
192
400
  _a.trys.push([3, 5, , 7]);
193
- return [4 /*yield*/, AsyncStorage.removeItem(prefixedKey)];
401
+ return [4 /*yield*/, this.getStorage().removeItem(prefixedKey)];
194
402
  case 4:
195
403
  _a.sent();
196
404
  return [3 /*break*/, 7];
197
405
  case 5:
198
406
  removeItemError_1 = _a.sent();
199
407
  // if some error happened, we need to rollback the current size
200
- return [4 /*yield*/, this._increaseCurSizeInBytes(itemSize)];
408
+ return [4 /*yield*/, this.increaseCurrentSizeInBytes(itemSize)];
201
409
  case 6:
202
410
  // if some error happened, we need to rollback the current size
203
411
  _a.sent();
@@ -208,35 +416,145 @@ var AsyncStorageCache = /** @class */ (function (_super) {
208
416
  });
209
417
  });
210
418
  };
419
+ /**
420
+ * produce a JSON object with meta-data and data value
421
+ * @param value - the value of the item
422
+ * @param options - optional, the specified meta-data
423
+ *
424
+ * @return - the item which has the meta-data and the value
425
+ */
426
+ StorageCacheCommon.prototype.fillCacheItem = function (key, value, options) {
427
+ var _a, _b;
428
+ var item = {
429
+ key: key,
430
+ data: value,
431
+ timestamp: getCurrentTime(),
432
+ visitedTime: getCurrentTime(),
433
+ priority: (_a = options.priority) !== null && _a !== void 0 ? _a : 0,
434
+ expires: (_b = options.expires) !== null && _b !== void 0 ? _b : 0,
435
+ type: typeof value,
436
+ byteSize: 0,
437
+ };
438
+ // calculate byte size
439
+ item.byteSize = getByteLength(JSON.stringify(item));
440
+ // re-calculate using cache item with updated byteSize property
441
+ item.byteSize = getByteLength(JSON.stringify(item));
442
+ return item;
443
+ };
444
+ StorageCacheCommon.prototype.sanitizeConfig = function () {
445
+ if (this.config.itemMaxSize > this.config.capacityInBytes) {
446
+ logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');
447
+ this.config.itemMaxSize = defaultConfig.itemMaxSize;
448
+ }
449
+ if (this.config.defaultPriority > 5 || this.config.defaultPriority < 1) {
450
+ logger.error('Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default.');
451
+ this.config.defaultPriority = defaultConfig.defaultPriority;
452
+ }
453
+ if (Number(this.config.warningThreshold) > 1 ||
454
+ Number(this.config.warningThreshold) < 0) {
455
+ logger.error('Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default.');
456
+ this.config.warningThreshold = defaultConfig.warningThreshold;
457
+ }
458
+ // Set 5MB limit
459
+ var cacheLimit = 5 * 1024 * 1024;
460
+ if (this.config.capacityInBytes > cacheLimit) {
461
+ logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');
462
+ this.config.capacityInBytes = defaultConfig.capacityInBytes;
463
+ }
464
+ };
465
+ /**
466
+ * increase current size of the cache
467
+ *
468
+ * @param amount - the amount of the cache szie which need to be increased
469
+ */
470
+ StorageCacheCommon.prototype.increaseCurrentSizeInBytes = function (amount) {
471
+ return __awaiter(this, void 0, void 0, function () {
472
+ var size;
473
+ return __generator(this, function (_a) {
474
+ switch (_a.label) {
475
+ case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
476
+ case 1:
477
+ size = _a.sent();
478
+ return [4 /*yield*/, this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size + amount).toString())];
479
+ case 2:
480
+ _a.sent();
481
+ return [2 /*return*/];
482
+ }
483
+ });
484
+ });
485
+ };
486
+ /**
487
+ * decrease current size of the cache
488
+ *
489
+ * @param amount - the amount of the cache size which needs to be decreased
490
+ */
491
+ StorageCacheCommon.prototype.decreaseCurrentSizeInBytes = function (amount) {
492
+ return __awaiter(this, void 0, void 0, function () {
493
+ var size;
494
+ return __generator(this, function (_a) {
495
+ switch (_a.label) {
496
+ case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
497
+ case 1:
498
+ size = _a.sent();
499
+ return [4 /*yield*/, this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size - amount).toString())];
500
+ case 2:
501
+ _a.sent();
502
+ return [2 /*return*/];
503
+ }
504
+ });
505
+ });
506
+ };
507
+ /**
508
+ * update the visited time if item has been visited
509
+ *
510
+ * @param item - the item which need to be updated
511
+ * @param prefixedKey - the key of the item
512
+ *
513
+ * @return the updated item
514
+ */
515
+ StorageCacheCommon.prototype.updateVisitedTime = function (item, prefixedKey) {
516
+ return __awaiter(this, void 0, void 0, function () {
517
+ return __generator(this, function (_a) {
518
+ switch (_a.label) {
519
+ case 0:
520
+ item.visitedTime = getCurrentTime();
521
+ return [4 /*yield*/, this.getStorage().setItem(prefixedKey, JSON.stringify(item))];
522
+ case 1:
523
+ _a.sent();
524
+ return [2 /*return*/, item];
525
+ }
526
+ });
527
+ });
528
+ };
211
529
  /**
212
530
  * put item into cache
213
- * @private
531
+ *
214
532
  * @param prefixedKey - the key of the item
215
533
  * @param itemData - the value of the item
216
534
  * @param itemSizeInBytes - the byte size of the item
217
535
  */
218
- AsyncStorageCache.prototype._setItem = function (prefixedKey, item) {
536
+ StorageCacheCommon.prototype.setCacheItem = function (prefixedKey, item) {
219
537
  return __awaiter(this, void 0, void 0, function () {
220
538
  var setItemErr_1;
221
539
  return __generator(this, function (_a) {
222
540
  switch (_a.label) {
223
541
  case 0:
224
542
  // first try to update the current size of the cache.
225
- return [4 /*yield*/, this._increaseCurSizeInBytes(item.byteSize)];
543
+ return [4 /*yield*/, this.increaseCurrentSizeInBytes(item.byteSize)];
226
544
  case 1:
227
545
  // first try to update the current size of the cache.
228
546
  _a.sent();
229
547
  _a.label = 2;
230
548
  case 2:
231
549
  _a.trys.push([2, 4, , 6]);
232
- return [4 /*yield*/, AsyncStorage.setItem(prefixedKey, JSON.stringify(item))];
550
+ return [4 /*yield*/, this.getStorage().setItem(prefixedKey, JSON.stringify(item))];
233
551
  case 3:
234
552
  _a.sent();
235
553
  return [3 /*break*/, 6];
236
554
  case 4:
237
555
  setItemErr_1 = _a.sent();
238
556
  // if some error happened, we need to rollback the current size
239
- return [4 /*yield*/, this._decreaseCurSizeInBytes(item.byteSize)];
557
+ return [4 /*yield*/, this.decreaseCurrentSizeInBytes(item.byteSize)];
240
558
  case 5:
241
559
  // if some error happened, we need to rollback the current size
242
560
  _a.sent();
@@ -249,23 +567,21 @@ var AsyncStorageCache = /** @class */ (function (_super) {
249
567
  };
250
568
  /**
251
569
  * total space needed when poping out items
252
- * @private
570
+ *
253
571
  * @param itemSize
254
572
  *
255
573
  * @return total space needed
256
574
  */
257
- AsyncStorageCache.prototype._sizeToPop = function (itemSize) {
575
+ StorageCacheCommon.prototype.sizeToPop = function (itemSize) {
258
576
  return __awaiter(this, void 0, void 0, function () {
259
- var spaceItemNeed, cacheThresholdSpace;
577
+ var cur, spaceItemNeed, cacheThresholdSpace;
260
578
  return __generator(this, function (_a) {
261
579
  switch (_a.label) {
262
- case 0: return [4 /*yield*/, this.getCacheCurSize()];
580
+ case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
263
581
  case 1:
264
- spaceItemNeed = (_a.sent()) +
265
- itemSize -
266
- this.cacheConfig.capacityInBytes;
267
- cacheThresholdSpace = (1 - this.cacheConfig.warningThreshold) *
268
- this.cacheConfig.capacityInBytes;
582
+ cur = _a.sent();
583
+ spaceItemNeed = cur + itemSize - this.config.capacityInBytes;
584
+ cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
269
585
  return [2 /*return*/, spaceItemNeed > cacheThresholdSpace
270
586
  ? spaceItemNeed
271
587
  : cacheThresholdSpace];
@@ -275,63 +591,20 @@ var AsyncStorageCache = /** @class */ (function (_super) {
275
591
  };
276
592
  /**
277
593
  * see whether cache is full
278
- * @private
594
+ *
279
595
  * @param itemSize
280
596
  *
281
597
  * @return true if cache is full
282
598
  */
283
- AsyncStorageCache.prototype._isCacheFull = function (itemSize) {
599
+ StorageCacheCommon.prototype.isCacheFull = function (itemSize) {
284
600
  return __awaiter(this, void 0, void 0, function () {
285
- var _a;
286
- return __generator(this, function (_b) {
287
- switch (_b.label) {
288
- case 0:
289
- _a = itemSize;
290
- return [4 /*yield*/, this.getCacheCurSize()];
291
- case 1: return [2 /*return*/, (_a + (_b.sent()) >
292
- this.cacheConfig.capacityInBytes)];
293
- }
294
- });
295
- });
296
- };
297
- /**
298
- * scan the storage and find out all the keys owned by this cache
299
- * also clean the expired keys while scanning
300
- * @private
301
- * @return array of keys
302
- */
303
- AsyncStorageCache.prototype._findValidKeys = function () {
304
- return __awaiter(this, void 0, void 0, function () {
305
- var keys, keyInCache, i, key;
601
+ var cur;
306
602
  return __generator(this, function (_a) {
307
603
  switch (_a.label) {
308
- case 0:
309
- keys = [];
310
- keyInCache = [];
311
- return [4 /*yield*/, AsyncStorage.getAllKeys()];
604
+ case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
312
605
  case 1:
313
- keyInCache = _a.sent();
314
- i = 0;
315
- _a.label = 2;
316
- case 2:
317
- if (!(i < keyInCache.length)) return [3 /*break*/, 7];
318
- key = keyInCache[i];
319
- if (!(key.indexOf(this.cacheConfig.keyPrefix) === 0 &&
320
- key !== getCurrSizeKey(this.cacheConfig.keyPrefix))) return [3 /*break*/, 6];
321
- return [4 /*yield*/, this._isExpired(key)];
322
- case 3:
323
- if (!_a.sent()) return [3 /*break*/, 5];
324
- return [4 /*yield*/, this._removeItem(key)];
325
- case 4:
326
- _a.sent();
327
- return [3 /*break*/, 6];
328
- case 5:
329
- keys.push(key);
330
- _a.label = 6;
331
- case 6:
332
- i += 1;
333
- return [3 /*break*/, 2];
334
- case 7: return [2 /*return*/, keys];
606
+ cur = _a.sent();
607
+ return [2 /*return*/, itemSize + cur > this.config.capacityInBytes];
335
608
  }
336
609
  });
337
610
  });
@@ -344,7 +617,7 @@ var AsyncStorageCache = /** @class */ (function (_super) {
344
617
  * @param keys - all the keys in this cache
345
618
  * @param sizeToPop - the total size of the items which needed to be poped out
346
619
  */
347
- AsyncStorageCache.prototype._popOutItems = function (keys, sizeToPop) {
620
+ StorageCacheCommon.prototype.popOutItems = function (keys, sizeToPop) {
348
621
  return __awaiter(this, void 0, void 0, function () {
349
622
  var items, remainedSize, i, val, item, i;
350
623
  return __generator(this, function (_a) {
@@ -356,7 +629,7 @@ var AsyncStorageCache = /** @class */ (function (_super) {
356
629
  _a.label = 1;
357
630
  case 1:
358
631
  if (!(i < keys.length)) return [3 /*break*/, 4];
359
- return [4 /*yield*/, AsyncStorage.getItem(keys[i])];
632
+ return [4 /*yield*/, this.getStorage().getItem(keys[i])];
360
633
  case 2:
361
634
  val = _a.sent();
362
635
  if (val != null) {
@@ -390,7 +663,7 @@ var AsyncStorageCache = /** @class */ (function (_super) {
390
663
  case 5:
391
664
  if (!(i < items.length)) return [3 /*break*/, 8];
392
665
  // pop out items until we have enough room for new item
393
- return [4 /*yield*/, this._removeItem(items[i].key, items[i].byteSize)];
666
+ return [4 /*yield*/, this.removeCacheItem(items[i].key, items[i].byteSize)];
394
667
  case 6:
395
668
  // pop out items until we have enough room for new item
396
669
  _a.sent();
@@ -408,324 +681,117 @@ var AsyncStorageCache = /** @class */ (function (_super) {
408
681
  });
409
682
  };
410
683
  /**
411
- * Set item into cache. You can put number, string, boolean or object.
412
- * The cache will first check whether has the same key.
413
- * If it has, it will delete the old item and then put the new item in
414
- * The cache will pop out items if it is full
415
- * You can specify the cache item options. The cache will abort and output a warning:
416
- * If the key is invalid
417
- * If the size of the item exceeds itemMaxSize.
418
- * If the value is undefined
419
- * If incorrect cache item configuration
420
- * If error happened with browser storage
684
+ * Scan the storage and combine the following operations for efficiency
685
+ * 1. Clear out all expired keys owned by this cache, not including the size key.
686
+ * 2. Return the remaining keys.
421
687
  *
422
- * @param {String} key - the key of the item
423
- * @param {Object} value - the value of the item
424
- * @param {Object} [options] - optional, the specified meta-data
425
- * @return {Promise}
688
+ * @return The remaining valid keys
426
689
  */
427
- AsyncStorageCache.prototype.setItem = function (key, value, options) {
690
+ StorageCacheCommon.prototype.clearInvalidAndGetRemainingKeys = function () {
428
691
  return __awaiter(this, void 0, void 0, function () {
429
- var prefixedKey, cacheItemOptions, item, val, validKeys, sizeToPop, e_1;
430
- return __generator(this, function (_a) {
431
- switch (_a.label) {
432
- case 0:
433
- logger.debug("Set item: key is ".concat(key, ", value is ").concat(value, " with options: ").concat(options));
434
- prefixedKey = this.cacheConfig.keyPrefix + key;
435
- // invalid keys
436
- if (prefixedKey === this.cacheConfig.keyPrefix ||
437
- prefixedKey === getCurrSizeKey(this.cacheConfig.keyPrefix)) {
438
- logger.warn("Invalid key: should not be empty or 'CurSize'");
439
- return [2 /*return*/];
440
- }
441
- if (typeof value === 'undefined') {
442
- logger.warn("The value of item should not be undefined!");
443
- return [2 /*return*/];
444
- }
445
- cacheItemOptions = {
446
- priority: options && options.priority !== undefined
447
- ? options.priority
448
- : this.cacheConfig.defaultPriority,
449
- expires: options && options.expires !== undefined
450
- ? options.expires
451
- : this.cacheConfig.defaultTTL + getCurrTime(),
452
- };
453
- if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
454
- logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
455
- return [2 /*return*/];
456
- }
457
- item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
458
- // check wether this item is too big;
459
- if (item.byteSize > this.cacheConfig.itemMaxSize) {
460
- logger.warn("Item with key: ".concat(key, " you are trying to put into is too big!"));
461
- return [2 /*return*/];
462
- }
463
- _a.label = 1;
464
- case 1:
465
- _a.trys.push([1, 12, , 13]);
466
- return [4 /*yield*/, AsyncStorage.getItem(prefixedKey)];
467
- case 2:
468
- val = _a.sent();
469
- if (!val) return [3 /*break*/, 4];
470
- return [4 /*yield*/, this._removeItem(prefixedKey, JSON.parse(val).byteSize)];
471
- case 3:
472
- _a.sent();
473
- _a.label = 4;
474
- case 4: return [4 /*yield*/, this._isCacheFull(item.byteSize)];
475
- case 5:
476
- if (!_a.sent()) return [3 /*break*/, 10];
477
- return [4 /*yield*/, this._findValidKeys()];
478
- case 6:
479
- validKeys = _a.sent();
480
- return [4 /*yield*/, this._isCacheFull(item.byteSize)];
481
- case 7:
482
- if (!_a.sent()) return [3 /*break*/, 10];
483
- return [4 /*yield*/, this._sizeToPop(item.byteSize)];
484
- case 8:
485
- sizeToPop = _a.sent();
486
- return [4 /*yield*/, this._popOutItems(validKeys, sizeToPop)];
487
- case 9:
488
- _a.sent();
489
- _a.label = 10;
490
- case 10:
491
- // put item in the cache
492
- return [4 /*yield*/, this._setItem(prefixedKey, item)];
493
- case 11:
494
- // put item in the cache
495
- _a.sent();
496
- return [3 /*break*/, 13];
497
- case 12:
498
- e_1 = _a.sent();
499
- logger.warn("setItem failed! ".concat(e_1));
500
- return [3 /*break*/, 13];
501
- case 13: return [2 /*return*/];
502
- }
503
- });
504
- });
505
- };
506
- /**
507
- * Get item from cache. It will return null if item doesn’t exist or it has been expired.
508
- * If you specified callback function in the options,
509
- * then the function will be executed if no such item in the cache
510
- * and finally put the return value into cache.
511
- * Please make sure the callback function will return the value you want to put into the cache.
512
- * The cache will abort output a warning:
513
- * If the key is invalid
514
- * If error happened with AsyncStorage
515
- *
516
- * @param {String} key - the key of the item
517
- * @param {Object} [options] - the options of callback function
518
- * @return {Promise} - return a promise resolves to be the value of the item
519
- */
520
- AsyncStorageCache.prototype.getItem = function (key, options) {
521
- return __awaiter(this, void 0, void 0, function () {
522
- var ret, prefixedKey, item, val, e_2;
523
- return __generator(this, function (_a) {
524
- switch (_a.label) {
692
+ var remainingKeys, keys, keys_1, keys_1_1, key, e_5_1;
693
+ var e_5, _a;
694
+ return __generator(this, function (_b) {
695
+ switch (_b.label) {
525
696
  case 0:
526
- logger.debug("Get item: key is ".concat(key, " with options ").concat(options));
527
- ret = null;
528
- prefixedKey = this.cacheConfig.keyPrefix + key;
529
- if (prefixedKey === this.cacheConfig.keyPrefix ||
530
- prefixedKey === getCurrSizeKey(this.cacheConfig.keyPrefix)) {
531
- logger.warn("Invalid key: should not be empty or 'CurSize'");
532
- return [2 /*return*/, null];
533
- }
534
- _a.label = 1;
697
+ remainingKeys = [];
698
+ return [4 /*yield*/, this.getAllCacheKeys({
699
+ omitSizeKey: true,
700
+ })];
535
701
  case 1:
536
- _a.trys.push([1, 8, , 9]);
537
- return [4 /*yield*/, AsyncStorage.getItem(prefixedKey)];
702
+ keys = _b.sent();
703
+ _b.label = 2;
538
704
  case 2:
539
- ret = _a.sent();
540
- if (!(ret != null)) return [3 /*break*/, 7];
541
- return [4 /*yield*/, this._isExpired(prefixedKey)];
705
+ _b.trys.push([2, 9, 10, 11]);
706
+ keys_1 = __values(keys), keys_1_1 = keys_1.next();
707
+ _b.label = 3;
542
708
  case 3:
543
- if (!_a.sent()) return [3 /*break*/, 5];
544
- // if expired, remove that item and return null
545
- return [4 /*yield*/, this._removeItem(prefixedKey, JSON.parse(ret).byteSize)];
709
+ if (!!keys_1_1.done) return [3 /*break*/, 8];
710
+ key = keys_1_1.value;
711
+ return [4 /*yield*/, this.isExpired(key)];
546
712
  case 4:
547
- // if expired, remove that item and return null
548
- _a.sent();
549
- return [3 /*break*/, 7];
713
+ if (!_b.sent()) return [3 /*break*/, 6];
714
+ return [4 /*yield*/, this.removeCacheItem(key)];
550
715
  case 5:
551
- item = JSON.parse(ret);
552
- return [4 /*yield*/, this._refreshItem(item, prefixedKey)];
716
+ _b.sent();
717
+ return [3 /*break*/, 7];
553
718
  case 6:
554
- item = _a.sent();
555
- return [2 /*return*/, item.data];
719
+ remainingKeys.push(key);
720
+ _b.label = 7;
556
721
  case 7:
557
- if (options && options.callback !== undefined) {
558
- val = options.callback();
559
- if (val !== null) {
560
- this.setItem(key, val, options);
561
- }
562
- return [2 /*return*/, val];
563
- }
564
- return [2 /*return*/, null];
565
- case 8:
566
- e_2 = _a.sent();
567
- logger.warn("getItem failed! ".concat(e_2));
568
- return [2 /*return*/, null];
569
- case 9: return [2 /*return*/];
570
- }
571
- });
572
- });
573
- };
574
- /**
575
- * remove item from the cache
576
- * The cache will abort output a warning:
577
- * If error happened with AsyncStorage
578
- * @param {String} key - the key of the item
579
- * @return {Promise}
580
- */
581
- AsyncStorageCache.prototype.removeItem = function (key) {
582
- return __awaiter(this, void 0, void 0, function () {
583
- var prefixedKey, val, e_3;
584
- return __generator(this, function (_a) {
585
- switch (_a.label) {
586
- case 0:
587
- logger.debug("Remove item: key is ".concat(key));
588
- prefixedKey = this.cacheConfig.keyPrefix + key;
589
- if (prefixedKey === this.cacheConfig.keyPrefix ||
590
- prefixedKey === getCurrSizeKey(this.cacheConfig.keyPrefix)) {
591
- return [2 /*return*/];
722
+ keys_1_1 = keys_1.next();
723
+ return [3 /*break*/, 3];
724
+ case 8: return [3 /*break*/, 11];
725
+ case 9:
726
+ e_5_1 = _b.sent();
727
+ e_5 = { error: e_5_1 };
728
+ return [3 /*break*/, 11];
729
+ case 10:
730
+ try {
731
+ if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
592
732
  }
593
- _a.label = 1;
594
- case 1:
595
- _a.trys.push([1, 5, , 6]);
596
- return [4 /*yield*/, AsyncStorage.getItem(prefixedKey)];
597
- case 2:
598
- val = _a.sent();
599
- if (!val) return [3 /*break*/, 4];
600
- return [4 /*yield*/, this._removeItem(prefixedKey, JSON.parse(val).byteSize)];
601
- case 3:
602
- _a.sent();
603
- _a.label = 4;
604
- case 4: return [3 /*break*/, 6];
605
- case 5:
606
- e_3 = _a.sent();
607
- logger.warn("removeItem failed! ".concat(e_3));
608
- return [3 /*break*/, 6];
609
- case 6: return [2 /*return*/];
733
+ finally { if (e_5) throw e_5.error; }
734
+ return [7 /*endfinally*/];
735
+ case 11: return [2 /*return*/, remainingKeys];
610
736
  }
611
737
  });
612
738
  });
613
739
  };
614
740
  /**
615
741
  * clear the entire cache
616
- * The cache will abort output a warning:
617
- * If error happened with AsyncStorage
742
+ * The cache will abort and output a warning if error occurs
618
743
  * @return {Promise}
619
744
  */
620
- AsyncStorageCache.prototype.clear = function () {
745
+ StorageCacheCommon.prototype.clear = function () {
621
746
  return __awaiter(this, void 0, void 0, function () {
622
- var keys, keysToRemove, i, i, e_4;
623
- return __generator(this, function (_a) {
624
- switch (_a.label) {
747
+ var keys, keys_2, keys_2_1, key, e_6_1, e_7;
748
+ var e_6, _a;
749
+ return __generator(this, function (_b) {
750
+ switch (_b.label) {
625
751
  case 0:
626
752
  logger.debug("Clear Cache");
627
- _a.label = 1;
753
+ _b.label = 1;
628
754
  case 1:
629
- _a.trys.push([1, 7, , 8]);
630
- return [4 /*yield*/, AsyncStorage.getAllKeys()];
755
+ _b.trys.push([1, 11, , 12]);
756
+ return [4 /*yield*/, this.getAllKeys()];
631
757
  case 2:
632
- keys = _a.sent();
633
- keysToRemove = [];
634
- for (i = 0; i < keys.length; i += 1) {
635
- if (keys[i].indexOf(this.cacheConfig.keyPrefix) === 0) {
636
- keysToRemove.push(keys[i]);
637
- }
638
- }
639
- i = 0;
640
- _a.label = 3;
758
+ keys = _b.sent();
759
+ _b.label = 3;
641
760
  case 3:
642
- if (!(i < keysToRemove.length)) return [3 /*break*/, 6];
643
- return [4 /*yield*/, AsyncStorage.removeItem(keysToRemove[i])];
761
+ _b.trys.push([3, 8, 9, 10]);
762
+ keys_2 = __values(keys), keys_2_1 = keys_2.next();
763
+ _b.label = 4;
644
764
  case 4:
645
- _a.sent();
646
- _a.label = 5;
765
+ if (!!keys_2_1.done) return [3 /*break*/, 7];
766
+ key = keys_2_1.value;
767
+ return [4 /*yield*/, this.getStorage().removeItem(key)];
647
768
  case 5:
648
- i += 1;
649
- return [3 /*break*/, 3];
650
- case 6: return [3 /*break*/, 8];
651
- case 7:
652
- e_4 = _a.sent();
653
- logger.warn("clear failed! ".concat(e_4));
654
- return [3 /*break*/, 8];
655
- case 8: return [2 /*return*/];
656
- }
657
- });
658
- });
659
- };
660
- /**
661
- * return the current size of the cache
662
- * @return {Promise}
663
- */
664
- AsyncStorageCache.prototype.getCacheCurSize = function () {
665
- return __awaiter(this, void 0, void 0, function () {
666
- var ret;
667
- return __generator(this, function (_a) {
668
- switch (_a.label) {
669
- case 0: return [4 /*yield*/, AsyncStorage.getItem(getCurrSizeKey(this.cacheConfig.keyPrefix))];
670
- case 1:
671
- ret = _a.sent();
672
- if (!!ret) return [3 /*break*/, 3];
673
- return [4 /*yield*/, AsyncStorage.setItem(getCurrSizeKey(this.cacheConfig.keyPrefix), '0')];
674
- case 2:
675
- _a.sent();
676
- ret = '0';
677
- _a.label = 3;
678
- case 3: return [2 /*return*/, Number(ret)];
679
- }
680
- });
681
- });
682
- };
683
- /**
684
- * Return all the keys in the cache.
685
- * Will return an empty array if error happend.
686
- * @return {Promise}
687
- */
688
- AsyncStorageCache.prototype.getAllKeys = function () {
689
- return __awaiter(this, void 0, void 0, function () {
690
- var keys, retKeys, i, e_5;
691
- return __generator(this, function (_a) {
692
- switch (_a.label) {
693
- case 0:
694
- _a.trys.push([0, 2, , 3]);
695
- return [4 /*yield*/, AsyncStorage.getAllKeys()];
696
- case 1:
697
- keys = _a.sent();
698
- retKeys = [];
699
- for (i = 0; i < keys.length; i += 1) {
700
- if (keys[i].indexOf(this.cacheConfig.keyPrefix) === 0 &&
701
- keys[i] !== getCurrSizeKey(this.cacheConfig.keyPrefix)) {
702
- retKeys.push(keys[i].substring(this.cacheConfig.keyPrefix.length));
703
- }
769
+ _b.sent();
770
+ _b.label = 6;
771
+ case 6:
772
+ keys_2_1 = keys_2.next();
773
+ return [3 /*break*/, 4];
774
+ case 7: return [3 /*break*/, 10];
775
+ case 8:
776
+ e_6_1 = _b.sent();
777
+ e_6 = { error: e_6_1 };
778
+ return [3 /*break*/, 10];
779
+ case 9:
780
+ try {
781
+ if (keys_2_1 && !keys_2_1.done && (_a = keys_2.return)) _a.call(keys_2);
704
782
  }
705
- return [2 /*return*/, retKeys];
706
- case 2:
707
- e_5 = _a.sent();
708
- logger.warn("getALlkeys failed! ".concat(e_5));
709
- return [2 /*return*/, []];
710
- case 3: return [2 /*return*/];
783
+ finally { if (e_6) throw e_6.error; }
784
+ return [7 /*endfinally*/];
785
+ case 10: return [3 /*break*/, 12];
786
+ case 11:
787
+ e_7 = _b.sent();
788
+ logger.warn("clear failed! ".concat(e_7));
789
+ return [3 /*break*/, 12];
790
+ case 12: return [2 /*return*/];
711
791
  }
712
792
  });
713
793
  });
714
794
  };
715
- /**
716
- * Return a new instance of cache with customized configuration.
717
- * @param {Object} config - the customized configuration
718
- * @return {Object} - the new instance of Cache
719
- */
720
- AsyncStorageCache.prototype.createInstance = function (config) {
721
- if (config.keyPrefix === defaultConfig.keyPrefix) {
722
- logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');
723
- config.keyPrefix = getCurrTime.toString();
724
- }
725
- return new AsyncStorageCache(config);
726
- };
727
- return AsyncStorageCache;
728
- }(StorageCache));
729
- export { AsyncStorageCache };
730
- var instance = new AsyncStorageCache();
731
- export { AsyncStorage, instance as Cache };
795
+ return StorageCacheCommon;
796
+ }());
797
+ export { StorageCacheCommon };