@aws-amplify/core 6.0.1-api-v6-models.9351bcf.0 → 6.0.1-api-v6-models.891fe0d.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 (360) hide show
  1. package/lib/BackgroundProcessManager/BackgroundManagerNotOpenError.js +4 -21
  2. package/lib/BackgroundProcessManager/BackgroundProcessManager.js +126 -245
  3. package/lib/Cache/StorageCache.js +32 -92
  4. package/lib/Cache/StorageCache.native.js +38 -140
  5. package/lib/Cache/StorageCacheCommon.js +271 -600
  6. package/lib/Cache/index.js +1 -1
  7. package/lib/Cache/utils/CacheList.js +42 -66
  8. package/lib/Cache/utils/cacheHelpers.js +6 -8
  9. package/lib/Cache/utils/errorHelpers.js +6 -7
  10. package/lib/Hub/index.js +34 -74
  11. package/lib/I18n/I18n.js +24 -39
  12. package/lib/I18n/errorHelpers.js +4 -5
  13. package/lib/I18n/index.js +24 -27
  14. package/lib/I18n/types.js +3 -4
  15. package/lib/Logger/ConsoleLogger.js +53 -129
  16. package/lib/Mutex/Mutex.js +15 -19
  17. package/lib/Platform/customUserAgent.js +13 -26
  18. package/lib/Platform/detectFramework.js +12 -13
  19. package/lib/Platform/detection/Angular.js +4 -5
  20. package/lib/Platform/detection/Expo.js +1 -1
  21. package/lib/Platform/detection/Next.js +1 -1
  22. package/lib/Platform/detection/Nuxt.js +1 -1
  23. package/lib/Platform/detection/React.js +5 -5
  24. package/lib/Platform/detection/Svelte.js +2 -2
  25. package/lib/Platform/detection/Vue.js +1 -1
  26. package/lib/Platform/detection/Web.js +1 -1
  27. package/lib/Platform/detection/helpers.js +7 -7
  28. package/lib/Platform/detection/index.js +13 -13
  29. package/lib/Platform/index.js +26 -55
  30. package/lib/Platform/types.d.ts +1 -1
  31. package/lib/Platform/types.js +1 -1
  32. package/lib/Platform/version.d.ts +1 -1
  33. package/lib/Platform/version.js +1 -1
  34. package/lib/Reachability/Reachability.js +20 -48
  35. package/lib/Reachability/Reachability.native.js +12 -16
  36. package/lib/ServiceWorker/ServiceWorker.js +80 -136
  37. package/lib/ServiceWorker/errorHelpers.js +6 -7
  38. package/lib/Signer/DateUtils.d.ts +9 -0
  39. package/lib/Signer/DateUtils.js +19 -28
  40. package/lib/Signer/Signer.d.ts +9 -0
  41. package/lib/Signer/Signer.js +58 -54
  42. package/lib/adapterCore/error/AmplifyServerContextError.js +9 -27
  43. package/lib/adapterCore/serverContext/serverContext.js +8 -8
  44. package/lib/adapterCore/serverContext/serverContextRegistry.js +6 -6
  45. package/lib/awsClients/cognitoIdentity/base.js +25 -73
  46. package/lib/awsClients/cognitoIdentity/getCredentialsForIdentity.js +24 -68
  47. package/lib/awsClients/cognitoIdentity/getId.js +19 -62
  48. package/lib/awsClients/pinpoint/base.js +12 -15
  49. package/lib/awsClients/pinpoint/errorHelpers.js +4 -5
  50. package/lib/awsClients/pinpoint/getInAppMessages.js +24 -68
  51. package/lib/awsClients/pinpoint/putEvents.js +26 -70
  52. package/lib/awsClients/pinpoint/updateEndpoint.js +28 -72
  53. package/lib/clients/endpoints/getDnsSuffix.js +7 -29
  54. package/lib/clients/handlers/authenticated.js +5 -5
  55. package/lib/clients/handlers/fetch.js +41 -98
  56. package/lib/clients/handlers/unauthenticated.js +4 -4
  57. package/lib/clients/internal/composeServiceApi.js +17 -67
  58. package/lib/clients/internal/composeTransferHandler.js +9 -11
  59. package/lib/clients/middleware/retry/defaultRetryDecider.js +18 -75
  60. package/lib/clients/middleware/retry/isClockSkewError.js +2 -4
  61. package/lib/clients/middleware/retry/jitteredBackoff.js +5 -5
  62. package/lib/clients/middleware/retry/middleware.js +61 -125
  63. package/lib/clients/middleware/signing/middleware.js +24 -86
  64. package/lib/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  65. package/lib/clients/middleware/signing/signer/signatureV4/presignUrl.js +21 -56
  66. package/lib/clients/middleware/signing/signer/signatureV4/signRequest.js +14 -25
  67. package/lib/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.js +7 -7
  68. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalHeaders.js +8 -30
  69. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.js +11 -38
  70. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.js +13 -17
  71. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCanonicalUri.js +5 -8
  72. package/lib/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.js +2 -2
  73. package/lib/clients/middleware/signing/signer/signatureV4/utils/getFormattedDates.js +3 -3
  74. package/lib/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.js +7 -11
  75. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSignature.js +9 -10
  76. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSignedHeaders.js +4 -6
  77. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.js +8 -8
  78. package/lib/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.js +15 -16
  79. package/lib/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.js +2 -4
  80. package/lib/clients/middleware/signing/utils/extendedEncodeURIComponent.js +3 -5
  81. package/lib/clients/middleware/signing/utils/getSkewCorrectedDate.js +1 -3
  82. package/lib/clients/middleware/signing/utils/getUpdatedSystemClockOffset.js +2 -2
  83. package/lib/clients/middleware/signing/utils/isClockSkewed.js +4 -6
  84. package/lib/clients/middleware/userAgent/middleware.js +14 -63
  85. package/lib/clients/serde/json.js +30 -96
  86. package/lib/clients/serde/responseInfo.js +12 -18
  87. package/lib/clients/utils/memoization.js +3 -3
  88. package/lib/constants.js +1 -1
  89. package/lib/errors/AmplifyError.js +9 -28
  90. package/lib/errors/PlatformNotSupportedError.js +7 -24
  91. package/lib/errors/createAssertionFunction.js +12 -15
  92. package/lib/errors/errorHelpers.js +7 -8
  93. package/lib/index.d.ts +1 -1
  94. package/lib/libraryUtils.d.ts +4 -0
  95. package/lib/libraryUtils.js +13 -3
  96. package/lib/parseAWSExports.js +109 -100
  97. package/lib/providers/kinesis/types/kinesis.d.ts +1 -1
  98. package/lib/providers/kinesis-firehose/types/kinesis-firehose.d.ts +1 -1
  99. package/lib/providers/personalize/types/personalize.d.ts +1 -1
  100. package/lib/providers/pinpoint/apis/flushEvents.js +8 -8
  101. package/lib/providers/pinpoint/apis/record.js +58 -93
  102. package/lib/providers/pinpoint/apis/updateEndpoint.js +65 -112
  103. package/lib/providers/pinpoint/types/pinpoint.d.ts +3 -1
  104. package/lib/providers/pinpoint/utils/PinpointEventBuffer.js +105 -196
  105. package/lib/providers/pinpoint/utils/cacheEndpointId.js +12 -49
  106. package/lib/providers/pinpoint/utils/getCacheKey.js +2 -2
  107. package/lib/providers/pinpoint/utils/getEndpointId.js +7 -51
  108. package/lib/providers/pinpoint/utils/getEventBuffer.js +19 -21
  109. package/lib/providers/pinpoint/utils/isAppInForeground.js +1 -1
  110. package/lib/providers/pinpoint/utils/isAppInForeground.native.js +2 -2
  111. package/lib/providers/pinpoint/utils/resolveEndpointId.js +20 -71
  112. package/lib/singleton/Amplify.d.ts +4 -0
  113. package/lib/singleton/Amplify.js +21 -103
  114. package/lib/singleton/Analytics/types.d.ts +5 -1
  115. package/lib/singleton/Auth/index.js +48 -115
  116. package/lib/singleton/Auth/types.d.ts +2 -2
  117. package/lib/singleton/Auth/utils/errorHelpers.js +7 -8
  118. package/lib/singleton/Auth/utils/index.js +18 -19
  119. package/lib/singleton/Predictions/types.d.ts +49 -0
  120. package/lib/singleton/Predictions/types.js +4 -0
  121. package/lib/singleton/apis/clearCredentials.js +1 -1
  122. package/lib/singleton/apis/fetchAuthSession.js +3 -3
  123. package/lib/singleton/apis/internal/fetchAuthSession.js +1 -1
  124. package/lib/singleton/apis/server/fetchAuthSession.js +3 -3
  125. package/lib/singleton/types.d.ts +3 -1
  126. package/lib/storage/CookieStorage.js +29 -99
  127. package/lib/storage/CookieStorage.native.js +5 -22
  128. package/lib/storage/DefaultStorage.js +6 -23
  129. package/lib/storage/DefaultStorage.native.js +18 -64
  130. package/lib/storage/InMemoryStorage.js +17 -23
  131. package/lib/storage/KeyValueStorage.js +24 -80
  132. package/lib/storage/SessionStorage.js +6 -23
  133. package/lib/storage/index.js +4 -4
  134. package/lib/storage/utils.js +7 -11
  135. package/lib/tsconfig.tsbuildinfo +1 -1
  136. package/lib/utils/WordArray.d.ts +7 -0
  137. package/lib/utils/WordArray.js +49 -0
  138. package/lib/utils/amplifyUrl/index.js +2 -2
  139. package/lib/utils/amplifyUrl/polyfill.native.js +1 -1
  140. package/lib/utils/amplifyUuid/index.d.ts +1 -1
  141. package/lib/utils/amplifyUuid/index.js +2 -2
  142. package/lib/utils/amplifyUuid/polyfill.native.js +1 -1
  143. package/lib/utils/convert/base64/base64Decoder.js +2 -2
  144. package/lib/utils/convert/base64/base64Encoder.js +5 -6
  145. package/lib/utils/convert/base64/bytesToString.js +1 -1
  146. package/lib/utils/cryptoSecureRandomInt.d.ts +1 -0
  147. package/lib/utils/cryptoSecureRandomInt.js +16 -0
  148. package/lib/utils/deepFreeze.js +6 -28
  149. package/lib/utils/generateRandomString.js +4 -4
  150. package/lib/utils/getClientInfo/getClientInfo.android.js +7 -7
  151. package/lib/utils/getClientInfo/getClientInfo.ios.js +12 -12
  152. package/lib/utils/getClientInfo/getClientInfo.js +16 -16
  153. package/lib/utils/globalHelpers/index.js +4 -4
  154. package/lib/utils/globalHelpers/index.native.js +6 -6
  155. package/lib/utils/isBrowser.js +1 -3
  156. package/lib/utils/isWebWorker.js +2 -2
  157. package/lib/utils/retry/NonRetryableError.js +5 -23
  158. package/lib/utils/retry/isNonRetryableError.js +2 -2
  159. package/lib/utils/retry/jitteredBackoff.js +6 -7
  160. package/lib/utils/retry/jitteredExponentialRetry.js +4 -7
  161. package/lib/utils/retry/retry.js +50 -140
  162. package/lib/utils/sessionListener/SessionListener.js +17 -19
  163. package/lib/utils/sessionListener/SessionListener.native.js +18 -22
  164. package/lib/utils/sessionListener/constants.d.ts +2 -0
  165. package/lib/utils/sessionListener/constants.js +8 -0
  166. package/lib/utils/sessionListener/index.d.ts +1 -0
  167. package/lib/utils/sessionListener/index.js +5 -2
  168. package/lib/utils/urlSafeDecode.js +2 -2
  169. package/lib/utils/urlSafeEncode.js +1 -1
  170. package/lib-esm/BackgroundProcessManager/BackgroundManagerNotOpenError.js +4 -22
  171. package/lib-esm/BackgroundProcessManager/BackgroundProcessManager.js +124 -244
  172. package/lib-esm/Cache/StorageCache.js +26 -87
  173. package/lib-esm/Cache/StorageCache.native.js +33 -136
  174. package/lib-esm/Cache/StorageCacheCommon.js +267 -597
  175. package/lib-esm/Cache/constants.js +2 -2
  176. package/lib-esm/Cache/index.js +1 -1
  177. package/lib-esm/Cache/utils/CacheList.js +41 -66
  178. package/lib-esm/Cache/utils/cacheHelpers.js +5 -7
  179. package/lib-esm/Cache/utils/errorHelpers.js +6 -7
  180. package/lib-esm/Hub/index.js +34 -75
  181. package/lib-esm/I18n/I18n.js +23 -39
  182. package/lib-esm/I18n/errorHelpers.js +4 -5
  183. package/lib-esm/I18n/index.js +21 -25
  184. package/lib-esm/I18n/types.js +3 -5
  185. package/lib-esm/Logger/ConsoleLogger.js +52 -128
  186. package/lib-esm/Mutex/Mutex.js +15 -20
  187. package/lib-esm/Platform/customUserAgent.js +13 -26
  188. package/lib-esm/Platform/detectFramework.js +11 -12
  189. package/lib-esm/Platform/detection/Angular.js +3 -4
  190. package/lib-esm/Platform/detection/React.js +4 -4
  191. package/lib-esm/Platform/detection/Svelte.js +1 -1
  192. package/lib-esm/Platform/detection/helpers.js +7 -7
  193. package/lib-esm/Platform/detection/index.js +3 -3
  194. package/lib-esm/Platform/index.js +23 -52
  195. package/lib-esm/Platform/types.d.ts +1 -1
  196. package/lib-esm/Platform/types.js +1 -1
  197. package/lib-esm/Platform/version.d.ts +1 -1
  198. package/lib-esm/Platform/version.js +1 -1
  199. package/lib-esm/Reachability/Reachability.js +18 -46
  200. package/lib-esm/Reachability/Reachability.native.js +10 -15
  201. package/lib-esm/ServiceWorker/ServiceWorker.js +74 -131
  202. package/lib-esm/ServiceWorker/errorHelpers.js +6 -7
  203. package/lib-esm/Signer/DateUtils.d.ts +9 -0
  204. package/lib-esm/Signer/DateUtils.js +20 -29
  205. package/lib-esm/Signer/Signer.d.ts +9 -0
  206. package/lib-esm/Signer/Signer.js +54 -51
  207. package/lib-esm/adapterCore/error/AmplifyServerContextError.js +8 -27
  208. package/lib-esm/adapterCore/serverContext/serverContext.js +6 -6
  209. package/lib-esm/adapterCore/serverContext/serverContextRegistry.js +7 -7
  210. package/lib-esm/awsClients/cognitoIdentity/base.js +21 -69
  211. package/lib-esm/awsClients/cognitoIdentity/getCredentialsForIdentity.js +22 -66
  212. package/lib-esm/awsClients/cognitoIdentity/getId.js +17 -60
  213. package/lib-esm/awsClients/pinpoint/base.js +8 -11
  214. package/lib-esm/awsClients/pinpoint/errorHelpers.js +4 -5
  215. package/lib-esm/awsClients/pinpoint/getInAppMessages.js +19 -63
  216. package/lib-esm/awsClients/pinpoint/putEvents.js +20 -64
  217. package/lib-esm/awsClients/pinpoint/updateEndpoint.js +23 -67
  218. package/lib-esm/clients/endpoints/getDnsSuffix.js +6 -28
  219. package/lib-esm/clients/endpoints/partitions.js +2 -2
  220. package/lib-esm/clients/handlers/authenticated.js +1 -1
  221. package/lib-esm/clients/handlers/fetch.js +40 -97
  222. package/lib-esm/clients/handlers/unauthenticated.js +1 -1
  223. package/lib-esm/clients/internal/composeServiceApi.js +17 -67
  224. package/lib-esm/clients/internal/composeTransferHandler.js +9 -11
  225. package/lib-esm/clients/middleware/retry/defaultRetryDecider.js +17 -74
  226. package/lib-esm/clients/middleware/retry/isClockSkewError.js +2 -4
  227. package/lib-esm/clients/middleware/retry/jitteredBackoff.js +4 -4
  228. package/lib-esm/clients/middleware/retry/middleware.js +61 -125
  229. package/lib-esm/clients/middleware/signing/middleware.js +21 -83
  230. package/lib-esm/clients/middleware/signing/signer/signatureV4/constants.js +17 -17
  231. package/lib-esm/clients/middleware/signing/signer/signatureV4/index.js +0 -1
  232. package/lib-esm/clients/middleware/signing/signer/signatureV4/presignUrl.js +17 -52
  233. package/lib-esm/clients/middleware/signing/signer/signatureV4/signRequest.js +10 -21
  234. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.js +5 -5
  235. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalHeaders.js +8 -30
  236. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.js +11 -38
  237. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.js +8 -12
  238. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalUri.js +5 -8
  239. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.js +1 -1
  240. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getFormattedDates.js +3 -3
  241. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.js +5 -9
  242. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSignature.js +5 -6
  243. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSignedHeaders.js +4 -6
  244. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.js +6 -6
  245. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.js +13 -14
  246. package/lib-esm/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.js +1 -3
  247. package/lib-esm/clients/middleware/signing/utils/extendedEncodeURIComponent.js +3 -5
  248. package/lib-esm/clients/middleware/signing/utils/getSkewCorrectedDate.js +1 -3
  249. package/lib-esm/clients/middleware/signing/utils/getUpdatedSystemClockOffset.js +1 -1
  250. package/lib-esm/clients/middleware/signing/utils/isClockSkewed.js +3 -5
  251. package/lib-esm/clients/middleware/userAgent/middleware.js +14 -63
  252. package/lib-esm/clients/serde/json.js +29 -95
  253. package/lib-esm/clients/serde/responseInfo.js +11 -17
  254. package/lib-esm/clients/utils/memoization.js +3 -3
  255. package/lib-esm/constants.js +5 -5
  256. package/lib-esm/errors/AmplifyError.js +9 -29
  257. package/lib-esm/errors/PlatformNotSupportedError.js +5 -23
  258. package/lib-esm/errors/createAssertionFunction.js +11 -14
  259. package/lib-esm/errors/errorHelpers.js +6 -7
  260. package/lib-esm/index.d.ts +1 -1
  261. package/lib-esm/libraryUtils.d.ts +4 -0
  262. package/lib-esm/libraryUtils.js +4 -0
  263. package/lib-esm/parseAWSExports.js +108 -99
  264. package/lib-esm/providers/kinesis/types/kinesis.d.ts +1 -1
  265. package/lib-esm/providers/kinesis-firehose/types/kinesis-firehose.d.ts +1 -1
  266. package/lib-esm/providers/personalize/types/personalize.d.ts +1 -1
  267. package/lib-esm/providers/pinpoint/apis/flushEvents.js +6 -6
  268. package/lib-esm/providers/pinpoint/apis/record.js +54 -89
  269. package/lib-esm/providers/pinpoint/apis/updateEndpoint.js +61 -108
  270. package/lib-esm/providers/pinpoint/types/pinpoint.d.ts +3 -1
  271. package/lib-esm/providers/pinpoint/utils/PinpointEventBuffer.js +102 -194
  272. package/lib-esm/providers/pinpoint/utils/cacheEndpointId.js +10 -47
  273. package/lib-esm/providers/pinpoint/utils/constants.js +4 -4
  274. package/lib-esm/providers/pinpoint/utils/getCacheKey.js +2 -2
  275. package/lib-esm/providers/pinpoint/utils/getEndpointId.js +5 -49
  276. package/lib-esm/providers/pinpoint/utils/getEventBuffer.js +17 -19
  277. package/lib-esm/providers/pinpoint/utils/isAppInForeground.js +1 -1
  278. package/lib-esm/providers/pinpoint/utils/isAppInForeground.native.js +1 -1
  279. package/lib-esm/providers/pinpoint/utils/resolveEndpointId.js +16 -67
  280. package/lib-esm/singleton/Amplify.d.ts +4 -0
  281. package/lib-esm/singleton/Amplify.js +18 -101
  282. package/lib-esm/singleton/Analytics/types.d.ts +5 -1
  283. package/lib-esm/singleton/Auth/index.js +48 -116
  284. package/lib-esm/singleton/Auth/types.d.ts +2 -2
  285. package/lib-esm/singleton/Auth/utils/errorHelpers.js +7 -8
  286. package/lib-esm/singleton/Auth/utils/index.js +16 -17
  287. package/lib-esm/singleton/Predictions/types.d.ts +49 -0
  288. package/lib-esm/singleton/Predictions/types.js +3 -0
  289. package/lib-esm/singleton/apis/fetchAuthSession.js +1 -1
  290. package/lib-esm/singleton/apis/internal/fetchAuthSession.js +1 -1
  291. package/lib-esm/singleton/apis/server/fetchAuthSession.js +1 -1
  292. package/lib-esm/singleton/types.d.ts +3 -1
  293. package/lib-esm/storage/CookieStorage.js +28 -99
  294. package/lib-esm/storage/CookieStorage.native.js +4 -22
  295. package/lib-esm/storage/DefaultStorage.js +4 -22
  296. package/lib-esm/storage/DefaultStorage.native.js +17 -64
  297. package/lib-esm/storage/InMemoryStorage.js +17 -24
  298. package/lib-esm/storage/KeyValueStorage.js +23 -80
  299. package/lib-esm/storage/SessionStorage.js +4 -22
  300. package/lib-esm/storage/index.js +3 -3
  301. package/lib-esm/storage/utils.js +6 -10
  302. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  303. package/lib-esm/utils/WordArray.d.ts +7 -0
  304. package/lib-esm/utils/WordArray.js +46 -0
  305. package/lib-esm/utils/amplifyUrl/index.js +2 -2
  306. package/lib-esm/utils/amplifyUuid/index.d.ts +1 -1
  307. package/lib-esm/utils/amplifyUuid/index.js +1 -1
  308. package/lib-esm/utils/convert/base64/base64Decoder.js +2 -2
  309. package/lib-esm/utils/convert/base64/base64Encoder.js +4 -5
  310. package/lib-esm/utils/convert/base64/bytesToString.js +1 -1
  311. package/lib-esm/utils/cryptoSecureRandomInt.d.ts +1 -0
  312. package/lib-esm/utils/cryptoSecureRandomInt.js +12 -0
  313. package/lib-esm/utils/deepFreeze.js +6 -28
  314. package/lib-esm/utils/generateRandomString.js +4 -4
  315. package/lib-esm/utils/getClientInfo/getClientInfo.android.js +5 -5
  316. package/lib-esm/utils/getClientInfo/getClientInfo.ios.js +10 -10
  317. package/lib-esm/utils/getClientInfo/getClientInfo.js +15 -15
  318. package/lib-esm/utils/globalHelpers/index.js +3 -3
  319. package/lib-esm/utils/globalHelpers/index.native.js +4 -4
  320. package/lib-esm/utils/isBrowser.js +1 -3
  321. package/lib-esm/utils/isWebWorker.js +2 -2
  322. package/lib-esm/utils/retry/NonRetryableError.js +5 -24
  323. package/lib-esm/utils/retry/constants.js +1 -1
  324. package/lib-esm/utils/retry/isNonRetryableError.js +2 -2
  325. package/lib-esm/utils/retry/jitteredBackoff.js +5 -6
  326. package/lib-esm/utils/retry/jitteredExponentialRetry.js +1 -4
  327. package/lib-esm/utils/retry/retry.js +48 -138
  328. package/lib-esm/utils/sessionListener/SessionListener.js +16 -19
  329. package/lib-esm/utils/sessionListener/SessionListener.native.js +17 -22
  330. package/lib-esm/utils/sessionListener/constants.d.ts +2 -0
  331. package/lib-esm/utils/sessionListener/constants.js +5 -0
  332. package/lib-esm/utils/sessionListener/index.d.ts +1 -0
  333. package/lib-esm/utils/sessionListener/index.js +2 -1
  334. package/lib-esm/utils/urlSafeDecode.js +2 -2
  335. package/lib-esm/utils/urlSafeEncode.js +1 -1
  336. package/package.json +11 -24
  337. package/src/Cache/types/index.ts +4 -4
  338. package/src/Platform/types.ts +1 -1
  339. package/src/Platform/version.ts +1 -1
  340. package/src/Signer/DateUtils.ts +10 -2
  341. package/src/Signer/Signer.ts +9 -2
  342. package/src/clients/middleware/signing/signer/signatureV4/index.ts +0 -1
  343. package/src/index.ts +1 -0
  344. package/src/libraryUtils.ts +7 -1
  345. package/src/parseAWSExports.ts +45 -6
  346. package/src/providers/kinesis/types/kinesis.ts +1 -1
  347. package/src/providers/kinesis-firehose/types/kinesis-firehose.ts +1 -1
  348. package/src/providers/personalize/types/personalize.ts +1 -1
  349. package/src/providers/pinpoint/apis/record.ts +22 -5
  350. package/src/providers/pinpoint/types/pinpoint.ts +3 -1
  351. package/src/singleton/Amplify.ts +9 -52
  352. package/src/singleton/Analytics/types.ts +9 -4
  353. package/src/singleton/Auth/types.ts +2 -2
  354. package/src/singleton/Predictions/types.ts +61 -0
  355. package/src/singleton/types.ts +3 -1
  356. package/src/utils/WordArray.ts +57 -0
  357. package/src/utils/amplifyUuid/index.ts +1 -1
  358. package/src/utils/cryptoSecureRandomInt.ts +14 -0
  359. package/src/utils/sessionListener/constants.ts +6 -0
  360. package/src/utils/sessionListener/index.ts +1 -0
@@ -1,90 +1,34 @@
1
1
  "use strict";
2
2
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  // SPDX-License-Identifier: Apache-2.0
4
- var __assign = (this && this.__assign) || function () {
5
- __assign = Object.assign || function(t) {
6
- for (var s, i = 1, n = arguments.length; i < n; i++) {
7
- s = arguments[i];
8
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
9
- t[p] = s[p];
10
- }
11
- return t;
12
- };
13
- return __assign.apply(this, arguments);
14
- };
15
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
16
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
17
- return new (P || (P = Promise))(function (resolve, reject) {
18
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
20
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21
- step((generator = generator.apply(thisArg, _arguments || [])).next());
22
- });
23
- };
24
- var __generator = (this && this.__generator) || function (thisArg, body) {
25
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
26
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
27
- function verb(n) { return function (v) { return step([n, v]); }; }
28
- function step(op) {
29
- if (f) throw new TypeError("Generator is already executing.");
30
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
31
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
32
- if (y = 0, t) op = [op[0] & 2, t.value];
33
- switch (op[0]) {
34
- case 0: case 1: t = op; break;
35
- case 4: _.label++; return { value: op[1], done: false };
36
- case 5: _.label++; y = op[1]; op = [0]; continue;
37
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
38
- default:
39
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
40
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
41
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
42
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
43
- if (t[2]) _.ops.pop();
44
- _.trys.pop(); continue;
45
- }
46
- op = body.call(thisArg, _);
47
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
48
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
49
- }
50
- };
51
- var __values = (this && this.__values) || function(o) {
52
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
53
- if (m) return m.call(o);
54
- if (o && typeof o.length === "number") return {
55
- next: function () {
56
- if (o && i >= o.length) o = void 0;
57
- return { value: o && o[i++], done: !o };
58
- }
59
- };
60
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
61
- };
62
4
  Object.defineProperty(exports, "__esModule", { value: true });
63
5
  exports.StorageCacheCommon = void 0;
64
- var Logger_1 = require("../Logger");
65
- var constants_1 = require("./constants");
66
- var utils_1 = require("./utils");
67
- var errorHelpers_1 = require("./utils/errorHelpers");
68
- var logger = new Logger_1.ConsoleLogger('StorageCache');
6
+ const Logger_1 = require("../Logger");
7
+ const constants_1 = require("./constants");
8
+ const utils_1 = require("./utils");
9
+ const errorHelpers_1 = require("./utils/errorHelpers");
10
+ const logger = new Logger_1.ConsoleLogger('StorageCache');
69
11
  /**
70
12
  * Initialization of the cache
71
13
  *
72
14
  */
73
- var StorageCacheCommon = /** @class */ (function () {
15
+ class StorageCacheCommon {
74
16
  /**
75
17
  * Initialize the cache
76
18
  *
77
19
  * @param config - Custom configuration for this instance.
78
20
  */
79
- function StorageCacheCommon(_a) {
80
- var config = _a.config, keyValueStorage = _a.keyValueStorage;
81
- this.config = __assign(__assign({}, constants_1.defaultConfig), config);
21
+ constructor({ config, keyValueStorage, }) {
22
+ this.config = {
23
+ ...constants_1.defaultConfig,
24
+ ...config,
25
+ };
82
26
  this.keyValueStorage = keyValueStorage;
83
27
  this.sanitizeConfig();
84
28
  }
85
- StorageCacheCommon.prototype.getModuleName = function () {
29
+ getModuleName() {
86
30
  return 'Cache';
87
- };
31
+ }
88
32
  /**
89
33
  * Set custom configuration for the cache instance.
90
34
  *
@@ -92,39 +36,31 @@ var StorageCacheCommon = /** @class */ (function () {
92
36
  *
93
37
  * @return - the current configuration
94
38
  */
95
- StorageCacheCommon.prototype.configure = function (config) {
39
+ configure(config) {
96
40
  if (config) {
97
41
  if (config.keyPrefix) {
98
42
  logger.warn('keyPrefix can not be re-configured on an existing Cache instance.');
99
43
  }
100
- this.config = __assign(__assign({}, this.config), config);
44
+ this.config = {
45
+ ...this.config,
46
+ ...config,
47
+ };
101
48
  }
102
49
  this.sanitizeConfig();
103
50
  return this.config;
104
- };
51
+ }
105
52
  /**
106
53
  * return the current size of the cache
107
54
  * @return {Promise}
108
55
  */
109
- StorageCacheCommon.prototype.getCurrentCacheSize = function () {
110
- return __awaiter(this, void 0, void 0, function () {
111
- var size;
112
- return __generator(this, function (_a) {
113
- switch (_a.label) {
114
- case 0: return [4 /*yield*/, this.getStorage().getItem((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix))];
115
- case 1:
116
- size = _a.sent();
117
- if (!!size) return [3 /*break*/, 3];
118
- return [4 /*yield*/, this.getStorage().setItem((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix), '0')];
119
- case 2:
120
- _a.sent();
121
- size = '0';
122
- _a.label = 3;
123
- case 3: return [2 /*return*/, Number(size)];
124
- }
125
- });
126
- });
127
- };
56
+ async getCurrentCacheSize() {
57
+ let size = await this.getStorage().getItem((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix));
58
+ if (!size) {
59
+ await this.getStorage().setItem((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix), '0');
60
+ size = '0';
61
+ }
62
+ return Number(size);
63
+ }
128
64
  /**
129
65
  * Set item into cache. You can put number, string, boolean or object.
130
66
  * The cache will first check whether has the same key.
@@ -143,79 +79,56 @@ var StorageCacheCommon = /** @class */ (function () {
143
79
  *
144
80
  * @return {Promise}
145
81
  */
146
- StorageCacheCommon.prototype.setItem = function (key, value, options) {
147
- return __awaiter(this, void 0, void 0, function () {
148
- var cacheItemOptions, prefixedKey, item, val, validKeys, sizeToPop, e_1;
149
- return __generator(this, function (_a) {
150
- switch (_a.label) {
151
- case 0:
152
- logger.debug("Set item: key is ".concat(key, ", value is ").concat(value, " with options: ").concat(options));
153
- if (!key || key === constants_1.currentSizeKey) {
154
- logger.warn("Invalid key: should not be empty or reserved key: '".concat(constants_1.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 + (0, utils_1.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;
181
- case 1:
182
- _a.trys.push([1, 11, , 12]);
183
- return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
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:
189
- _a.sent();
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*/];
82
+ async setItem(key, value, options) {
83
+ logger.debug(`Set item: key is ${key}, value is ${value} with options: ${options}`);
84
+ if (!key || key === constants_1.currentSizeKey) {
85
+ logger.warn(`Invalid key: should not be empty or reserved key: '${constants_1.currentSizeKey}'`);
86
+ return;
87
+ }
88
+ if (typeof value === 'undefined') {
89
+ logger.warn(`The value of item should not be undefined!`);
90
+ return;
91
+ }
92
+ const cacheItemOptions = {
93
+ priority: options?.priority !== undefined
94
+ ? options.priority
95
+ : this.config.defaultPriority,
96
+ expires: options?.expires !== undefined
97
+ ? options.expires
98
+ : this.config.defaultTTL + (0, utils_1.getCurrentTime)(),
99
+ };
100
+ if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
101
+ logger.warn(`Invalid parameter: priority due to out or range. It should be within 1 and 5.`);
102
+ return;
103
+ }
104
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
105
+ const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
106
+ // check whether this item is too big;
107
+ if (item.byteSize > this.config.itemMaxSize) {
108
+ logger.warn(`Item with key: ${key} you are trying to put into is too big!`);
109
+ return;
110
+ }
111
+ try {
112
+ // first look into the storage, if it exists, delete it.
113
+ const val = await this.getStorage().getItem(prefixedKey);
114
+ if (val) {
115
+ await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);
116
+ }
117
+ // check whether the cache is full
118
+ if (await this.isCacheFull(item.byteSize)) {
119
+ const validKeys = await this.clearInvalidAndGetRemainingKeys();
120
+ if (await this.isCacheFull(item.byteSize)) {
121
+ const sizeToPop = await this.sizeToPop(item.byteSize);
122
+ await this.popOutItems(validKeys, sizeToPop);
215
123
  }
216
- });
217
- });
218
- };
124
+ }
125
+ // put item in the cache
126
+ return this.setCacheItem(prefixedKey, item);
127
+ }
128
+ catch (e) {
129
+ logger.warn(`setItem failed! ${e}`);
130
+ }
131
+ }
219
132
  /**
220
133
  * Get item from cache. It will return null if item doesn’t exist or it has been expired.
221
134
  * If you specified callback function in the options,
@@ -231,57 +144,41 @@ var StorageCacheCommon = /** @class */ (function () {
231
144
  *
232
145
  * @return {Promise} - return a promise resolves to be the value of the item
233
146
  */
234
- StorageCacheCommon.prototype.getItem = function (key, options) {
235
- return __awaiter(this, void 0, void 0, function () {
236
- var cached, prefixedKey, item, val, e_2;
237
- return __generator(this, function (_a) {
238
- switch (_a.label) {
239
- case 0:
240
- logger.debug("Get item: key is ".concat(key, " with options ").concat(options));
241
- if (!key || key === constants_1.currentSizeKey) {
242
- logger.warn("Invalid key: should not be empty or reserved key: '".concat(constants_1.currentSizeKey, "'"));
243
- return [2 /*return*/, null];
244
- }
245
- prefixedKey = "".concat(this.config.keyPrefix).concat(key);
246
- _a.label = 1;
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
260
- _a.sent();
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*/];
147
+ async getItem(key, options) {
148
+ logger.debug(`Get item: key is ${key} with options ${options}`);
149
+ let cached;
150
+ if (!key || key === constants_1.currentSizeKey) {
151
+ logger.warn(`Invalid key: should not be empty or reserved key: '${constants_1.currentSizeKey}'`);
152
+ return null;
153
+ }
154
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
155
+ try {
156
+ cached = await this.getStorage().getItem(prefixedKey);
157
+ if (cached != null) {
158
+ if (await this.isExpired(prefixedKey)) {
159
+ // if expired, remove that item and return null
160
+ await this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize);
281
161
  }
282
- });
283
- });
284
- };
162
+ else {
163
+ // if not expired, update its visitedTime and return the value
164
+ const item = await this.updateVisitedTime(JSON.parse(cached), prefixedKey);
165
+ return item.data;
166
+ }
167
+ }
168
+ if (options?.callback) {
169
+ const val = options.callback();
170
+ if (val !== null) {
171
+ await this.setItem(key, val, options);
172
+ }
173
+ return val;
174
+ }
175
+ return null;
176
+ }
177
+ catch (e) {
178
+ logger.warn(`getItem failed! ${e}`);
179
+ return null;
180
+ }
181
+ }
285
182
  /**
286
183
  * remove item from the cache
287
184
  * The cache will abort output a warning:
@@ -289,66 +186,41 @@ var StorageCacheCommon = /** @class */ (function () {
289
186
  * @param {String} key - the key of the item
290
187
  * @return {Promise}
291
188
  */
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 === constants_1.currentSizeKey) {
300
- logger.warn("Invalid key: should not be empty or reserved key: '".concat(constants_1.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
- };
189
+ async removeItem(key) {
190
+ logger.debug(`Remove item: key is ${key}`);
191
+ if (!key || key === constants_1.currentSizeKey) {
192
+ logger.warn(`Invalid key: should not be empty or reserved key: '${constants_1.currentSizeKey}'`);
193
+ return;
194
+ }
195
+ const prefixedKey = `${this.config.keyPrefix}${key}`;
196
+ try {
197
+ const val = await this.getStorage().getItem(prefixedKey);
198
+ if (val) {
199
+ await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);
200
+ }
201
+ }
202
+ catch (e) {
203
+ logger.warn(`removeItem failed! ${e}`);
204
+ }
205
+ }
325
206
  /**
326
207
  * Return all the keys owned by this cache.
327
208
  * Will return an empty array if error occurred.
328
209
  *
329
210
  * @return {Promise}
330
211
  */
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 () {
212
+ async getAllKeys() {
213
+ try {
214
+ return await this.getAllCacheKeys();
215
+ }
216
+ catch (e) {
217
+ logger.warn(`getAllkeys failed! ${e}`);
218
+ return [];
219
+ }
220
+ }
221
+ getStorage() {
350
222
  return this.keyValueStorage;
351
- };
223
+ }
352
224
  /**
353
225
  * check whether item is expired
354
226
  *
@@ -356,66 +228,37 @@ var StorageCacheCommon = /** @class */ (function () {
356
228
  *
357
229
  * @return true if the item is expired.
358
230
  */
359
- StorageCacheCommon.prototype.isExpired = function (key) {
360
- return __awaiter(this, void 0, void 0, function () {
361
- var text, item;
362
- return __generator(this, function (_a) {
363
- switch (_a.label) {
364
- case 0: return [4 /*yield*/, this.getStorage().getItem(key)];
365
- case 1:
366
- text = _a.sent();
367
- (0, errorHelpers_1.assert)(text !== null, errorHelpers_1.CacheErrorCode.NoCacheItem, "Key: ".concat(key));
368
- item = JSON.parse(text);
369
- if ((0, utils_1.getCurrentTime)() >= item.expires) {
370
- return [2 /*return*/, true];
371
- }
372
- return [2 /*return*/, false];
373
- }
374
- });
375
- });
376
- };
231
+ async isExpired(key) {
232
+ const text = await this.getStorage().getItem(key);
233
+ (0, errorHelpers_1.assert)(text !== null, errorHelpers_1.CacheErrorCode.NoCacheItem, `Key: ${key}`);
234
+ const item = JSON.parse(text);
235
+ if ((0, utils_1.getCurrentTime)() >= item.expires) {
236
+ return true;
237
+ }
238
+ return false;
239
+ }
377
240
  /**
378
241
  * delete item from cache
379
242
  *
380
243
  * @param prefixedKey - the key of the item
381
244
  * @param size - optional, the byte size of the item
382
245
  */
383
- StorageCacheCommon.prototype.removeCacheItem = function (prefixedKey, size) {
384
- return __awaiter(this, void 0, void 0, function () {
385
- var item, itemSize, removeItemError_1;
386
- return __generator(this, function (_a) {
387
- switch (_a.label) {
388
- case 0: return [4 /*yield*/, this.getStorage().getItem(prefixedKey)];
389
- case 1:
390
- item = _a.sent();
391
- (0, errorHelpers_1.assert)(item !== null, errorHelpers_1.CacheErrorCode.NoCacheItem, "Key: ".concat(prefixedKey));
392
- itemSize = size !== null && size !== void 0 ? size : JSON.parse(item).byteSize;
393
- // first try to update the current size of the cache
394
- return [4 /*yield*/, this.decreaseCurrentSizeInBytes(itemSize)];
395
- case 2:
396
- // first try to update the current size of the cache
397
- _a.sent();
398
- _a.label = 3;
399
- case 3:
400
- _a.trys.push([3, 5, , 7]);
401
- return [4 /*yield*/, this.getStorage().removeItem(prefixedKey)];
402
- case 4:
403
- _a.sent();
404
- return [3 /*break*/, 7];
405
- case 5:
406
- removeItemError_1 = _a.sent();
407
- // if some error happened, we need to rollback the current size
408
- return [4 /*yield*/, this.increaseCurrentSizeInBytes(itemSize)];
409
- case 6:
410
- // if some error happened, we need to rollback the current size
411
- _a.sent();
412
- logger.error("Failed to remove item: ".concat(removeItemError_1));
413
- return [3 /*break*/, 7];
414
- case 7: return [2 /*return*/];
415
- }
416
- });
417
- });
418
- };
246
+ async removeCacheItem(prefixedKey, size) {
247
+ const item = await this.getStorage().getItem(prefixedKey);
248
+ (0, errorHelpers_1.assert)(item !== null, errorHelpers_1.CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`);
249
+ const itemSize = size ?? JSON.parse(item).byteSize;
250
+ // first try to update the current size of the cache
251
+ await this.decreaseCurrentSizeInBytes(itemSize);
252
+ // try to remove the item from cache
253
+ try {
254
+ await this.getStorage().removeItem(prefixedKey);
255
+ }
256
+ catch (removeItemError) {
257
+ // if some error happened, we need to rollback the current size
258
+ await this.increaseCurrentSizeInBytes(itemSize);
259
+ logger.error(`Failed to remove item: ${removeItemError}`);
260
+ }
261
+ }
419
262
  /**
420
263
  * produce a JSON object with meta-data and data value
421
264
  * @param value - the value of the item
@@ -423,15 +266,14 @@ var StorageCacheCommon = /** @class */ (function () {
423
266
  *
424
267
  * @return - the item which has the meta-data and the value
425
268
  */
426
- StorageCacheCommon.prototype.fillCacheItem = function (key, value, options) {
427
- var _a, _b;
428
- var item = {
429
- key: key,
269
+ fillCacheItem(key, value, options) {
270
+ const item = {
271
+ key,
430
272
  data: value,
431
273
  timestamp: (0, utils_1.getCurrentTime)(),
432
274
  visitedTime: (0, utils_1.getCurrentTime)(),
433
- priority: (_a = options.priority) !== null && _a !== void 0 ? _a : 0,
434
- expires: (_b = options.expires) !== null && _b !== void 0 ? _b : 0,
275
+ priority: options.priority ?? 0,
276
+ expires: options.expires ?? 0,
435
277
  type: typeof value,
436
278
  byteSize: 0,
437
279
  };
@@ -440,8 +282,8 @@ var StorageCacheCommon = /** @class */ (function () {
440
282
  // re-calculate using cache item with updated byteSize property
441
283
  item.byteSize = (0, utils_1.getByteLength)(JSON.stringify(item));
442
284
  return item;
443
- };
444
- StorageCacheCommon.prototype.sanitizeConfig = function () {
285
+ }
286
+ sanitizeConfig() {
445
287
  if (this.config.itemMaxSize > this.config.capacityInBytes) {
446
288
  logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');
447
289
  this.config.itemMaxSize = constants_1.defaultConfig.itemMaxSize;
@@ -456,54 +298,30 @@ var StorageCacheCommon = /** @class */ (function () {
456
298
  this.config.warningThreshold = constants_1.defaultConfig.warningThreshold;
457
299
  }
458
300
  // Set 5MB limit
459
- var cacheLimit = 5 * 1024 * 1024;
301
+ const cacheLimit = 5 * 1024 * 1024;
460
302
  if (this.config.capacityInBytes > cacheLimit) {
461
303
  logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');
462
304
  this.config.capacityInBytes = constants_1.defaultConfig.capacityInBytes;
463
305
  }
464
- };
306
+ }
465
307
  /**
466
308
  * increase current size of the cache
467
309
  *
468
310
  * @param amount - the amount of the cache szie which need to be increased
469
311
  */
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((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix), (size + amount).toString())];
479
- case 2:
480
- _a.sent();
481
- return [2 /*return*/];
482
- }
483
- });
484
- });
485
- };
312
+ async increaseCurrentSizeInBytes(amount) {
313
+ const size = await this.getCurrentCacheSize();
314
+ await this.getStorage().setItem((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix), (size + amount).toString());
315
+ }
486
316
  /**
487
317
  * decrease current size of the cache
488
318
  *
489
319
  * @param amount - the amount of the cache size which needs to be decreased
490
320
  */
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((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix), (size - amount).toString())];
500
- case 2:
501
- _a.sent();
502
- return [2 /*return*/];
503
- }
504
- });
505
- });
506
- };
321
+ async decreaseCurrentSizeInBytes(amount) {
322
+ const size = await this.getCurrentCacheSize();
323
+ await this.getStorage().setItem((0, utils_1.getCurrentSizeKey)(this.config.keyPrefix), (size - amount).toString());
324
+ }
507
325
  /**
508
326
  * update the visited time if item has been visited
509
327
  *
@@ -512,20 +330,11 @@ var StorageCacheCommon = /** @class */ (function () {
512
330
  *
513
331
  * @return the updated item
514
332
  */
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 = (0, utils_1.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
- };
333
+ async updateVisitedTime(item, prefixedKey) {
334
+ item.visitedTime = (0, utils_1.getCurrentTime)();
335
+ await this.getStorage().setItem(prefixedKey, JSON.stringify(item));
336
+ return item;
337
+ }
529
338
  /**
530
339
  * put item into cache
531
340
  *
@@ -533,38 +342,19 @@ var StorageCacheCommon = /** @class */ (function () {
533
342
  * @param itemData - the value of the item
534
343
  * @param itemSizeInBytes - the byte size of the item
535
344
  */
536
- StorageCacheCommon.prototype.setCacheItem = function (prefixedKey, item) {
537
- return __awaiter(this, void 0, void 0, function () {
538
- var setItemErr_1;
539
- return __generator(this, function (_a) {
540
- switch (_a.label) {
541
- case 0:
542
- // first try to update the current size of the cache.
543
- return [4 /*yield*/, this.increaseCurrentSizeInBytes(item.byteSize)];
544
- case 1:
545
- // first try to update the current size of the cache.
546
- _a.sent();
547
- _a.label = 2;
548
- case 2:
549
- _a.trys.push([2, 4, , 6]);
550
- return [4 /*yield*/, this.getStorage().setItem(prefixedKey, JSON.stringify(item))];
551
- case 3:
552
- _a.sent();
553
- return [3 /*break*/, 6];
554
- case 4:
555
- setItemErr_1 = _a.sent();
556
- // if some error happened, we need to rollback the current size
557
- return [4 /*yield*/, this.decreaseCurrentSizeInBytes(item.byteSize)];
558
- case 5:
559
- // if some error happened, we need to rollback the current size
560
- _a.sent();
561
- logger.error("Failed to set item ".concat(setItemErr_1));
562
- return [3 /*break*/, 6];
563
- case 6: return [2 /*return*/];
564
- }
565
- });
566
- });
567
- };
345
+ async setCacheItem(prefixedKey, item) {
346
+ // first try to update the current size of the cache.
347
+ await this.increaseCurrentSizeInBytes(item.byteSize);
348
+ // try to add the item into cache
349
+ try {
350
+ await this.getStorage().setItem(prefixedKey, JSON.stringify(item));
351
+ }
352
+ catch (setItemErr) {
353
+ // if some error happened, we need to rollback the current size
354
+ await this.decreaseCurrentSizeInBytes(item.byteSize);
355
+ logger.error(`Failed to set item ${setItemErr}`);
356
+ }
357
+ }
568
358
  /**
569
359
  * total space needed when poping out items
570
360
  *
@@ -572,23 +362,14 @@ var StorageCacheCommon = /** @class */ (function () {
572
362
  *
573
363
  * @return total space needed
574
364
  */
575
- StorageCacheCommon.prototype.sizeToPop = function (itemSize) {
576
- return __awaiter(this, void 0, void 0, function () {
577
- var cur, spaceItemNeed, cacheThresholdSpace;
578
- return __generator(this, function (_a) {
579
- switch (_a.label) {
580
- case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
581
- case 1:
582
- cur = _a.sent();
583
- spaceItemNeed = cur + itemSize - this.config.capacityInBytes;
584
- cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
585
- return [2 /*return*/, spaceItemNeed > cacheThresholdSpace
586
- ? spaceItemNeed
587
- : cacheThresholdSpace];
588
- }
589
- });
590
- });
591
- };
365
+ async sizeToPop(itemSize) {
366
+ const cur = await this.getCurrentCacheSize();
367
+ const spaceItemNeed = cur + itemSize - this.config.capacityInBytes;
368
+ const cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
369
+ return spaceItemNeed > cacheThresholdSpace
370
+ ? spaceItemNeed
371
+ : cacheThresholdSpace;
372
+ }
592
373
  /**
593
374
  * see whether cache is full
594
375
  *
@@ -596,19 +377,10 @@ var StorageCacheCommon = /** @class */ (function () {
596
377
  *
597
378
  * @return true if cache is full
598
379
  */
599
- StorageCacheCommon.prototype.isCacheFull = function (itemSize) {
600
- return __awaiter(this, void 0, void 0, function () {
601
- var cur;
602
- return __generator(this, function (_a) {
603
- switch (_a.label) {
604
- case 0: return [4 /*yield*/, this.getCurrentCacheSize()];
605
- case 1:
606
- cur = _a.sent();
607
- return [2 /*return*/, itemSize + cur > this.config.capacityInBytes];
608
- }
609
- });
610
- });
611
- };
380
+ async isCacheFull(itemSize) {
381
+ const cur = await this.getCurrentCacheSize();
382
+ return itemSize + cur > this.config.capacityInBytes;
383
+ }
612
384
  /**
613
385
  * get all the items we have, sort them by their priority,
614
386
  * if priority is same, sort them by their last visited time
@@ -617,69 +389,42 @@ var StorageCacheCommon = /** @class */ (function () {
617
389
  * @param keys - all the keys in this cache
618
390
  * @param sizeToPop - the total size of the items which needed to be poped out
619
391
  */
620
- StorageCacheCommon.prototype.popOutItems = function (keys, sizeToPop) {
621
- return __awaiter(this, void 0, void 0, function () {
622
- var items, remainedSize, i, val, item, i;
623
- return __generator(this, function (_a) {
624
- switch (_a.label) {
625
- case 0:
626
- items = [];
627
- remainedSize = sizeToPop;
628
- i = 0;
629
- _a.label = 1;
630
- case 1:
631
- if (!(i < keys.length)) return [3 /*break*/, 4];
632
- return [4 /*yield*/, this.getStorage().getItem(keys[i])];
633
- case 2:
634
- val = _a.sent();
635
- if (val != null) {
636
- item = JSON.parse(val);
637
- items.push(item);
638
- }
639
- _a.label = 3;
640
- case 3:
641
- i += 1;
642
- return [3 /*break*/, 1];
643
- case 4:
644
- // first compare priority
645
- // then compare visited time
646
- items.sort(function (a, b) {
647
- if (a.priority > b.priority) {
648
- return -1;
649
- }
650
- else if (a.priority < b.priority) {
651
- return 1;
652
- }
653
- else {
654
- if (a.visitedTime < b.visitedTime) {
655
- return -1;
656
- }
657
- else
658
- return 1;
659
- }
660
- });
661
- i = 0;
662
- _a.label = 5;
663
- case 5:
664
- if (!(i < items.length)) return [3 /*break*/, 8];
665
- // pop out items until we have enough room for new item
666
- return [4 /*yield*/, this.removeCacheItem(items[i].key, items[i].byteSize)];
667
- case 6:
668
- // pop out items until we have enough room for new item
669
- _a.sent();
670
- remainedSize -= items[i].byteSize;
671
- if (remainedSize <= 0) {
672
- return [2 /*return*/];
673
- }
674
- _a.label = 7;
675
- case 7:
676
- i += 1;
677
- return [3 /*break*/, 5];
678
- case 8: return [2 /*return*/];
392
+ async popOutItems(keys, sizeToPop) {
393
+ const items = [];
394
+ let remainedSize = sizeToPop;
395
+ for (let i = 0; i < keys.length; i += 1) {
396
+ const val = await this.getStorage().getItem(keys[i]);
397
+ if (val != null) {
398
+ const item = JSON.parse(val);
399
+ items.push(item);
400
+ }
401
+ }
402
+ // first compare priority
403
+ // then compare visited time
404
+ items.sort((a, b) => {
405
+ if (a.priority > b.priority) {
406
+ return -1;
407
+ }
408
+ else if (a.priority < b.priority) {
409
+ return 1;
410
+ }
411
+ else {
412
+ if (a.visitedTime < b.visitedTime) {
413
+ return -1;
679
414
  }
680
- });
415
+ else
416
+ return 1;
417
+ }
681
418
  });
682
- };
419
+ for (let i = 0; i < items.length; i += 1) {
420
+ // pop out items until we have enough room for new item
421
+ await this.removeCacheItem(items[i].key, items[i].byteSize);
422
+ remainedSize -= items[i].byteSize;
423
+ if (remainedSize <= 0) {
424
+ return;
425
+ }
426
+ }
427
+ }
683
428
  /**
684
429
  * Scan the storage and combine the following operations for efficiency
685
430
  * 1. Clear out all expired keys owned by this cache, not including the size key.
@@ -687,111 +432,37 @@ var StorageCacheCommon = /** @class */ (function () {
687
432
  *
688
433
  * @return The remaining valid keys
689
434
  */
690
- StorageCacheCommon.prototype.clearInvalidAndGetRemainingKeys = function () {
691
- return __awaiter(this, void 0, void 0, function () {
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) {
696
- case 0:
697
- remainingKeys = [];
698
- return [4 /*yield*/, this.getAllCacheKeys({
699
- omitSizeKey: true,
700
- })];
701
- case 1:
702
- keys = _b.sent();
703
- _b.label = 2;
704
- case 2:
705
- _b.trys.push([2, 9, 10, 11]);
706
- keys_1 = __values(keys), keys_1_1 = keys_1.next();
707
- _b.label = 3;
708
- case 3:
709
- if (!!keys_1_1.done) return [3 /*break*/, 8];
710
- key = keys_1_1.value;
711
- return [4 /*yield*/, this.isExpired(key)];
712
- case 4:
713
- if (!_b.sent()) return [3 /*break*/, 6];
714
- return [4 /*yield*/, this.removeCacheItem(key)];
715
- case 5:
716
- _b.sent();
717
- return [3 /*break*/, 7];
718
- case 6:
719
- remainingKeys.push(key);
720
- _b.label = 7;
721
- case 7:
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);
732
- }
733
- finally { if (e_5) throw e_5.error; }
734
- return [7 /*endfinally*/];
735
- case 11: return [2 /*return*/, remainingKeys];
736
- }
737
- });
435
+ async clearInvalidAndGetRemainingKeys() {
436
+ const remainingKeys = [];
437
+ const keys = await this.getAllCacheKeys({
438
+ omitSizeKey: true,
738
439
  });
739
- };
440
+ for (const key of keys) {
441
+ if (await this.isExpired(key)) {
442
+ await this.removeCacheItem(key);
443
+ }
444
+ else {
445
+ remainingKeys.push(key);
446
+ }
447
+ }
448
+ return remainingKeys;
449
+ }
740
450
  /**
741
451
  * clear the entire cache
742
452
  * The cache will abort and output a warning if error occurs
743
453
  * @return {Promise}
744
454
  */
745
- StorageCacheCommon.prototype.clear = function () {
746
- return __awaiter(this, void 0, void 0, function () {
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) {
751
- case 0:
752
- logger.debug("Clear Cache");
753
- _b.label = 1;
754
- case 1:
755
- _b.trys.push([1, 11, , 12]);
756
- return [4 /*yield*/, this.getAllKeys()];
757
- case 2:
758
- keys = _b.sent();
759
- _b.label = 3;
760
- case 3:
761
- _b.trys.push([3, 8, 9, 10]);
762
- keys_2 = __values(keys), keys_2_1 = keys_2.next();
763
- _b.label = 4;
764
- case 4:
765
- if (!!keys_2_1.done) return [3 /*break*/, 7];
766
- key = keys_2_1.value;
767
- return [4 /*yield*/, this.getStorage().removeItem(key)];
768
- case 5:
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);
782
- }
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*/];
791
- }
792
- });
793
- });
794
- };
795
- return StorageCacheCommon;
796
- }());
455
+ async clear() {
456
+ logger.debug(`Clear Cache`);
457
+ try {
458
+ const keys = await this.getAllKeys();
459
+ for (const key of keys) {
460
+ await this.getStorage().removeItem(key);
461
+ }
462
+ }
463
+ catch (e) {
464
+ logger.warn(`clear failed! ${e}`);
465
+ }
466
+ }
467
+ }
797
468
  exports.StorageCacheCommon = StorageCacheCommon;