UNPKG

55.6 kBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory(require("@aws-amplify/core"));
4 else if(typeof define === 'function' && define.amd)
5 define("aws_amplify_cache", ["@aws-amplify/core"], factory);
6 else if(typeof exports === 'object')
7 exports["aws_amplify_cache"] = factory(require("@aws-amplify/core"));
8 else
9 root["aws_amplify_cache"] = factory(root["@aws-amplify/core"]);
10})(this, function(__WEBPACK_EXTERNAL_MODULE__aws_amplify_core__) {
11return /******/ (function(modules) { // webpackBootstrap
12/******/ // The module cache
13/******/ var installedModules = {};
14/******/
15/******/ // The require function
16/******/ function __webpack_require__(moduleId) {
17/******/
18/******/ // Check if module is in cache
19/******/ if(installedModules[moduleId]) {
20/******/ return installedModules[moduleId].exports;
21/******/ }
22/******/ // Create a new module (and put it into the cache)
23/******/ var module = installedModules[moduleId] = {
24/******/ i: moduleId,
25/******/ l: false,
26/******/ exports: {}
27/******/ };
28/******/
29/******/ // Execute the module function
30/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31/******/
32/******/ // Flag the module as loaded
33/******/ module.l = true;
34/******/
35/******/ // Return the exports of the module
36/******/ return module.exports;
37/******/ }
38/******/
39/******/
40/******/ // expose the modules object (__webpack_modules__)
41/******/ __webpack_require__.m = modules;
42/******/
43/******/ // expose the module cache
44/******/ __webpack_require__.c = installedModules;
45/******/
46/******/ // define getter function for harmony exports
47/******/ __webpack_require__.d = function(exports, name, getter) {
48/******/ if(!__webpack_require__.o(exports, name)) {
49/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
50/******/ }
51/******/ };
52/******/
53/******/ // define __esModule on exports
54/******/ __webpack_require__.r = function(exports) {
55/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
56/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
57/******/ }
58/******/ Object.defineProperty(exports, '__esModule', { value: true });
59/******/ };
60/******/
61/******/ // create a fake namespace object
62/******/ // mode & 1: value is a module id, require it
63/******/ // mode & 2: merge all properties of value into the ns
64/******/ // mode & 4: return value when already ns object
65/******/ // mode & 8|1: behave like require
66/******/ __webpack_require__.t = function(value, mode) {
67/******/ if(mode & 1) value = __webpack_require__(value);
68/******/ if(mode & 8) return value;
69/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
70/******/ var ns = Object.create(null);
71/******/ __webpack_require__.r(ns);
72/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
73/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
74/******/ return ns;
75/******/ };
76/******/
77/******/ // getDefaultExport function for compatibility with non-harmony modules
78/******/ __webpack_require__.n = function(module) {
79/******/ var getter = module && module.__esModule ?
80/******/ function getDefault() { return module['default']; } :
81/******/ function getModuleExports() { return module; };
82/******/ __webpack_require__.d(getter, 'a', getter);
83/******/ return getter;
84/******/ };
85/******/
86/******/ // Object.prototype.hasOwnProperty.call
87/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
88/******/
89/******/ // __webpack_public_path__
90/******/ __webpack_require__.p = "";
91/******/
92/******/
93/******/ // Load entry module and return exports
94/******/ return __webpack_require__(__webpack_require__.s = "./lib-esm/index.js");
95/******/ })
96/************************************************************************/
97/******/ ({
98
99/***/ "./lib-esm/BrowserStorageCache.js":
100/*!****************************************!*\
101 !*** ./lib-esm/BrowserStorageCache.js ***!
102 \****************************************/
103/*! exports provided: BrowserStorageCacheClass, BrowserStorageCache, default */
104/***/ (function(module, __webpack_exports__, __webpack_require__) {
105
106"use strict";
107__webpack_require__.r(__webpack_exports__);
108/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserStorageCacheClass", function() { return BrowserStorageCacheClass; });
109/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserStorageCache", function() { return BrowserStorageCache; });
110/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils */ "./lib-esm/Utils/index.js");
111/* harmony import */ var _StorageCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./StorageCache */ "./lib-esm/StorageCache.js");
112/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
113/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__);
114/*
115 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
116 *
117 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
118 * the License. A copy of the License is located at
119 *
120 * http://aws.amazon.com/apache2.0/
121 *
122 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
123 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
124 * and limitations under the License.
125 */
126var __extends = undefined && undefined.__extends || function () {
127 var _extendStatics = function extendStatics(d, b) {
128 _extendStatics = Object.setPrototypeOf || {
129 __proto__: []
130 } instanceof Array && function (d, b) {
131 d.__proto__ = b;
132 } || function (d, b) {
133 for (var p in b) {
134 if (b.hasOwnProperty(p)) d[p] = b[p];
135 }
136 };
137
138 return _extendStatics(d, b);
139 };
140
141 return function (d, b) {
142 _extendStatics(d, b);
143
144 function __() {
145 this.constructor = d;
146 }
147
148 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
149 };
150}();
151
152
153
154
155var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__["ConsoleLogger"]('Cache');
156/**
157 * Customized storage based on the SessionStorage or LocalStorage with LRU implemented
158 */
159
160var BrowserStorageCacheClass = function (_super) {
161 __extends(BrowserStorageCacheClass, _super);
162 /**
163 * initialize the cache
164 * @param config - the configuration of the cache
165 */
166
167
168 function BrowserStorageCacheClass(config) {
169 var _this = this;
170
171 var cacheConfig = config ? Object.assign({}, _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"], config) : _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"];
172 _this = _super.call(this, cacheConfig) || this;
173 _this.config.storage = cacheConfig.storage;
174 _this.getItem = _this.getItem.bind(_this);
175 _this.setItem = _this.setItem.bind(_this);
176 _this.removeItem = _this.removeItem.bind(_this);
177 return _this;
178 }
179 /**
180 * decrease current size of the cache
181 *
182 * @private
183 * @param amount - the amount of the cache size which needs to be decreased
184 */
185
186
187 BrowserStorageCacheClass.prototype._decreaseCurSizeInBytes = function (amount) {
188 var curSize = this.getCacheCurSize();
189 this.config.storage.setItem(this.cacheCurSizeKey, (curSize - amount).toString());
190 };
191 /**
192 * increase current size of the cache
193 *
194 * @private
195 * @param amount - the amount of the cache szie which need to be increased
196 */
197
198
199 BrowserStorageCacheClass.prototype._increaseCurSizeInBytes = function (amount) {
200 var curSize = this.getCacheCurSize();
201 this.config.storage.setItem(this.cacheCurSizeKey, (curSize + amount).toString());
202 };
203 /**
204 * update the visited time if item has been visited
205 *
206 * @private
207 * @param item - the item which need to be refreshed
208 * @param prefixedKey - the key of the item
209 *
210 * @return the refreshed item
211 */
212
213
214 BrowserStorageCacheClass.prototype._refreshItem = function (item, prefixedKey) {
215 item.visitedTime = Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])();
216 this.config.storage.setItem(prefixedKey, JSON.stringify(item));
217 return item;
218 };
219 /**
220 * check wether item is expired
221 *
222 * @private
223 * @param key - the key of the item
224 *
225 * @return true if the item is expired.
226 */
227
228
229 BrowserStorageCacheClass.prototype._isExpired = function (key) {
230 var text = this.config.storage.getItem(key);
231 var item = JSON.parse(text);
232
233 if (Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])() >= item.expires) {
234 return true;
235 }
236
237 return false;
238 };
239 /**
240 * delete item from cache
241 *
242 * @private
243 * @param prefixedKey - the key of the item
244 * @param size - optional, the byte size of the item
245 */
246
247
248 BrowserStorageCacheClass.prototype._removeItem = function (prefixedKey, size) {
249 var itemSize = size ? size : JSON.parse(this.config.storage.getItem(prefixedKey)).byteSize;
250
251 this._decreaseCurSizeInBytes(itemSize); // remove the cache item
252
253
254 this.config.storage.removeItem(prefixedKey);
255 };
256 /**
257 * put item into cache
258 *
259 * @private
260 * @param prefixedKey - the key of the item
261 * @param itemData - the value of the item
262 * @param itemSizeInBytes - the byte size of the item
263 */
264
265
266 BrowserStorageCacheClass.prototype._setItem = function (prefixedKey, item) {
267 // update the cache size
268 this._increaseCurSizeInBytes(item.byteSize);
269
270 try {
271 this.config.storage.setItem(prefixedKey, JSON.stringify(item));
272 } catch (setItemErr) {
273 // if failed, we need to rollback the cache size
274 this._decreaseCurSizeInBytes(item.byteSize);
275
276 logger.error("Failed to set item " + setItemErr);
277 }
278 };
279 /**
280 * total space needed when poping out items
281 *
282 * @private
283 * @param itemSize
284 *
285 * @return total space needed
286 */
287
288
289 BrowserStorageCacheClass.prototype._sizeToPop = function (itemSize) {
290 var spaceItemNeed = this.getCacheCurSize() + itemSize - this.config.capacityInBytes;
291 var cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
292 return spaceItemNeed > cacheThresholdSpace ? spaceItemNeed : cacheThresholdSpace;
293 };
294 /**
295 * see whether cache is full
296 *
297 * @private
298 * @param itemSize
299 *
300 * @return true if cache is full
301 */
302
303
304 BrowserStorageCacheClass.prototype._isCacheFull = function (itemSize) {
305 return itemSize + this.getCacheCurSize() > this.config.capacityInBytes;
306 };
307 /**
308 * scan the storage and find out all the keys owned by this cache
309 * also clean the expired keys while scanning
310 *
311 * @private
312 *
313 * @return array of keys
314 */
315
316
317 BrowserStorageCacheClass.prototype._findValidKeys = function () {
318 var keys = [];
319 var keyInCache = []; // get all keys in Storage
320
321 for (var i = 0; i < this.config.storage.length; i += 1) {
322 keyInCache.push(this.config.storage.key(i));
323 } // find those items which belong to our cache and also clean those expired items
324
325
326 for (var i = 0; i < keyInCache.length; i += 1) {
327 var key = keyInCache[i];
328
329 if (key.indexOf(this.config.keyPrefix) === 0 && key !== this.cacheCurSizeKey) {
330 if (this._isExpired(key)) {
331 this._removeItem(key);
332 } else {
333 keys.push(key);
334 }
335 }
336 }
337
338 return keys;
339 };
340 /**
341 * get all the items we have, sort them by their priority,
342 * if priority is same, sort them by their last visited time
343 * pop out items from the low priority (5 is the lowest)
344 *
345 * @private
346 * @param keys - all the keys in this cache
347 * @param sizeToPop - the total size of the items which needed to be poped out
348 */
349
350
351 BrowserStorageCacheClass.prototype._popOutItems = function (keys, sizeToPop) {
352 var items = [];
353 var remainedSize = sizeToPop; // get the items from Storage
354
355 for (var i = 0; i < keys.length; i += 1) {
356 var val = this.config.storage.getItem(keys[i]);
357
358 if (val != null) {
359 var item = JSON.parse(val);
360 items.push(item);
361 }
362 } // first compare priority
363 // then compare visited time
364
365
366 items.sort(function (a, b) {
367 if (a.priority > b.priority) {
368 return -1;
369 } else if (a.priority < b.priority) {
370 return 1;
371 } else {
372 if (a.visitedTime < b.visitedTime) {
373 return -1;
374 } else return 1;
375 }
376 });
377
378 for (var i = 0; i < items.length; i += 1) {
379 // pop out items until we have enough room for new item
380 this._removeItem(items[i].key, items[i].byteSize);
381
382 remainedSize -= items[i].byteSize;
383
384 if (remainedSize <= 0) {
385 return;
386 }
387 }
388 };
389 /**
390 * Set item into cache. You can put number, string, boolean or object.
391 * The cache will first check whether has the same key.
392 * If it has, it will delete the old item and then put the new item in
393 * The cache will pop out items if it is full
394 * You can specify the cache item options. The cache will abort and output a warning:
395 * If the key is invalid
396 * If the size of the item exceeds itemMaxSize.
397 * If the value is undefined
398 * If incorrect cache item configuration
399 * If error happened with browser storage
400 *
401 * @param key - the key of the item
402 * @param value - the value of the item
403 * @param {Object} [options] - optional, the specified meta-data
404 */
405
406
407 BrowserStorageCacheClass.prototype.setItem = function (key, value, options) {
408 logger.log("Set item: key is " + key + ", value is " + value + " with options: " + options);
409 var prefixedKey = this.config.keyPrefix + key; // invalid keys
410
411 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
412 logger.warn("Invalid key: should not be empty or 'CurSize'");
413 return;
414 }
415
416 if (typeof value === 'undefined') {
417 logger.warn("The value of item should not be undefined!");
418 return;
419 }
420
421 var cacheItemOptions = {
422 priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority,
423 expires: options && options.expires !== undefined ? options.expires : this.config.defaultTTL + Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])()
424 };
425
426 if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
427 logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
428 return;
429 }
430
431 var item = this.fillCacheItem(prefixedKey, value, cacheItemOptions); // check wether this item is too big;
432
433 if (item.byteSize > this.config.itemMaxSize) {
434 logger.warn("Item with key: " + key + " you are trying to put into is too big!");
435 return;
436 }
437
438 try {
439 // first look into the storage, if it exists, delete it.
440 var val = this.config.storage.getItem(prefixedKey);
441
442 if (val) {
443 this._removeItem(prefixedKey, JSON.parse(val).byteSize);
444 } // check whether the cache is full
445
446
447 if (this._isCacheFull(item.byteSize)) {
448 var validKeys = this._findValidKeys(); // check again and then pop out items
449
450
451 if (this._isCacheFull(item.byteSize)) {
452 var sizeToPop = this._sizeToPop(item.byteSize);
453
454 this._popOutItems(validKeys, sizeToPop);
455 }
456 } // put item in the cache
457 // may failed due to storage full
458
459
460 this._setItem(prefixedKey, item);
461 } catch (e) {
462 logger.warn("setItem failed! " + e);
463 }
464 };
465 /**
466 * Get item from cache. It will return null if item doesn’t exist or it has been expired.
467 * If you specified callback function in the options,
468 * then the function will be executed if no such item in the cache
469 * and finally put the return value into cache.
470 * Please make sure the callback function will return the value you want to put into the cache.
471 * The cache will abort output a warning:
472 * If the key is invalid
473 * If error happened with browser storage
474 *
475 * @param key - the key of the item
476 * @param {Object} [options] - the options of callback function
477 *
478 * @return - return the value of the item
479 */
480
481
482 BrowserStorageCacheClass.prototype.getItem = function (key, options) {
483 logger.log("Get item: key is " + key + " with options " + options);
484 var ret = null;
485 var prefixedKey = this.config.keyPrefix + key;
486
487 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
488 logger.warn("Invalid key: should not be empty or 'CurSize'");
489 return null;
490 }
491
492 try {
493 ret = this.config.storage.getItem(prefixedKey);
494
495 if (ret != null) {
496 if (this._isExpired(prefixedKey)) {
497 // if expired, remove that item and return null
498 this._removeItem(prefixedKey, JSON.parse(ret).byteSize);
499
500 ret = null;
501 } else {
502 // if not expired, great, return the value and refresh it
503 var item = JSON.parse(ret);
504 item = this._refreshItem(item, prefixedKey);
505 return item.data;
506 }
507 }
508
509 if (options && options.callback !== undefined) {
510 var val = options.callback();
511
512 if (val !== null) {
513 this.setItem(key, val, options);
514 }
515
516 return val;
517 }
518
519 return null;
520 } catch (e) {
521 logger.warn("getItem failed! " + e);
522 return null;
523 }
524 };
525 /**
526 * remove item from the cache
527 * The cache will abort output a warning:
528 * If error happened with browser storage
529 * @param key - the key of the item
530 */
531
532
533 BrowserStorageCacheClass.prototype.removeItem = function (key) {
534 logger.log("Remove item: key is " + key);
535 var prefixedKey = this.config.keyPrefix + key;
536
537 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
538 return;
539 }
540
541 try {
542 var val = this.config.storage.getItem(prefixedKey);
543
544 if (val) {
545 this._removeItem(prefixedKey, JSON.parse(val).byteSize);
546 }
547 } catch (e) {
548 logger.warn("removeItem failed! " + e);
549 }
550 };
551 /**
552 * clear the entire cache
553 * The cache will abort output a warning:
554 * If error happened with browser storage
555 */
556
557
558 BrowserStorageCacheClass.prototype.clear = function () {
559 logger.log("Clear Cache");
560 var keysToRemove = [];
561
562 for (var i = 0; i < this.config.storage.length; i += 1) {
563 var key = this.config.storage.key(i);
564
565 if (key.indexOf(this.config.keyPrefix) === 0) {
566 keysToRemove.push(key);
567 }
568 }
569
570 try {
571 for (var i = 0; i < keysToRemove.length; i += 1) {
572 this.config.storage.removeItem(keysToRemove[i]);
573 }
574 } catch (e) {
575 logger.warn("clear failed! " + e);
576 }
577 };
578 /**
579 * Return all the keys in the cache.
580 *
581 * @return - all keys in the cache
582 */
583
584
585 BrowserStorageCacheClass.prototype.getAllKeys = function () {
586 var keys = [];
587
588 for (var i = 0; i < this.config.storage.length; i += 1) {
589 var key = this.config.storage.key(i);
590
591 if (key.indexOf(this.config.keyPrefix) === 0 && key !== this.cacheCurSizeKey) {
592 keys.push(key.substring(this.config.keyPrefix.length));
593 }
594 }
595
596 return keys;
597 };
598 /**
599 * return the current size of the cache
600 *
601 * @return - current size of the cache
602 */
603
604
605 BrowserStorageCacheClass.prototype.getCacheCurSize = function () {
606 var ret = this.config.storage.getItem(this.cacheCurSizeKey);
607
608 if (!ret) {
609 this.config.storage.setItem(this.cacheCurSizeKey, '0');
610 ret = '0';
611 }
612
613 return Number(ret);
614 };
615 /**
616 * Return a new instance of cache with customized configuration.
617 * @param config - the customized configuration
618 *
619 * @return - new instance of Cache
620 */
621
622
623 BrowserStorageCacheClass.prototype.createInstance = function (config) {
624 if (!config.keyPrefix || config.keyPrefix === _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].keyPrefix) {
625 logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');
626 config.keyPrefix = _Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"].toString();
627 }
628
629 return new BrowserStorageCacheClass(config);
630 };
631
632 return BrowserStorageCacheClass;
633}(_StorageCache__WEBPACK_IMPORTED_MODULE_1__["StorageCache"]);
634
635
636var BrowserStorageCache = new BrowserStorageCacheClass();
637/**
638 * @deprecated use named import
639 */
640
641/* harmony default export */ __webpack_exports__["default"] = (BrowserStorageCache);
642
643/***/ }),
644
645/***/ "./lib-esm/InMemoryCache.js":
646/*!**********************************!*\
647 !*** ./lib-esm/InMemoryCache.js ***!
648 \**********************************/
649/*! exports provided: InMemoryCacheClass, InMemoryCache, default */
650/***/ (function(module, __webpack_exports__, __webpack_require__) {
651
652"use strict";
653__webpack_require__.r(__webpack_exports__);
654/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InMemoryCacheClass", function() { return InMemoryCacheClass; });
655/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InMemoryCache", function() { return InMemoryCache; });
656/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils */ "./lib-esm/Utils/index.js");
657/* harmony import */ var _StorageCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./StorageCache */ "./lib-esm/StorageCache.js");
658/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
659/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__);
660/*
661 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
662 *
663 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
664 * the License. A copy of the License is located at
665 *
666 * http://aws.amazon.com/apache2.0/
667 *
668 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
669 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
670 * and limitations under the License.
671 */
672var __extends = undefined && undefined.__extends || function () {
673 var _extendStatics = function extendStatics(d, b) {
674 _extendStatics = Object.setPrototypeOf || {
675 __proto__: []
676 } instanceof Array && function (d, b) {
677 d.__proto__ = b;
678 } || function (d, b) {
679 for (var p in b) {
680 if (b.hasOwnProperty(p)) d[p] = b[p];
681 }
682 };
683
684 return _extendStatics(d, b);
685 };
686
687 return function (d, b) {
688 _extendStatics(d, b);
689
690 function __() {
691 this.constructor = d;
692 }
693
694 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
695 };
696}();
697
698var __values = undefined && undefined.__values || function (o) {
699 var s = typeof Symbol === "function" && Symbol.iterator,
700 m = s && o[s],
701 i = 0;
702 if (m) return m.call(o);
703 if (o && typeof o.length === "number") return {
704 next: function next() {
705 if (o && i >= o.length) o = void 0;
706 return {
707 value: o && o[i++],
708 done: !o
709 };
710 }
711 };
712 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
713};
714
715
716
717
718var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_2__["ConsoleLogger"]('InMemoryCache');
719/**
720 * Customized in-memory cache with LRU implemented
721 * @member cacheObj - object which store items
722 * @member cacheList - list of keys in the cache with LRU
723 * @member curSizeInBytes - current size of the cache
724 * @member maxPriority - max of the priority
725 * @member cacheSizeLimit - the limit of cache size
726 */
727
728var InMemoryCacheClass = function (_super) {
729 __extends(InMemoryCacheClass, _super);
730 /**
731 * initialize the cache
732 *
733 * @param config - the configuration of the cache
734 */
735
736
737 function InMemoryCacheClass(config) {
738 var _this = this;
739
740 var cacheConfig = config ? Object.assign({}, _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"], config) : _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"];
741 _this = _super.call(this, cacheConfig) || this;
742 logger.debug('now we start!');
743 _this.cacheList = [];
744 _this.curSizeInBytes = 0;
745 _this.maxPriority = 5;
746 _this.getItem = _this.getItem.bind(_this);
747 _this.setItem = _this.setItem.bind(_this);
748 _this.removeItem = _this.removeItem.bind(_this); // initialize list for every priority
749
750 for (var i = 0; i < _this.maxPriority; i += 1) {
751 _this.cacheList[i] = new _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheList"]();
752 }
753
754 return _this;
755 }
756 /**
757 * decrease current size of the cache
758 *
759 * @param amount - the amount of the cache size which needs to be decreased
760 */
761
762
763 InMemoryCacheClass.prototype._decreaseCurSizeInBytes = function (amount) {
764 this.curSizeInBytes -= amount;
765 };
766 /**
767 * increase current size of the cache
768 *
769 * @param amount - the amount of the cache szie which need to be increased
770 */
771
772
773 InMemoryCacheClass.prototype._increaseCurSizeInBytes = function (amount) {
774 this.curSizeInBytes += amount;
775 };
776 /**
777 * check whether item is expired
778 *
779 * @param key - the key of the item
780 *
781 * @return true if the item is expired.
782 */
783
784
785 InMemoryCacheClass.prototype._isExpired = function (key) {
786 var text = _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].getItem(key);
787 var item = JSON.parse(text);
788
789 if (Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])() >= item.expires) {
790 return true;
791 }
792
793 return false;
794 };
795 /**
796 * delete item from cache
797 *
798 * @param prefixedKey - the key of the item
799 * @param listIdx - indicates which cache list the key belongs to
800 */
801
802
803 InMemoryCacheClass.prototype._removeItem = function (prefixedKey, listIdx) {
804 // delete the key from the list
805 this.cacheList[listIdx].removeItem(prefixedKey); // decrease the current size of the cache
806
807 this._decreaseCurSizeInBytes(JSON.parse(_Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].getItem(prefixedKey)).byteSize); // finally remove the item from memory
808
809
810 _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].removeItem(prefixedKey);
811 };
812 /**
813 * put item into cache
814 *
815 * @param prefixedKey - the key of the item
816 * @param itemData - the value of the item
817 * @param itemSizeInBytes - the byte size of the item
818 * @param listIdx - indicates which cache list the key belongs to
819 */
820
821
822 InMemoryCacheClass.prototype._setItem = function (prefixedKey, item, listIdx) {
823 // insert the key into the list
824 this.cacheList[listIdx].insertItem(prefixedKey); // increase the current size of the cache
825
826 this._increaseCurSizeInBytes(item.byteSize); // finally add the item into memory
827
828
829 _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].setItem(prefixedKey, JSON.stringify(item));
830 };
831 /**
832 * see whether cache is full
833 *
834 * @param itemSize
835 *
836 * @return true if cache is full
837 */
838
839
840 InMemoryCacheClass.prototype._isCacheFull = function (itemSize) {
841 return this.curSizeInBytes + itemSize > this.config.capacityInBytes;
842 };
843 /**
844 * check whether the cache contains the key
845 *
846 * @param key
847 */
848
849
850 InMemoryCacheClass.prototype.containsKey = function (key) {
851 var prefixedKey = this.config.keyPrefix + key;
852
853 for (var i = 0; i < this.maxPriority; i += 1) {
854 if (this.cacheList[i].containsKey(prefixedKey)) {
855 return i + 1;
856 }
857 }
858
859 return -1;
860 };
861 /**
862 * * Set item into cache. You can put number, string, boolean or object.
863 * The cache will first check whether has the same key.
864 * If it has, it will delete the old item and then put the new item in
865 * The cache will pop out items if it is full
866 * You can specify the cache item options. The cache will abort and output a warning:
867 * If the key is invalid
868 * If the size of the item exceeds itemMaxSize.
869 * If the value is undefined
870 * If incorrect cache item configuration
871 * If error happened with browser storage
872 *
873 * @param key - the key of the item
874 * @param value - the value of the item
875 * @param options - optional, the specified meta-data
876 *
877 * @throws if the item is too big which exceeds the limit of single item size
878 * @throws if the key is invalid
879 */
880
881
882 InMemoryCacheClass.prototype.setItem = function (key, value, options) {
883 var prefixedKey = this.config.keyPrefix + key; // invalid keys
884
885 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
886 logger.warn("Invalid key: should not be empty or 'CurSize'");
887 return;
888 }
889
890 if (typeof value === 'undefined') {
891 logger.warn("The value of item should not be undefined!");
892 return;
893 }
894
895 var cacheItemOptions = {
896 priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority,
897 expires: options && options.expires !== undefined ? options.expires : this.config.defaultTTL + Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])()
898 };
899
900 if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
901 logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
902 return;
903 }
904
905 var item = this.fillCacheItem(prefixedKey, value, cacheItemOptions); // check wether this item is too big;
906
907 if (item.byteSize > this.config.itemMaxSize) {
908 logger.warn("Item with key: " + key + " you are trying to put into is too big!");
909 return;
910 } // if key already in the cache, then delete it.
911
912
913 var presentKeyPrio = this.containsKey(key);
914
915 if (presentKeyPrio !== -1) {
916 this._removeItem(prefixedKey, presentKeyPrio - 1);
917 } // pop out items in the cache when cache is full based on LRU
918 // first start from lowest priority cache list
919
920
921 var cacheListIdx = this.maxPriority - 1;
922
923 while (this._isCacheFull(item.byteSize) && cacheListIdx >= 0) {
924 if (!this.cacheList[cacheListIdx].isEmpty()) {
925 var popedItemKey = this.cacheList[cacheListIdx].getLastItem();
926
927 this._removeItem(popedItemKey, cacheListIdx);
928 } else {
929 cacheListIdx -= 1;
930 }
931 }
932
933 this._setItem(prefixedKey, item, Number(item.priority) - 1);
934 };
935 /**
936 * Get item from cache. It will return null if item doesn’t exist or it has been expired.
937 * If you specified callback function in the options,
938 * then the function will be executed if no such item in the cache
939 * and finally put the return value into cache.
940 * Please make sure the callback function will return the value you want to put into the cache.
941 * The cache will abort output a warning:
942 * If the key is invalid
943 *
944 * @param key - the key of the item
945 * @param options - the options of callback function
946 */
947
948
949 InMemoryCacheClass.prototype.getItem = function (key, options) {
950 var ret = null;
951 var prefixedKey = this.config.keyPrefix + key;
952
953 if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
954 logger.warn("Invalid key: should not be empty or 'CurSize'");
955 return null;
956 } // check whether it's in the cachelist
957
958
959 var presentKeyPrio = this.containsKey(key);
960
961 if (presentKeyPrio !== -1) {
962 if (this._isExpired(prefixedKey)) {
963 // if expired, remove that item and return null
964 this._removeItem(prefixedKey, presentKeyPrio - 1);
965 } else {
966 // if not expired, great, return the value and refresh it
967 ret = _Utils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"].getItem(prefixedKey);
968 var item = JSON.parse(ret);
969 this.cacheList[item.priority - 1].refresh(prefixedKey);
970 return item.data;
971 }
972 }
973
974 if (options && options.callback !== undefined) {
975 var val = options.callback();
976
977 if (val !== null) {
978 this.setItem(key, val, options);
979 }
980
981 return val;
982 }
983
984 return null;
985 };
986 /**
987 * remove item from the cache
988 *
989 * @param key - the key of the item
990 */
991
992
993 InMemoryCacheClass.prototype.removeItem = function (key) {
994 var prefixedKey = this.config.keyPrefix + key; // check if the key is in the cache
995
996 var presentKeyPrio = this.containsKey(key);
997
998 if (presentKeyPrio !== -1) {
999 this._removeItem(prefixedKey, presentKeyPrio - 1);
1000 }
1001 };
1002 /**
1003 * clear the entire cache
1004 */
1005
1006
1007 InMemoryCacheClass.prototype.clear = function () {
1008 var e_1, _a;
1009
1010 for (var i = 0; i < this.maxPriority; i += 1) {
1011 try {
1012 for (var _b = (e_1 = void 0, __values(this.cacheList[i].getKeys())), _c = _b.next(); !_c.done; _c = _b.next()) {
1013 var key = _c.value;
1014
1015 this._removeItem(key, i);
1016 }
1017 } catch (e_1_1) {
1018 e_1 = {
1019 error: e_1_1
1020 };
1021 } finally {
1022 try {
1023 if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
1024 } finally {
1025 if (e_1) throw e_1.error;
1026 }
1027 }
1028 }
1029 };
1030 /**
1031 * Return all the keys in the cache.
1032 */
1033
1034
1035 InMemoryCacheClass.prototype.getAllKeys = function () {
1036 var e_2, _a;
1037
1038 var keys = [];
1039
1040 for (var i = 0; i < this.maxPriority; i += 1) {
1041 try {
1042 for (var _b = (e_2 = void 0, __values(this.cacheList[i].getKeys())), _c = _b.next(); !_c.done; _c = _b.next()) {
1043 var key = _c.value;
1044 keys.push(key.substring(this.config.keyPrefix.length));
1045 }
1046 } catch (e_2_1) {
1047 e_2 = {
1048 error: e_2_1
1049 };
1050 } finally {
1051 try {
1052 if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
1053 } finally {
1054 if (e_2) throw e_2.error;
1055 }
1056 }
1057 }
1058
1059 return keys;
1060 };
1061 /**
1062 * return the current size of the cache
1063 *
1064 * @return the current size of the cache
1065 */
1066
1067
1068 InMemoryCacheClass.prototype.getCacheCurSize = function () {
1069 return this.curSizeInBytes;
1070 };
1071 /**
1072 * Return a new instance of cache with customized configuration.
1073 * @param config - the customized configuration
1074 */
1075
1076
1077 InMemoryCacheClass.prototype.createInstance = function (config) {
1078 return new InMemoryCacheClass(config);
1079 };
1080
1081 return InMemoryCacheClass;
1082}(_StorageCache__WEBPACK_IMPORTED_MODULE_1__["StorageCache"]);
1083
1084
1085var InMemoryCache = new InMemoryCacheClass();
1086/**
1087 * @deprecated use named import
1088 */
1089
1090/* harmony default export */ __webpack_exports__["default"] = (InMemoryCache);
1091
1092/***/ }),
1093
1094/***/ "./lib-esm/StorageCache.js":
1095/*!*********************************!*\
1096 !*** ./lib-esm/StorageCache.js ***!
1097 \*********************************/
1098/*! exports provided: StorageCache, default */
1099/***/ (function(module, __webpack_exports__, __webpack_require__) {
1100
1101"use strict";
1102__webpack_require__.r(__webpack_exports__);
1103/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StorageCache", function() { return StorageCache; });
1104/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils */ "./lib-esm/Utils/index.js");
1105/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
1106/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__);
1107function _typeof(obj) {
1108 "@babel/helpers - typeof";
1109
1110 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
1111 _typeof = function _typeof(obj) {
1112 return typeof obj;
1113 };
1114 } else {
1115 _typeof = function _typeof(obj) {
1116 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
1117 };
1118 }
1119
1120 return _typeof(obj);
1121}
1122/*
1123 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1124 *
1125 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1126 * the License. A copy of the License is located at
1127 *
1128 * http://aws.amazon.com/apache2.0/
1129 *
1130 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1131 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1132 * and limitations under the License.
1133 */
1134
1135
1136
1137
1138var logger = new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_1__["ConsoleLogger"]('StorageCache');
1139/**
1140 * Initialization of the cache
1141 *
1142 */
1143
1144var StorageCache = function () {
1145 /**
1146 * Initialize the cache
1147 * @param config - the configuration of the cache
1148 */
1149 function StorageCache(config) {
1150 this.config = Object.assign({}, config);
1151 this.cacheCurSizeKey = this.config.keyPrefix + 'CurSize';
1152 this.checkConfig();
1153 }
1154
1155 StorageCache.prototype.getModuleName = function () {
1156 return 'Cache';
1157 };
1158
1159 StorageCache.prototype.checkConfig = function () {
1160 // check configuration
1161 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.capacityInBytes)) {
1162 logger.error('Invalid parameter: capacityInBytes. It should be an Integer. Setting back to default.');
1163 this.config.capacityInBytes = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].capacityInBytes;
1164 }
1165
1166 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.itemMaxSize)) {
1167 logger.error('Invalid parameter: itemMaxSize. It should be an Integer. Setting back to default.');
1168 this.config.itemMaxSize = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].itemMaxSize;
1169 }
1170
1171 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.defaultTTL)) {
1172 logger.error('Invalid parameter: defaultTTL. It should be an Integer. Setting back to default.');
1173 this.config.defaultTTL = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].defaultTTL;
1174 }
1175
1176 if (!Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["isInteger"])(this.config.defaultPriority)) {
1177 logger.error('Invalid parameter: defaultPriority. It should be an Integer. Setting back to default.');
1178 this.config.defaultPriority = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].defaultPriority;
1179 }
1180
1181 if (this.config.itemMaxSize > this.config.capacityInBytes) {
1182 logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');
1183 this.config.itemMaxSize = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].itemMaxSize;
1184 }
1185
1186 if (this.config.defaultPriority > 5 || this.config.defaultPriority < 1) {
1187 logger.error('Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default.');
1188 this.config.defaultPriority = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].defaultPriority;
1189 }
1190
1191 if (Number(this.config.warningThreshold) > 1 || Number(this.config.warningThreshold) < 0) {
1192 logger.error('Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default.');
1193 this.config.warningThreshold = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].warningThreshold;
1194 } // set 5MB limit
1195
1196
1197 var cacheLimit = 5 * 1024 * 1024;
1198
1199 if (this.config.capacityInBytes > cacheLimit) {
1200 logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');
1201 this.config.capacityInBytes = _Utils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"].capacityInBytes;
1202 }
1203 };
1204 /**
1205 * produce a JSON object with meta-data and data value
1206 * @param value - the value of the item
1207 * @param options - optional, the specified meta-data
1208 *
1209 * @return - the item which has the meta-data and the value
1210 */
1211
1212
1213 StorageCache.prototype.fillCacheItem = function (key, value, options) {
1214 var ret = {
1215 key: key,
1216 data: value,
1217 timestamp: Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])(),
1218 visitedTime: Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"])(),
1219 priority: options.priority,
1220 expires: options.expires,
1221 type: _typeof(value),
1222 byteSize: 0
1223 };
1224 ret.byteSize = Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getByteLength"])(JSON.stringify(ret)); // for accurate size
1225
1226 ret.byteSize = Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["getByteLength"])(JSON.stringify(ret));
1227 return ret;
1228 };
1229 /**
1230 * set cache with customized configuration
1231 * @param config - customized configuration
1232 *
1233 * @return - the current configuration
1234 */
1235
1236
1237 StorageCache.prototype.configure = function (config) {
1238 if (!config) {
1239 return this.config;
1240 }
1241
1242 if (config.keyPrefix) {
1243 logger.warn("Don't try to configure keyPrefix!");
1244 }
1245
1246 this.config = Object.assign({}, this.config, config, config.Cache);
1247 this.checkConfig();
1248 return this.config;
1249 };
1250
1251 return StorageCache;
1252}();
1253
1254
1255/**
1256 * @deprecated use named import
1257 */
1258
1259/* harmony default export */ __webpack_exports__["default"] = (StorageCache);
1260
1261/***/ }),
1262
1263/***/ "./lib-esm/Utils/CacheList.js":
1264/*!************************************!*\
1265 !*** ./lib-esm/Utils/CacheList.js ***!
1266 \************************************/
1267/*! exports provided: default */
1268/***/ (function(module, __webpack_exports__, __webpack_require__) {
1269
1270"use strict";
1271__webpack_require__.r(__webpack_exports__);
1272/*
1273 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1274 *
1275 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1276 * the License. A copy of the License is located at
1277 *
1278 * http://aws.amazon.com/apache2.0/
1279 *
1280 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1281 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1282 * and limitations under the License.
1283 */
1284var __values = undefined && undefined.__values || function (o) {
1285 var s = typeof Symbol === "function" && Symbol.iterator,
1286 m = s && o[s],
1287 i = 0;
1288 if (m) return m.call(o);
1289 if (o && typeof o.length === "number") return {
1290 next: function next() {
1291 if (o && i >= o.length) o = void 0;
1292 return {
1293 value: o && o[i++],
1294 done: !o
1295 };
1296 }
1297 };
1298 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1299};
1300
1301var DoubleLinkedNode = function () {
1302 function DoubleLinkedNode(keyVal) {
1303 this.key = keyVal ? keyVal : '';
1304 this.prevNode = null;
1305 this.nextNode = null;
1306 }
1307
1308 return DoubleLinkedNode;
1309}();
1310/**
1311 * double linked list plus a hash table inside
1312 * each key in the cache stored as a node in the list
1313 * recently visited node will be rotated to the head
1314 * so the Last Recently Visited node will be at the tail
1315 *
1316 * @member head - dummy head of the linked list
1317 * @member tail - dummy tail of the linked list
1318 * @member hashtable - the hashtable which maps cache key to list node
1319 * @member length - length of the list
1320 */
1321
1322
1323var CacheList = function () {
1324 /**
1325 * initialization
1326 */
1327 function CacheList() {
1328 this.head = new DoubleLinkedNode();
1329 this.tail = new DoubleLinkedNode();
1330 this.hashtable = {};
1331 this.length = 0;
1332 this.head.nextNode = this.tail;
1333 this.tail.prevNode = this.head;
1334 }
1335 /**
1336 * insert node to the head of the list
1337 *
1338 * @param node
1339 */
1340
1341
1342 CacheList.prototype.insertNodeToHead = function (node) {
1343 var tmp = this.head.nextNode;
1344 this.head.nextNode = node;
1345 node.nextNode = tmp;
1346 node.prevNode = this.head;
1347 tmp.prevNode = node;
1348 this.length = this.length + 1;
1349 };
1350 /**
1351 * remove node
1352 *
1353 * @param node
1354 */
1355
1356
1357 CacheList.prototype.removeNode = function (node) {
1358 node.prevNode.nextNode = node.nextNode;
1359 node.nextNode.prevNode = node.prevNode;
1360 node.prevNode = null;
1361 node.nextNode = null;
1362 this.length = this.length - 1;
1363 };
1364 /**
1365 * @return true if list is empty
1366 */
1367
1368
1369 CacheList.prototype.isEmpty = function () {
1370 return this.length === 0;
1371 };
1372 /**
1373 * refresh node so it is rotated to the head
1374 *
1375 * @param key - key of the node
1376 */
1377
1378
1379 CacheList.prototype.refresh = function (key) {
1380 var node = this.hashtable[key];
1381 this.removeNode(node);
1382 this.insertNodeToHead(node);
1383 };
1384 /**
1385 * insert new node to the head and add it in the hashtable
1386 *
1387 * @param key - the key of the node
1388 */
1389
1390
1391 CacheList.prototype.insertItem = function (key) {
1392 var node = new DoubleLinkedNode(key);
1393 this.hashtable[key] = node;
1394 this.insertNodeToHead(node);
1395 };
1396 /**
1397 * @return the LAST Recently Visited key
1398 */
1399
1400
1401 CacheList.prototype.getLastItem = function () {
1402 return this.tail.prevNode.key;
1403 };
1404 /**
1405 * remove the cache key from the list and hashtable
1406 * @param key - the key of the node
1407 */
1408
1409
1410 CacheList.prototype.removeItem = function (key) {
1411 var removedItem = this.hashtable[key];
1412 this.removeNode(removedItem);
1413 delete this.hashtable[key];
1414 };
1415 /**
1416 * @return length of the list
1417 */
1418
1419
1420 CacheList.prototype.getSize = function () {
1421 return this.length;
1422 };
1423 /**
1424 * @return true if the key is in the hashtable
1425 * @param key
1426 */
1427
1428
1429 CacheList.prototype.containsKey = function (key) {
1430 return key in this.hashtable;
1431 };
1432 /**
1433 * clean up the list and hashtable
1434 */
1435
1436
1437 CacheList.prototype.clearList = function () {
1438 var e_1, _a;
1439
1440 try {
1441 for (var _b = __values(Object.keys(this.hashtable)), _c = _b.next(); !_c.done; _c = _b.next()) {
1442 var key = _c.value;
1443
1444 if (this.hashtable.hasOwnProperty(key)) {
1445 delete this.hashtable[key];
1446 }
1447 }
1448 } catch (e_1_1) {
1449 e_1 = {
1450 error: e_1_1
1451 };
1452 } finally {
1453 try {
1454 if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
1455 } finally {
1456 if (e_1) throw e_1.error;
1457 }
1458 }
1459
1460 this.head.nextNode = this.tail;
1461 this.tail.prevNode = this.head;
1462 this.length = 0;
1463 };
1464 /**
1465 * @return all keys in the hashtable
1466 */
1467
1468
1469 CacheList.prototype.getKeys = function () {
1470 return Object.keys(this.hashtable);
1471 };
1472 /**
1473 * mainly for test
1474 *
1475 * @param key
1476 * @return true if key is the head node
1477 */
1478
1479
1480 CacheList.prototype.isHeadNode = function (key) {
1481 var node = this.hashtable[key];
1482 return node.prevNode === this.head;
1483 };
1484 /**
1485 * mainly for test
1486 *
1487 * @param key
1488 * @return true if key is the tail node
1489 */
1490
1491
1492 CacheList.prototype.isTailNode = function (key) {
1493 var node = this.hashtable[key];
1494 return node.nextNode === this.tail;
1495 };
1496
1497 return CacheList;
1498}();
1499
1500/* harmony default export */ __webpack_exports__["default"] = (CacheList);
1501
1502/***/ }),
1503
1504/***/ "./lib-esm/Utils/CacheUtils.js":
1505/*!*************************************!*\
1506 !*** ./lib-esm/Utils/CacheUtils.js ***!
1507 \*************************************/
1508/*! exports provided: defaultConfig, getByteLength, getCurrTime, isInteger, CacheObject */
1509/***/ (function(module, __webpack_exports__, __webpack_require__) {
1510
1511"use strict";
1512__webpack_require__.r(__webpack_exports__);
1513/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultConfig", function() { return defaultConfig; });
1514/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getByteLength", function() { return getByteLength; });
1515/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCurrTime", function() { return getCurrTime; });
1516/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInteger", function() { return isInteger; });
1517/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CacheObject", function() { return CacheObject; });
1518/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
1519/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
1520/*
1521 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1522 *
1523 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1524 * the License. A copy of the License is located at
1525 *
1526 * http://aws.amazon.com/apache2.0/
1527 *
1528 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1529 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1530 * and limitations under the License.
1531 */
1532
1533/**
1534 * Default cache config
1535 */
1536
1537var defaultConfig = {
1538 keyPrefix: 'aws-amplify-cache',
1539 capacityInBytes: 1048576,
1540 itemMaxSize: 210000,
1541 defaultTTL: 259200000,
1542 defaultPriority: 5,
1543 warningThreshold: 0.8,
1544 // the storage helper will check if localStorage exists,
1545 // if not, will use a in-memory object instead
1546 storage: new _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["StorageHelper"]().getStorage()
1547};
1548/**
1549 * return the byte size of the string
1550 * @param str
1551 */
1552
1553function getByteLength(str) {
1554 var ret = 0;
1555 ret = str.length;
1556
1557 for (var i = str.length; i >= 0; i -= 1) {
1558 var charCode = str.charCodeAt(i);
1559
1560 if (charCode > 0x7f && charCode <= 0x7ff) {
1561 ret += 1;
1562 } else if (charCode > 0x7ff && charCode <= 0xffff) {
1563 ret += 2;
1564 } // trail surrogate
1565
1566
1567 if (charCode >= 0xdc00 && charCode <= 0xdfff) {
1568 i -= 1;
1569 }
1570 }
1571
1572 return ret;
1573}
1574/**
1575 * get current time
1576 */
1577
1578function getCurrTime() {
1579 var currTime = new Date();
1580 return currTime.getTime();
1581}
1582/**
1583 * check if passed value is an integer
1584 */
1585
1586function isInteger(value) {
1587 if (Number.isInteger) {
1588 return Number.isInteger(value);
1589 }
1590
1591 return _isInteger(value);
1592}
1593
1594function _isInteger(value) {
1595 return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
1596}
1597/**
1598 * provide an object as the in-memory cache
1599 */
1600
1601
1602var store = {};
1603
1604var CacheObject = function () {
1605 function CacheObject() {}
1606
1607 CacheObject.clear = function () {
1608 store = {};
1609 };
1610
1611 CacheObject.getItem = function (key) {
1612 return store[key] || null;
1613 };
1614
1615 CacheObject.setItem = function (key, value) {
1616 store[key] = value;
1617 };
1618
1619 CacheObject.removeItem = function (key) {
1620 delete store[key];
1621 };
1622
1623 return CacheObject;
1624}();
1625
1626
1627
1628/***/ }),
1629
1630/***/ "./lib-esm/Utils/index.js":
1631/*!********************************!*\
1632 !*** ./lib-esm/Utils/index.js ***!
1633 \********************************/
1634/*! exports provided: defaultConfig, getByteLength, getCurrTime, isInteger, CacheObject, CacheList */
1635/***/ (function(module, __webpack_exports__, __webpack_require__) {
1636
1637"use strict";
1638__webpack_require__.r(__webpack_exports__);
1639/* harmony import */ var _CacheUtils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CacheUtils */ "./lib-esm/Utils/CacheUtils.js");
1640/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultConfig", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["defaultConfig"]; });
1641
1642/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getByteLength", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["getByteLength"]; });
1643
1644/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getCurrTime", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["getCurrTime"]; });
1645
1646/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isInteger", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["isInteger"]; });
1647
1648/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CacheObject", function() { return _CacheUtils__WEBPACK_IMPORTED_MODULE_0__["CacheObject"]; });
1649
1650/* harmony import */ var _CacheList__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CacheList */ "./lib-esm/Utils/CacheList.js");
1651/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CacheList", function() { return _CacheList__WEBPACK_IMPORTED_MODULE_1__["default"]; });
1652
1653/*
1654 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1655 *
1656 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1657 * the License. A copy of the License is located at
1658 *
1659 * http://aws.amazon.com/apache2.0/
1660 *
1661 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1662 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1663 * and limitations under the License.
1664 */
1665
1666
1667
1668/***/ }),
1669
1670/***/ "./lib-esm/index.js":
1671/*!**************************!*\
1672 !*** ./lib-esm/index.js ***!
1673 \**************************/
1674/*! exports provided: BrowserStorageCache, InMemoryCache, default */
1675/***/ (function(module, __webpack_exports__, __webpack_require__) {
1676
1677"use strict";
1678__webpack_require__.r(__webpack_exports__);
1679/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @aws-amplify/core */ "@aws-amplify/core");
1680/* harmony import */ var _aws_amplify_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__);
1681/* harmony import */ var _BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BrowserStorageCache */ "./lib-esm/BrowserStorageCache.js");
1682/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BrowserStorageCache", function() { return _BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__["BrowserStorageCache"]; });
1683
1684/* harmony import */ var _InMemoryCache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./InMemoryCache */ "./lib-esm/InMemoryCache.js");
1685/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InMemoryCache", function() { return _InMemoryCache__WEBPACK_IMPORTED_MODULE_2__["InMemoryCache"]; });
1686
1687/*
1688 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
1689 *
1690 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
1691 * the License. A copy of the License is located at
1692 *
1693 * http://aws.amazon.com/apache2.0/
1694 *
1695 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
1696 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
1697 * and limitations under the License.
1698 */
1699
1700
1701
1702
1703/**
1704 * @deprecated use named import
1705 */
1706
1707/* harmony default export */ __webpack_exports__["default"] = (_BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__["BrowserStorageCache"]);
1708_aws_amplify_core__WEBPACK_IMPORTED_MODULE_0__["Amplify"].register(_BrowserStorageCache__WEBPACK_IMPORTED_MODULE_1__["BrowserStorageCache"]);
1709
1710/***/ }),
1711
1712/***/ "@aws-amplify/core":
1713/*!************************************!*\
1714 !*** external "@aws-amplify/core" ***!
1715 \************************************/
1716/*! no static exports found */
1717/***/ (function(module, exports) {
1718
1719module.exports = __WEBPACK_EXTERNAL_MODULE__aws_amplify_core__;
1720
1721/***/ })
1722
1723/******/ });
1724});
1725//# sourceMappingURL=aws-amplify-cache.js.map
\No newline at end of file