bruce-models 2.0.5 → 2.0.7

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 (82) hide show
  1. package/dist/bruce-models.es5.js +3294 -356
  2. package/dist/bruce-models.es5.js.map +1 -1
  3. package/dist/bruce-models.umd.js +3293 -354
  4. package/dist/bruce-models.umd.js.map +1 -1
  5. package/dist/lib/account/account.js +9 -9
  6. package/dist/lib/account/account.js.map +1 -1
  7. package/dist/lib/ann-document/ann-document.js +4 -4
  8. package/dist/lib/ann-document/ann-document.js.map +1 -1
  9. package/dist/lib/api/abstract-api.js +25 -21
  10. package/dist/lib/api/abstract-api.js.map +1 -1
  11. package/dist/lib/api/api.js +1 -1
  12. package/dist/lib/api/api.js.map +1 -1
  13. package/dist/lib/api/bruce-api.js +2 -1
  14. package/dist/lib/api/bruce-api.js.map +1 -1
  15. package/dist/lib/api/cam-api.js +2 -1
  16. package/dist/lib/api/cam-api.js.map +1 -1
  17. package/dist/lib/api/global-api.js +2 -1
  18. package/dist/lib/api/global-api.js.map +1 -1
  19. package/dist/lib/api/idm-api.js +2 -1
  20. package/dist/lib/api/idm-api.js.map +1 -1
  21. package/dist/lib/bruce-models.js +1 -0
  22. package/dist/lib/bruce-models.js.map +1 -1
  23. package/dist/lib/client-file/client-file.js +2 -2
  24. package/dist/lib/client-file/client-file.js.map +1 -1
  25. package/dist/lib/common/cache.js +222 -130
  26. package/dist/lib/common/cache.js.map +1 -1
  27. package/dist/lib/common/lru-cache.js +26 -0
  28. package/dist/lib/common/lru-cache.js.map +1 -0
  29. package/dist/lib/custom-form/custom-form.js +6 -6
  30. package/dist/lib/custom-form/custom-form.js.map +1 -1
  31. package/dist/lib/entity/entity-attachment-type.js +2 -2
  32. package/dist/lib/entity/entity-attachment-type.js.map +1 -1
  33. package/dist/lib/entity/entity-attachment.js +3 -3
  34. package/dist/lib/entity/entity-attachment.js.map +1 -1
  35. package/dist/lib/entity/entity-comment.js +4 -4
  36. package/dist/lib/entity/entity-comment.js.map +1 -1
  37. package/dist/lib/entity/entity-coords.js +2 -2
  38. package/dist/lib/entity/entity-coords.js.map +1 -1
  39. package/dist/lib/entity/entity-link.js +4 -4
  40. package/dist/lib/entity/entity-link.js.map +1 -1
  41. package/dist/lib/entity/entity-lod-category.js +4 -4
  42. package/dist/lib/entity/entity-lod-category.js.map +1 -1
  43. package/dist/lib/entity/entity-lod.js +6 -6
  44. package/dist/lib/entity/entity-lod.js.map +1 -1
  45. package/dist/lib/entity/entity-relation-type.js +4 -4
  46. package/dist/lib/entity/entity-relation-type.js.map +1 -1
  47. package/dist/lib/entity/entity-relation.js +15 -15
  48. package/dist/lib/entity/entity-relation.js.map +1 -1
  49. package/dist/lib/entity/entity-source.js +2 -2
  50. package/dist/lib/entity/entity-source.js.map +1 -1
  51. package/dist/lib/entity/entity-tag.js +6 -6
  52. package/dist/lib/entity/entity-tag.js.map +1 -1
  53. package/dist/lib/entity/entity-type.js +6 -5
  54. package/dist/lib/entity/entity-type.js.map +1 -1
  55. package/dist/lib/entity/entity.js +5 -5
  56. package/dist/lib/entity/entity.js.map +1 -1
  57. package/dist/lib/entity/getters/entity-filter-getter.js +1 -4
  58. package/dist/lib/entity/getters/entity-filter-getter.js.map +1 -1
  59. package/dist/lib/import/imported-file.js +4 -4
  60. package/dist/lib/import/imported-file.js.map +1 -1
  61. package/dist/lib/plugin/plugin.js +4 -4
  62. package/dist/lib/plugin/plugin.js.map +1 -1
  63. package/dist/lib/program-key/program-key.js +4 -4
  64. package/dist/lib/program-key/program-key.js.map +1 -1
  65. package/dist/lib/project/project-view-bookmark.js +6 -6
  66. package/dist/lib/project/project-view-bookmark.js.map +1 -1
  67. package/dist/lib/project/project-view.js +4 -4
  68. package/dist/lib/project/project-view.js.map +1 -1
  69. package/dist/lib/style/style.js +46 -42
  70. package/dist/lib/style/style.js.map +1 -1
  71. package/dist/lib/tileset/tileset.js +12 -12
  72. package/dist/lib/tileset/tileset.js.map +1 -1
  73. package/dist/lib/user/session.js +2 -2
  74. package/dist/lib/user/session.js.map +1 -1
  75. package/dist/lib/user/user.js +20 -20
  76. package/dist/lib/user/user.js.map +1 -1
  77. package/dist/types/api/abstract-api.d.ts +3 -2
  78. package/dist/types/api/api.d.ts +1 -1
  79. package/dist/types/bruce-models.d.ts +1 -0
  80. package/dist/types/common/cache.d.ts +9 -15
  81. package/dist/types/common/lru-cache.d.ts +7 -0
  82. package/package.json +2 -1
@@ -64,7 +64,7 @@ var Api;
64
64
  ECacheKey["ImportedFile"] = "importedfile";
65
65
  ECacheKey["Plugin"] = "plugin";
66
66
  })(ECacheKey = Api.ECacheKey || (Api.ECacheKey = {}));
67
- Api.DEFAULT_CACHE_DURATION = 60 * 5; // 5 minutes.
67
+ Api.DEFAULT_CACHE_DURATION = 60; // 1 minute.
68
68
  Api.TEMPLATE_ACCOUNT_ID = "template";
69
69
  Api.ACCESS_TOKEN_HEADER = "X-Access-Token";
70
70
  /**
@@ -138,7 +138,7 @@ var AnnDocument;
138
138
  throw ("Doc ID is required.");
139
139
  }
140
140
  const key = GetCacheKey(docId);
141
- const cacheData = api.GetCacheItem(key, reqParams);
141
+ const cacheData = yield api.GetCacheItem(key, reqParams);
142
142
  if (cacheData) {
143
143
  return cacheData;
144
144
  }
@@ -153,7 +153,7 @@ var AnnDocument;
153
153
  rej(e);
154
154
  }
155
155
  }));
156
- api.SetCacheItem({
156
+ yield api.SetCacheItem({
157
157
  key,
158
158
  value: prom,
159
159
  req: reqParams
@@ -168,7 +168,7 @@ var AnnDocument;
168
168
  if (!type) {
169
169
  type = "";
170
170
  }
171
- const cacheData = api.GetCacheItem(GetListCacheKey(type), reqParams);
171
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(type), reqParams);
172
172
  if (cacheData) {
173
173
  return cacheData;
174
174
  }
@@ -184,7 +184,7 @@ var AnnDocument;
184
184
  rej(e);
185
185
  }
186
186
  }));
187
- api.SetCacheItem({
187
+ yield api.SetCacheItem({
188
188
  key: GetListCacheKey(type),
189
189
  value: req,
190
190
  req: reqParams
@@ -223,7 +223,7 @@ var CustomForm;
223
223
  if (!id) {
224
224
  throw ("Id is required.");
225
225
  }
226
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
226
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
227
227
  if (cacheData) {
228
228
  return cacheData;
229
229
  }
@@ -238,7 +238,7 @@ var CustomForm;
238
238
  rej(err);
239
239
  }
240
240
  }));
241
- api.SetCacheItem({
241
+ yield api.SetCacheItem({
242
242
  key: GetCacheKey(id),
243
243
  value: prom,
244
244
  req: reqParams
@@ -254,7 +254,7 @@ var CustomForm;
254
254
  throw ("Id is required.");
255
255
  }
256
256
  yield api.DELETE(`customForm/${id}`, Api.PrepReqParams(reqParams));
257
- api.Cache.RemoveByStartsWith(Api.ECacheKey.CustomForm);
257
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.CustomForm);
258
258
  });
259
259
  }
260
260
  CustomForm.Delete = Delete;
@@ -262,7 +262,7 @@ var CustomForm;
262
262
  return __awaiter(this, void 0, void 0, function* () {
263
263
  const { api, entityTypeId: typeId, req: reqParams } = params;
264
264
  const url = typeId ? `entityType/${typeId}/customForms` : "customForms";
265
- const cacheData = api.GetCacheItem(GetListCacheKey(typeId), reqParams);
265
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(typeId), reqParams);
266
266
  if (cacheData) {
267
267
  return cacheData;
268
268
  }
@@ -272,7 +272,7 @@ var CustomForm;
272
272
  forms: data.Items
273
273
  };
274
274
  });
275
- api.SetCacheItem({
275
+ yield api.SetCacheItem({
276
276
  key: GetListCacheKey(typeId),
277
277
  value: prom,
278
278
  req: reqParams
@@ -288,7 +288,7 @@ var CustomForm;
288
288
  data.ID = 0;
289
289
  }
290
290
  const res = yield api.POST(`customForm/${data.ID}`, data, Api.PrepReqParams(reqParams));
291
- api.Cache.RemoveByStartsWith(Api.ECacheKey.CustomForm);
291
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.CustomForm);
292
292
  return {
293
293
  form: res
294
294
  };
@@ -321,43 +321,3021 @@ var CustomFormContent;
321
321
  })(EFlowDirection = CustomFormContent.EFlowDirection || (CustomFormContent.EFlowDirection = {}));
322
322
  })(CustomFormContent || (CustomFormContent = {}));
323
323
 
324
- class CacheItem {
324
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
325
+
326
+ function commonjsRequire () {
327
+ throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
328
+ }
329
+
330
+ function createCommonjsModule(fn, module) {
331
+ return module = { exports: {} }, fn(module, module.exports), module.exports;
332
+ }
333
+
334
+ var localforage = createCommonjsModule(function (module, exports) {
335
+ /*!
336
+ localForage -- Offline Storage, Improved
337
+ Version 1.10.0
338
+ https://localforage.github.io/localForage
339
+ (c) 2013-2017 Mozilla, Apache License 2.0
340
+ */
341
+ (function(f){{module.exports=f();}})(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
342
+ (function (global){
343
+ var Mutation = global.MutationObserver || global.WebKitMutationObserver;
344
+
345
+ var scheduleDrain;
346
+
347
+ {
348
+ if (Mutation) {
349
+ var called = 0;
350
+ var observer = new Mutation(nextTick);
351
+ var element = global.document.createTextNode('');
352
+ observer.observe(element, {
353
+ characterData: true
354
+ });
355
+ scheduleDrain = function () {
356
+ element.data = (called = ++called % 2);
357
+ };
358
+ } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
359
+ var channel = new global.MessageChannel();
360
+ channel.port1.onmessage = nextTick;
361
+ scheduleDrain = function () {
362
+ channel.port2.postMessage(0);
363
+ };
364
+ } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
365
+ scheduleDrain = function () {
366
+
367
+ // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
368
+ // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
369
+ var scriptEl = global.document.createElement('script');
370
+ scriptEl.onreadystatechange = function () {
371
+ nextTick();
372
+
373
+ scriptEl.onreadystatechange = null;
374
+ scriptEl.parentNode.removeChild(scriptEl);
375
+ scriptEl = null;
376
+ };
377
+ global.document.documentElement.appendChild(scriptEl);
378
+ };
379
+ } else {
380
+ scheduleDrain = function () {
381
+ setTimeout(nextTick, 0);
382
+ };
383
+ }
384
+ }
385
+
386
+ var draining;
387
+ var queue = [];
388
+ //named nextTick for less confusing stack traces
389
+ function nextTick() {
390
+ draining = true;
391
+ var i, oldQueue;
392
+ var len = queue.length;
393
+ while (len) {
394
+ oldQueue = queue;
395
+ queue = [];
396
+ i = -1;
397
+ while (++i < len) {
398
+ oldQueue[i]();
399
+ }
400
+ len = queue.length;
401
+ }
402
+ draining = false;
403
+ }
404
+
405
+ module.exports = immediate;
406
+ function immediate(task) {
407
+ if (queue.push(task) === 1 && !draining) {
408
+ scheduleDrain();
409
+ }
410
+ }
411
+
412
+ }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
413
+ },{}],2:[function(_dereq_,module,exports){
414
+ var immediate = _dereq_(1);
415
+
416
+ /* istanbul ignore next */
417
+ function INTERNAL() {}
418
+
419
+ var handlers = {};
420
+
421
+ var REJECTED = ['REJECTED'];
422
+ var FULFILLED = ['FULFILLED'];
423
+ var PENDING = ['PENDING'];
424
+
425
+ module.exports = Promise;
426
+
427
+ function Promise(resolver) {
428
+ if (typeof resolver !== 'function') {
429
+ throw new TypeError('resolver must be a function');
430
+ }
431
+ this.state = PENDING;
432
+ this.queue = [];
433
+ this.outcome = void 0;
434
+ if (resolver !== INTERNAL) {
435
+ safelyResolveThenable(this, resolver);
436
+ }
437
+ }
438
+
439
+ Promise.prototype["catch"] = function (onRejected) {
440
+ return this.then(null, onRejected);
441
+ };
442
+ Promise.prototype.then = function (onFulfilled, onRejected) {
443
+ if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
444
+ typeof onRejected !== 'function' && this.state === REJECTED) {
445
+ return this;
446
+ }
447
+ var promise = new this.constructor(INTERNAL);
448
+ if (this.state !== PENDING) {
449
+ var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
450
+ unwrap(promise, resolver, this.outcome);
451
+ } else {
452
+ this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
453
+ }
454
+
455
+ return promise;
456
+ };
457
+ function QueueItem(promise, onFulfilled, onRejected) {
458
+ this.promise = promise;
459
+ if (typeof onFulfilled === 'function') {
460
+ this.onFulfilled = onFulfilled;
461
+ this.callFulfilled = this.otherCallFulfilled;
462
+ }
463
+ if (typeof onRejected === 'function') {
464
+ this.onRejected = onRejected;
465
+ this.callRejected = this.otherCallRejected;
466
+ }
467
+ }
468
+ QueueItem.prototype.callFulfilled = function (value) {
469
+ handlers.resolve(this.promise, value);
470
+ };
471
+ QueueItem.prototype.otherCallFulfilled = function (value) {
472
+ unwrap(this.promise, this.onFulfilled, value);
473
+ };
474
+ QueueItem.prototype.callRejected = function (value) {
475
+ handlers.reject(this.promise, value);
476
+ };
477
+ QueueItem.prototype.otherCallRejected = function (value) {
478
+ unwrap(this.promise, this.onRejected, value);
479
+ };
480
+
481
+ function unwrap(promise, func, value) {
482
+ immediate(function () {
483
+ var returnValue;
484
+ try {
485
+ returnValue = func(value);
486
+ } catch (e) {
487
+ return handlers.reject(promise, e);
488
+ }
489
+ if (returnValue === promise) {
490
+ handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
491
+ } else {
492
+ handlers.resolve(promise, returnValue);
493
+ }
494
+ });
495
+ }
496
+
497
+ handlers.resolve = function (self, value) {
498
+ var result = tryCatch(getThen, value);
499
+ if (result.status === 'error') {
500
+ return handlers.reject(self, result.value);
501
+ }
502
+ var thenable = result.value;
503
+
504
+ if (thenable) {
505
+ safelyResolveThenable(self, thenable);
506
+ } else {
507
+ self.state = FULFILLED;
508
+ self.outcome = value;
509
+ var i = -1;
510
+ var len = self.queue.length;
511
+ while (++i < len) {
512
+ self.queue[i].callFulfilled(value);
513
+ }
514
+ }
515
+ return self;
516
+ };
517
+ handlers.reject = function (self, error) {
518
+ self.state = REJECTED;
519
+ self.outcome = error;
520
+ var i = -1;
521
+ var len = self.queue.length;
522
+ while (++i < len) {
523
+ self.queue[i].callRejected(error);
524
+ }
525
+ return self;
526
+ };
527
+
528
+ function getThen(obj) {
529
+ // Make sure we only access the accessor once as required by the spec
530
+ var then = obj && obj.then;
531
+ if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
532
+ return function appyThen() {
533
+ then.apply(obj, arguments);
534
+ };
535
+ }
536
+ }
537
+
538
+ function safelyResolveThenable(self, thenable) {
539
+ // Either fulfill, reject or reject with error
540
+ var called = false;
541
+ function onError(value) {
542
+ if (called) {
543
+ return;
544
+ }
545
+ called = true;
546
+ handlers.reject(self, value);
547
+ }
548
+
549
+ function onSuccess(value) {
550
+ if (called) {
551
+ return;
552
+ }
553
+ called = true;
554
+ handlers.resolve(self, value);
555
+ }
556
+
557
+ function tryToUnwrap() {
558
+ thenable(onSuccess, onError);
559
+ }
560
+
561
+ var result = tryCatch(tryToUnwrap);
562
+ if (result.status === 'error') {
563
+ onError(result.value);
564
+ }
565
+ }
566
+
567
+ function tryCatch(func, value) {
568
+ var out = {};
569
+ try {
570
+ out.value = func(value);
571
+ out.status = 'success';
572
+ } catch (e) {
573
+ out.status = 'error';
574
+ out.value = e;
575
+ }
576
+ return out;
577
+ }
578
+
579
+ Promise.resolve = resolve;
580
+ function resolve(value) {
581
+ if (value instanceof this) {
582
+ return value;
583
+ }
584
+ return handlers.resolve(new this(INTERNAL), value);
585
+ }
586
+
587
+ Promise.reject = reject;
588
+ function reject(reason) {
589
+ var promise = new this(INTERNAL);
590
+ return handlers.reject(promise, reason);
591
+ }
592
+
593
+ Promise.all = all;
594
+ function all(iterable) {
595
+ var self = this;
596
+ if (Object.prototype.toString.call(iterable) !== '[object Array]') {
597
+ return this.reject(new TypeError('must be an array'));
598
+ }
599
+
600
+ var len = iterable.length;
601
+ var called = false;
602
+ if (!len) {
603
+ return this.resolve([]);
604
+ }
605
+
606
+ var values = new Array(len);
607
+ var resolved = 0;
608
+ var i = -1;
609
+ var promise = new this(INTERNAL);
610
+
611
+ while (++i < len) {
612
+ allResolver(iterable[i], i);
613
+ }
614
+ return promise;
615
+ function allResolver(value, i) {
616
+ self.resolve(value).then(resolveFromAll, function (error) {
617
+ if (!called) {
618
+ called = true;
619
+ handlers.reject(promise, error);
620
+ }
621
+ });
622
+ function resolveFromAll(outValue) {
623
+ values[i] = outValue;
624
+ if (++resolved === len && !called) {
625
+ called = true;
626
+ handlers.resolve(promise, values);
627
+ }
628
+ }
629
+ }
630
+ }
631
+
632
+ Promise.race = race;
633
+ function race(iterable) {
634
+ var self = this;
635
+ if (Object.prototype.toString.call(iterable) !== '[object Array]') {
636
+ return this.reject(new TypeError('must be an array'));
637
+ }
638
+
639
+ var len = iterable.length;
640
+ var called = false;
641
+ if (!len) {
642
+ return this.resolve([]);
643
+ }
644
+
645
+ var i = -1;
646
+ var promise = new this(INTERNAL);
647
+
648
+ while (++i < len) {
649
+ resolver(iterable[i]);
650
+ }
651
+ return promise;
652
+ function resolver(value) {
653
+ self.resolve(value).then(function (response) {
654
+ if (!called) {
655
+ called = true;
656
+ handlers.resolve(promise, response);
657
+ }
658
+ }, function (error) {
659
+ if (!called) {
660
+ called = true;
661
+ handlers.reject(promise, error);
662
+ }
663
+ });
664
+ }
665
+ }
666
+
667
+ },{"1":1}],3:[function(_dereq_,module,exports){
668
+ (function (global){
669
+ if (typeof global.Promise !== 'function') {
670
+ global.Promise = _dereq_(2);
671
+ }
672
+
673
+ }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
674
+ },{"2":2}],4:[function(_dereq_,module,exports){
675
+
676
+ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
677
+
678
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
679
+
680
+ function getIDB() {
681
+ /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
682
+ try {
683
+ if (typeof indexedDB !== 'undefined') {
684
+ return indexedDB;
685
+ }
686
+ if (typeof webkitIndexedDB !== 'undefined') {
687
+ return webkitIndexedDB;
688
+ }
689
+ if (typeof mozIndexedDB !== 'undefined') {
690
+ return mozIndexedDB;
691
+ }
692
+ if (typeof OIndexedDB !== 'undefined') {
693
+ return OIndexedDB;
694
+ }
695
+ if (typeof msIndexedDB !== 'undefined') {
696
+ return msIndexedDB;
697
+ }
698
+ } catch (e) {
699
+ return;
700
+ }
701
+ }
702
+
703
+ var idb = getIDB();
704
+
705
+ function isIndexedDBValid() {
706
+ try {
707
+ // Initialize IndexedDB; fall back to vendor-prefixed versions
708
+ // if needed.
709
+ if (!idb || !idb.open) {
710
+ return false;
711
+ }
712
+ // We mimic PouchDB here;
713
+ //
714
+ // We test for openDatabase because IE Mobile identifies itself
715
+ // as Safari. Oh the lulz...
716
+ var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
717
+
718
+ var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
719
+
720
+ // Safari <10.1 does not meet our requirements for IDB support
721
+ // (see: https://github.com/pouchdb/pouchdb/issues/5572).
722
+ // Safari 10.1 shipped with fetch, we can use that to detect it.
723
+ // Note: this creates issues with `window.fetch` polyfills and
724
+ // overrides; see:
725
+ // https://github.com/localForage/localForage/issues/856
726
+ return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
727
+ // some outdated implementations of IDB that appear on Samsung
728
+ // and HTC Android devices <4.4 are missing IDBKeyRange
729
+ // See: https://github.com/mozilla/localForage/issues/128
730
+ // See: https://github.com/mozilla/localForage/issues/272
731
+ typeof IDBKeyRange !== 'undefined';
732
+ } catch (e) {
733
+ return false;
734
+ }
735
+ }
736
+
737
+ // Abstracts constructing a Blob object, so it also works in older
738
+ // browsers that don't support the native Blob constructor. (i.e.
739
+ // old QtWebKit versions, at least).
740
+ // Abstracts constructing a Blob object, so it also works in older
741
+ // browsers that don't support the native Blob constructor. (i.e.
742
+ // old QtWebKit versions, at least).
743
+ function createBlob(parts, properties) {
744
+ /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
745
+ parts = parts || [];
746
+ properties = properties || {};
747
+ try {
748
+ return new Blob(parts, properties);
749
+ } catch (e) {
750
+ if (e.name !== 'TypeError') {
751
+ throw e;
752
+ }
753
+ var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
754
+ var builder = new Builder();
755
+ for (var i = 0; i < parts.length; i += 1) {
756
+ builder.append(parts[i]);
757
+ }
758
+ return builder.getBlob(properties.type);
759
+ }
760
+ }
761
+
762
+ // This is CommonJS because lie is an external dependency, so Rollup
763
+ // can just ignore it.
764
+ if (typeof Promise === 'undefined') {
765
+ // In the "nopromises" build this will just throw if you don't have
766
+ // a global promise object, but it would throw anyway later.
767
+ _dereq_(3);
768
+ }
769
+ var Promise$1 = Promise;
770
+
771
+ function executeCallback(promise, callback) {
772
+ if (callback) {
773
+ promise.then(function (result) {
774
+ callback(null, result);
775
+ }, function (error) {
776
+ callback(error);
777
+ });
778
+ }
779
+ }
780
+
781
+ function executeTwoCallbacks(promise, callback, errorCallback) {
782
+ if (typeof callback === 'function') {
783
+ promise.then(callback);
784
+ }
785
+
786
+ if (typeof errorCallback === 'function') {
787
+ promise["catch"](errorCallback);
788
+ }
789
+ }
790
+
791
+ function normalizeKey(key) {
792
+ // Cast the key to a string, as that's all we can set as a key.
793
+ if (typeof key !== 'string') {
794
+ console.warn(key + ' used as a key, but it is not a string.');
795
+ key = String(key);
796
+ }
797
+
798
+ return key;
799
+ }
800
+
801
+ function getCallback() {
802
+ if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
803
+ return arguments[arguments.length - 1];
804
+ }
805
+ }
806
+
807
+ // Some code originally from async_storage.js in
808
+ // [Gaia](https://github.com/mozilla-b2g/gaia).
809
+
810
+ var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
811
+ var supportsBlobs = void 0;
812
+ var dbContexts = {};
813
+ var toString = Object.prototype.toString;
814
+
815
+ // Transaction Modes
816
+ var READ_ONLY = 'readonly';
817
+ var READ_WRITE = 'readwrite';
818
+
819
+ // Transform a binary string to an array buffer, because otherwise
820
+ // weird stuff happens when you try to work with the binary string directly.
821
+ // It is known.
822
+ // From http://stackoverflow.com/questions/14967647/ (continues on next line)
823
+ // encode-decode-image-with-base64-breaks-image (2013-04-21)
824
+ function _binStringToArrayBuffer(bin) {
825
+ var length = bin.length;
826
+ var buf = new ArrayBuffer(length);
827
+ var arr = new Uint8Array(buf);
828
+ for (var i = 0; i < length; i++) {
829
+ arr[i] = bin.charCodeAt(i);
830
+ }
831
+ return buf;
832
+ }
833
+
834
+ //
835
+ // Blobs are not supported in all versions of IndexedDB, notably
836
+ // Chrome <37 and Android <5. In those versions, storing a blob will throw.
837
+ //
838
+ // Various other blob bugs exist in Chrome v37-42 (inclusive).
839
+ // Detecting them is expensive and confusing to users, and Chrome 37-42
840
+ // is at very low usage worldwide, so we do a hacky userAgent check instead.
841
+ //
842
+ // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
843
+ // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
844
+ // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
845
+ //
846
+ // Code borrowed from PouchDB. See:
847
+ // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
848
+ //
849
+ function _checkBlobSupportWithoutCaching(idb) {
850
+ return new Promise$1(function (resolve) {
851
+ var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
852
+ var blob = createBlob(['']);
853
+ txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
854
+
855
+ txn.onabort = function (e) {
856
+ // If the transaction aborts now its due to not being able to
857
+ // write to the database, likely due to the disk being full
858
+ e.preventDefault();
859
+ e.stopPropagation();
860
+ resolve(false);
861
+ };
862
+
863
+ txn.oncomplete = function () {
864
+ var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
865
+ var matchedEdge = navigator.userAgent.match(/Edge\//);
866
+ // MS Edge pretends to be Chrome 42:
867
+ // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
868
+ resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
869
+ };
870
+ })["catch"](function () {
871
+ return false; // error, so assume unsupported
872
+ });
873
+ }
874
+
875
+ function _checkBlobSupport(idb) {
876
+ if (typeof supportsBlobs === 'boolean') {
877
+ return Promise$1.resolve(supportsBlobs);
878
+ }
879
+ return _checkBlobSupportWithoutCaching(idb).then(function (value) {
880
+ supportsBlobs = value;
881
+ return supportsBlobs;
882
+ });
883
+ }
884
+
885
+ function _deferReadiness(dbInfo) {
886
+ var dbContext = dbContexts[dbInfo.name];
887
+
888
+ // Create a deferred object representing the current database operation.
889
+ var deferredOperation = {};
890
+
891
+ deferredOperation.promise = new Promise$1(function (resolve, reject) {
892
+ deferredOperation.resolve = resolve;
893
+ deferredOperation.reject = reject;
894
+ });
895
+
896
+ // Enqueue the deferred operation.
897
+ dbContext.deferredOperations.push(deferredOperation);
898
+
899
+ // Chain its promise to the database readiness.
900
+ if (!dbContext.dbReady) {
901
+ dbContext.dbReady = deferredOperation.promise;
902
+ } else {
903
+ dbContext.dbReady = dbContext.dbReady.then(function () {
904
+ return deferredOperation.promise;
905
+ });
906
+ }
907
+ }
908
+
909
+ function _advanceReadiness(dbInfo) {
910
+ var dbContext = dbContexts[dbInfo.name];
911
+
912
+ // Dequeue a deferred operation.
913
+ var deferredOperation = dbContext.deferredOperations.pop();
914
+
915
+ // Resolve its promise (which is part of the database readiness
916
+ // chain of promises).
917
+ if (deferredOperation) {
918
+ deferredOperation.resolve();
919
+ return deferredOperation.promise;
920
+ }
921
+ }
922
+
923
+ function _rejectReadiness(dbInfo, err) {
924
+ var dbContext = dbContexts[dbInfo.name];
925
+
926
+ // Dequeue a deferred operation.
927
+ var deferredOperation = dbContext.deferredOperations.pop();
928
+
929
+ // Reject its promise (which is part of the database readiness
930
+ // chain of promises).
931
+ if (deferredOperation) {
932
+ deferredOperation.reject(err);
933
+ return deferredOperation.promise;
934
+ }
935
+ }
936
+
937
+ function _getConnection(dbInfo, upgradeNeeded) {
938
+ return new Promise$1(function (resolve, reject) {
939
+ dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
940
+
941
+ if (dbInfo.db) {
942
+ if (upgradeNeeded) {
943
+ _deferReadiness(dbInfo);
944
+ dbInfo.db.close();
945
+ } else {
946
+ return resolve(dbInfo.db);
947
+ }
948
+ }
949
+
950
+ var dbArgs = [dbInfo.name];
951
+
952
+ if (upgradeNeeded) {
953
+ dbArgs.push(dbInfo.version);
954
+ }
955
+
956
+ var openreq = idb.open.apply(idb, dbArgs);
957
+
958
+ if (upgradeNeeded) {
959
+ openreq.onupgradeneeded = function (e) {
960
+ var db = openreq.result;
961
+ try {
962
+ db.createObjectStore(dbInfo.storeName);
963
+ if (e.oldVersion <= 1) {
964
+ // Added when support for blob shims was added
965
+ db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
966
+ }
967
+ } catch (ex) {
968
+ if (ex.name === 'ConstraintError') {
969
+ console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
970
+ } else {
971
+ throw ex;
972
+ }
973
+ }
974
+ };
975
+ }
976
+
977
+ openreq.onerror = function (e) {
978
+ e.preventDefault();
979
+ reject(openreq.error);
980
+ };
981
+
982
+ openreq.onsuccess = function () {
983
+ var db = openreq.result;
984
+ db.onversionchange = function (e) {
985
+ // Triggered when the database is modified (e.g. adding an objectStore) or
986
+ // deleted (even when initiated by other sessions in different tabs).
987
+ // Closing the connection here prevents those operations from being blocked.
988
+ // If the database is accessed again later by this instance, the connection
989
+ // will be reopened or the database recreated as needed.
990
+ e.target.close();
991
+ };
992
+ resolve(db);
993
+ _advanceReadiness(dbInfo);
994
+ };
995
+ });
996
+ }
997
+
998
+ function _getOriginalConnection(dbInfo) {
999
+ return _getConnection(dbInfo, false);
1000
+ }
1001
+
1002
+ function _getUpgradedConnection(dbInfo) {
1003
+ return _getConnection(dbInfo, true);
1004
+ }
1005
+
1006
+ function _isUpgradeNeeded(dbInfo, defaultVersion) {
1007
+ if (!dbInfo.db) {
1008
+ return true;
1009
+ }
1010
+
1011
+ var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
1012
+ var isDowngrade = dbInfo.version < dbInfo.db.version;
1013
+ var isUpgrade = dbInfo.version > dbInfo.db.version;
1014
+
1015
+ if (isDowngrade) {
1016
+ // If the version is not the default one
1017
+ // then warn for impossible downgrade.
1018
+ if (dbInfo.version !== defaultVersion) {
1019
+ console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
1020
+ }
1021
+ // Align the versions to prevent errors.
1022
+ dbInfo.version = dbInfo.db.version;
1023
+ }
1024
+
1025
+ if (isUpgrade || isNewStore) {
1026
+ // If the store is new then increment the version (if needed).
1027
+ // This will trigger an "upgradeneeded" event which is required
1028
+ // for creating a store.
1029
+ if (isNewStore) {
1030
+ var incVersion = dbInfo.db.version + 1;
1031
+ if (incVersion > dbInfo.version) {
1032
+ dbInfo.version = incVersion;
1033
+ }
1034
+ }
1035
+
1036
+ return true;
1037
+ }
1038
+
1039
+ return false;
1040
+ }
1041
+
1042
+ // encode a blob for indexeddb engines that don't support blobs
1043
+ function _encodeBlob(blob) {
1044
+ return new Promise$1(function (resolve, reject) {
1045
+ var reader = new FileReader();
1046
+ reader.onerror = reject;
1047
+ reader.onloadend = function (e) {
1048
+ var base64 = btoa(e.target.result || '');
1049
+ resolve({
1050
+ __local_forage_encoded_blob: true,
1051
+ data: base64,
1052
+ type: blob.type
1053
+ });
1054
+ };
1055
+ reader.readAsBinaryString(blob);
1056
+ });
1057
+ }
1058
+
1059
+ // decode an encoded blob
1060
+ function _decodeBlob(encodedBlob) {
1061
+ var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
1062
+ return createBlob([arrayBuff], { type: encodedBlob.type });
1063
+ }
1064
+
1065
+ // is this one of our fancy encoded blobs?
1066
+ function _isEncodedBlob(value) {
1067
+ return value && value.__local_forage_encoded_blob;
1068
+ }
1069
+
1070
+ // Specialize the default `ready()` function by making it dependent
1071
+ // on the current database operations. Thus, the driver will be actually
1072
+ // ready when it's been initialized (default) *and* there are no pending
1073
+ // operations on the database (initiated by some other instances).
1074
+ function _fullyReady(callback) {
1075
+ var self = this;
1076
+
1077
+ var promise = self._initReady().then(function () {
1078
+ var dbContext = dbContexts[self._dbInfo.name];
1079
+
1080
+ if (dbContext && dbContext.dbReady) {
1081
+ return dbContext.dbReady;
1082
+ }
1083
+ });
1084
+
1085
+ executeTwoCallbacks(promise, callback, callback);
1086
+ return promise;
1087
+ }
1088
+
1089
+ // Try to establish a new db connection to replace the
1090
+ // current one which is broken (i.e. experiencing
1091
+ // InvalidStateError while creating a transaction).
1092
+ function _tryReconnect(dbInfo) {
1093
+ _deferReadiness(dbInfo);
1094
+
1095
+ var dbContext = dbContexts[dbInfo.name];
1096
+ var forages = dbContext.forages;
1097
+
1098
+ for (var i = 0; i < forages.length; i++) {
1099
+ var forage = forages[i];
1100
+ if (forage._dbInfo.db) {
1101
+ forage._dbInfo.db.close();
1102
+ forage._dbInfo.db = null;
1103
+ }
1104
+ }
1105
+ dbInfo.db = null;
1106
+
1107
+ return _getOriginalConnection(dbInfo).then(function (db) {
1108
+ dbInfo.db = db;
1109
+ if (_isUpgradeNeeded(dbInfo)) {
1110
+ // Reopen the database for upgrading.
1111
+ return _getUpgradedConnection(dbInfo);
1112
+ }
1113
+ return db;
1114
+ }).then(function (db) {
1115
+ // store the latest db reference
1116
+ // in case the db was upgraded
1117
+ dbInfo.db = dbContext.db = db;
1118
+ for (var i = 0; i < forages.length; i++) {
1119
+ forages[i]._dbInfo.db = db;
1120
+ }
1121
+ })["catch"](function (err) {
1122
+ _rejectReadiness(dbInfo, err);
1123
+ throw err;
1124
+ });
1125
+ }
1126
+
1127
+ // FF doesn't like Promises (micro-tasks) and IDDB store operations,
1128
+ // so we have to do it with callbacks
1129
+ function createTransaction(dbInfo, mode, callback, retries) {
1130
+ if (retries === undefined) {
1131
+ retries = 1;
1132
+ }
1133
+
1134
+ try {
1135
+ var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
1136
+ callback(null, tx);
1137
+ } catch (err) {
1138
+ if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
1139
+ return Promise$1.resolve().then(function () {
1140
+ if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
1141
+ // increase the db version, to create the new ObjectStore
1142
+ if (dbInfo.db) {
1143
+ dbInfo.version = dbInfo.db.version + 1;
1144
+ }
1145
+ // Reopen the database for upgrading.
1146
+ return _getUpgradedConnection(dbInfo);
1147
+ }
1148
+ }).then(function () {
1149
+ return _tryReconnect(dbInfo).then(function () {
1150
+ createTransaction(dbInfo, mode, callback, retries - 1);
1151
+ });
1152
+ })["catch"](callback);
1153
+ }
1154
+
1155
+ callback(err);
1156
+ }
1157
+ }
1158
+
1159
+ function createDbContext() {
1160
+ return {
1161
+ // Running localForages sharing a database.
1162
+ forages: [],
1163
+ // Shared database.
1164
+ db: null,
1165
+ // Database readiness (promise).
1166
+ dbReady: null,
1167
+ // Deferred operations on the database.
1168
+ deferredOperations: []
1169
+ };
1170
+ }
1171
+
1172
+ // Open the IndexedDB database (automatically creates one if one didn't
1173
+ // previously exist), using any options set in the config.
1174
+ function _initStorage(options) {
1175
+ var self = this;
1176
+ var dbInfo = {
1177
+ db: null
1178
+ };
1179
+
1180
+ if (options) {
1181
+ for (var i in options) {
1182
+ dbInfo[i] = options[i];
1183
+ }
1184
+ }
1185
+
1186
+ // Get the current context of the database;
1187
+ var dbContext = dbContexts[dbInfo.name];
1188
+
1189
+ // ...or create a new context.
1190
+ if (!dbContext) {
1191
+ dbContext = createDbContext();
1192
+ // Register the new context in the global container.
1193
+ dbContexts[dbInfo.name] = dbContext;
1194
+ }
1195
+
1196
+ // Register itself as a running localForage in the current context.
1197
+ dbContext.forages.push(self);
1198
+
1199
+ // Replace the default `ready()` function with the specialized one.
1200
+ if (!self._initReady) {
1201
+ self._initReady = self.ready;
1202
+ self.ready = _fullyReady;
1203
+ }
1204
+
1205
+ // Create an array of initialization states of the related localForages.
1206
+ var initPromises = [];
1207
+
1208
+ function ignoreErrors() {
1209
+ // Don't handle errors here,
1210
+ // just makes sure related localForages aren't pending.
1211
+ return Promise$1.resolve();
1212
+ }
1213
+
1214
+ for (var j = 0; j < dbContext.forages.length; j++) {
1215
+ var forage = dbContext.forages[j];
1216
+ if (forage !== self) {
1217
+ // Don't wait for itself...
1218
+ initPromises.push(forage._initReady()["catch"](ignoreErrors));
1219
+ }
1220
+ }
1221
+
1222
+ // Take a snapshot of the related localForages.
1223
+ var forages = dbContext.forages.slice(0);
1224
+
1225
+ // Initialize the connection process only when
1226
+ // all the related localForages aren't pending.
1227
+ return Promise$1.all(initPromises).then(function () {
1228
+ dbInfo.db = dbContext.db;
1229
+ // Get the connection or open a new one without upgrade.
1230
+ return _getOriginalConnection(dbInfo);
1231
+ }).then(function (db) {
1232
+ dbInfo.db = db;
1233
+ if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
1234
+ // Reopen the database for upgrading.
1235
+ return _getUpgradedConnection(dbInfo);
1236
+ }
1237
+ return db;
1238
+ }).then(function (db) {
1239
+ dbInfo.db = dbContext.db = db;
1240
+ self._dbInfo = dbInfo;
1241
+ // Share the final connection amongst related localForages.
1242
+ for (var k = 0; k < forages.length; k++) {
1243
+ var forage = forages[k];
1244
+ if (forage !== self) {
1245
+ // Self is already up-to-date.
1246
+ forage._dbInfo.db = dbInfo.db;
1247
+ forage._dbInfo.version = dbInfo.version;
1248
+ }
1249
+ }
1250
+ });
1251
+ }
1252
+
1253
+ function getItem(key, callback) {
1254
+ var self = this;
1255
+
1256
+ key = normalizeKey(key);
1257
+
1258
+ var promise = new Promise$1(function (resolve, reject) {
1259
+ self.ready().then(function () {
1260
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1261
+ if (err) {
1262
+ return reject(err);
1263
+ }
1264
+
1265
+ try {
1266
+ var store = transaction.objectStore(self._dbInfo.storeName);
1267
+ var req = store.get(key);
1268
+
1269
+ req.onsuccess = function () {
1270
+ var value = req.result;
1271
+ if (value === undefined) {
1272
+ value = null;
1273
+ }
1274
+ if (_isEncodedBlob(value)) {
1275
+ value = _decodeBlob(value);
1276
+ }
1277
+ resolve(value);
1278
+ };
1279
+
1280
+ req.onerror = function () {
1281
+ reject(req.error);
1282
+ };
1283
+ } catch (e) {
1284
+ reject(e);
1285
+ }
1286
+ });
1287
+ })["catch"](reject);
1288
+ });
1289
+
1290
+ executeCallback(promise, callback);
1291
+ return promise;
1292
+ }
1293
+
1294
+ // Iterate over all items stored in database.
1295
+ function iterate(iterator, callback) {
1296
+ var self = this;
1297
+
1298
+ var promise = new Promise$1(function (resolve, reject) {
1299
+ self.ready().then(function () {
1300
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1301
+ if (err) {
1302
+ return reject(err);
1303
+ }
1304
+
1305
+ try {
1306
+ var store = transaction.objectStore(self._dbInfo.storeName);
1307
+ var req = store.openCursor();
1308
+ var iterationNumber = 1;
1309
+
1310
+ req.onsuccess = function () {
1311
+ var cursor = req.result;
1312
+
1313
+ if (cursor) {
1314
+ var value = cursor.value;
1315
+ if (_isEncodedBlob(value)) {
1316
+ value = _decodeBlob(value);
1317
+ }
1318
+ var result = iterator(value, cursor.key, iterationNumber++);
1319
+
1320
+ // when the iterator callback returns any
1321
+ // (non-`undefined`) value, then we stop
1322
+ // the iteration immediately
1323
+ if (result !== void 0) {
1324
+ resolve(result);
1325
+ } else {
1326
+ cursor["continue"]();
1327
+ }
1328
+ } else {
1329
+ resolve();
1330
+ }
1331
+ };
1332
+
1333
+ req.onerror = function () {
1334
+ reject(req.error);
1335
+ };
1336
+ } catch (e) {
1337
+ reject(e);
1338
+ }
1339
+ });
1340
+ })["catch"](reject);
1341
+ });
1342
+
1343
+ executeCallback(promise, callback);
1344
+
1345
+ return promise;
1346
+ }
1347
+
1348
+ function setItem(key, value, callback) {
1349
+ var self = this;
1350
+
1351
+ key = normalizeKey(key);
1352
+
1353
+ var promise = new Promise$1(function (resolve, reject) {
1354
+ var dbInfo;
1355
+ self.ready().then(function () {
1356
+ dbInfo = self._dbInfo;
1357
+ if (toString.call(value) === '[object Blob]') {
1358
+ return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
1359
+ if (blobSupport) {
1360
+ return value;
1361
+ }
1362
+ return _encodeBlob(value);
1363
+ });
1364
+ }
1365
+ return value;
1366
+ }).then(function (value) {
1367
+ createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1368
+ if (err) {
1369
+ return reject(err);
1370
+ }
1371
+
1372
+ try {
1373
+ var store = transaction.objectStore(self._dbInfo.storeName);
1374
+
1375
+ // The reason we don't _save_ null is because IE 10 does
1376
+ // not support saving the `null` type in IndexedDB. How
1377
+ // ironic, given the bug below!
1378
+ // See: https://github.com/mozilla/localForage/issues/161
1379
+ if (value === null) {
1380
+ value = undefined;
1381
+ }
1382
+
1383
+ var req = store.put(value, key);
1384
+
1385
+ transaction.oncomplete = function () {
1386
+ // Cast to undefined so the value passed to
1387
+ // callback/promise is the same as what one would get out
1388
+ // of `getItem()` later. This leads to some weirdness
1389
+ // (setItem('foo', undefined) will return `null`), but
1390
+ // it's not my fault localStorage is our baseline and that
1391
+ // it's weird.
1392
+ if (value === undefined) {
1393
+ value = null;
1394
+ }
1395
+
1396
+ resolve(value);
1397
+ };
1398
+ transaction.onabort = transaction.onerror = function () {
1399
+ var err = req.error ? req.error : req.transaction.error;
1400
+ reject(err);
1401
+ };
1402
+ } catch (e) {
1403
+ reject(e);
1404
+ }
1405
+ });
1406
+ })["catch"](reject);
1407
+ });
1408
+
1409
+ executeCallback(promise, callback);
1410
+ return promise;
1411
+ }
1412
+
1413
+ function removeItem(key, callback) {
1414
+ var self = this;
1415
+
1416
+ key = normalizeKey(key);
1417
+
1418
+ var promise = new Promise$1(function (resolve, reject) {
1419
+ self.ready().then(function () {
1420
+ createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1421
+ if (err) {
1422
+ return reject(err);
1423
+ }
1424
+
1425
+ try {
1426
+ var store = transaction.objectStore(self._dbInfo.storeName);
1427
+ // We use a Grunt task to make this safe for IE and some
1428
+ // versions of Android (including those used by Cordova).
1429
+ // Normally IE won't like `.delete()` and will insist on
1430
+ // using `['delete']()`, but we have a build step that
1431
+ // fixes this for us now.
1432
+ var req = store["delete"](key);
1433
+ transaction.oncomplete = function () {
1434
+ resolve();
1435
+ };
1436
+
1437
+ transaction.onerror = function () {
1438
+ reject(req.error);
1439
+ };
1440
+
1441
+ // The request will be also be aborted if we've exceeded our storage
1442
+ // space.
1443
+ transaction.onabort = function () {
1444
+ var err = req.error ? req.error : req.transaction.error;
1445
+ reject(err);
1446
+ };
1447
+ } catch (e) {
1448
+ reject(e);
1449
+ }
1450
+ });
1451
+ })["catch"](reject);
1452
+ });
1453
+
1454
+ executeCallback(promise, callback);
1455
+ return promise;
1456
+ }
1457
+
1458
+ function clear(callback) {
1459
+ var self = this;
1460
+
1461
+ var promise = new Promise$1(function (resolve, reject) {
1462
+ self.ready().then(function () {
1463
+ createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1464
+ if (err) {
1465
+ return reject(err);
1466
+ }
1467
+
1468
+ try {
1469
+ var store = transaction.objectStore(self._dbInfo.storeName);
1470
+ var req = store.clear();
1471
+
1472
+ transaction.oncomplete = function () {
1473
+ resolve();
1474
+ };
1475
+
1476
+ transaction.onabort = transaction.onerror = function () {
1477
+ var err = req.error ? req.error : req.transaction.error;
1478
+ reject(err);
1479
+ };
1480
+ } catch (e) {
1481
+ reject(e);
1482
+ }
1483
+ });
1484
+ })["catch"](reject);
1485
+ });
1486
+
1487
+ executeCallback(promise, callback);
1488
+ return promise;
1489
+ }
1490
+
1491
+ function length(callback) {
1492
+ var self = this;
1493
+
1494
+ var promise = new Promise$1(function (resolve, reject) {
1495
+ self.ready().then(function () {
1496
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1497
+ if (err) {
1498
+ return reject(err);
1499
+ }
1500
+
1501
+ try {
1502
+ var store = transaction.objectStore(self._dbInfo.storeName);
1503
+ var req = store.count();
1504
+
1505
+ req.onsuccess = function () {
1506
+ resolve(req.result);
1507
+ };
1508
+
1509
+ req.onerror = function () {
1510
+ reject(req.error);
1511
+ };
1512
+ } catch (e) {
1513
+ reject(e);
1514
+ }
1515
+ });
1516
+ })["catch"](reject);
1517
+ });
1518
+
1519
+ executeCallback(promise, callback);
1520
+ return promise;
1521
+ }
1522
+
1523
+ function key(n, callback) {
1524
+ var self = this;
1525
+
1526
+ var promise = new Promise$1(function (resolve, reject) {
1527
+ if (n < 0) {
1528
+ resolve(null);
1529
+
1530
+ return;
1531
+ }
1532
+
1533
+ self.ready().then(function () {
1534
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1535
+ if (err) {
1536
+ return reject(err);
1537
+ }
1538
+
1539
+ try {
1540
+ var store = transaction.objectStore(self._dbInfo.storeName);
1541
+ var advanced = false;
1542
+ var req = store.openKeyCursor();
1543
+
1544
+ req.onsuccess = function () {
1545
+ var cursor = req.result;
1546
+ if (!cursor) {
1547
+ // this means there weren't enough keys
1548
+ resolve(null);
1549
+
1550
+ return;
1551
+ }
1552
+
1553
+ if (n === 0) {
1554
+ // We have the first key, return it if that's what they
1555
+ // wanted.
1556
+ resolve(cursor.key);
1557
+ } else {
1558
+ if (!advanced) {
1559
+ // Otherwise, ask the cursor to skip ahead n
1560
+ // records.
1561
+ advanced = true;
1562
+ cursor.advance(n);
1563
+ } else {
1564
+ // When we get here, we've got the nth key.
1565
+ resolve(cursor.key);
1566
+ }
1567
+ }
1568
+ };
1569
+
1570
+ req.onerror = function () {
1571
+ reject(req.error);
1572
+ };
1573
+ } catch (e) {
1574
+ reject(e);
1575
+ }
1576
+ });
1577
+ })["catch"](reject);
1578
+ });
1579
+
1580
+ executeCallback(promise, callback);
1581
+ return promise;
1582
+ }
1583
+
1584
+ function keys(callback) {
1585
+ var self = this;
1586
+
1587
+ var promise = new Promise$1(function (resolve, reject) {
1588
+ self.ready().then(function () {
1589
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1590
+ if (err) {
1591
+ return reject(err);
1592
+ }
1593
+
1594
+ try {
1595
+ var store = transaction.objectStore(self._dbInfo.storeName);
1596
+ var req = store.openKeyCursor();
1597
+ var keys = [];
1598
+
1599
+ req.onsuccess = function () {
1600
+ var cursor = req.result;
1601
+
1602
+ if (!cursor) {
1603
+ resolve(keys);
1604
+ return;
1605
+ }
1606
+
1607
+ keys.push(cursor.key);
1608
+ cursor["continue"]();
1609
+ };
1610
+
1611
+ req.onerror = function () {
1612
+ reject(req.error);
1613
+ };
1614
+ } catch (e) {
1615
+ reject(e);
1616
+ }
1617
+ });
1618
+ })["catch"](reject);
1619
+ });
1620
+
1621
+ executeCallback(promise, callback);
1622
+ return promise;
1623
+ }
1624
+
1625
+ function dropInstance(options, callback) {
1626
+ callback = getCallback.apply(this, arguments);
1627
+
1628
+ var currentConfig = this.config();
1629
+ options = typeof options !== 'function' && options || {};
1630
+ if (!options.name) {
1631
+ options.name = options.name || currentConfig.name;
1632
+ options.storeName = options.storeName || currentConfig.storeName;
1633
+ }
1634
+
1635
+ var self = this;
1636
+ var promise;
1637
+ if (!options.name) {
1638
+ promise = Promise$1.reject('Invalid arguments');
1639
+ } else {
1640
+ var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
1641
+
1642
+ var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
1643
+ var dbContext = dbContexts[options.name];
1644
+ var forages = dbContext.forages;
1645
+ dbContext.db = db;
1646
+ for (var i = 0; i < forages.length; i++) {
1647
+ forages[i]._dbInfo.db = db;
1648
+ }
1649
+ return db;
1650
+ });
1651
+
1652
+ if (!options.storeName) {
1653
+ promise = dbPromise.then(function (db) {
1654
+ _deferReadiness(options);
1655
+
1656
+ var dbContext = dbContexts[options.name];
1657
+ var forages = dbContext.forages;
1658
+
1659
+ db.close();
1660
+ for (var i = 0; i < forages.length; i++) {
1661
+ var forage = forages[i];
1662
+ forage._dbInfo.db = null;
1663
+ }
1664
+
1665
+ var dropDBPromise = new Promise$1(function (resolve, reject) {
1666
+ var req = idb.deleteDatabase(options.name);
1667
+
1668
+ req.onerror = function () {
1669
+ var db = req.result;
1670
+ if (db) {
1671
+ db.close();
1672
+ }
1673
+ reject(req.error);
1674
+ };
1675
+
1676
+ req.onblocked = function () {
1677
+ // Closing all open connections in onversionchange handler should prevent this situation, but if
1678
+ // we do get here, it just means the request remains pending - eventually it will succeed or error
1679
+ console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
1680
+ };
1681
+
1682
+ req.onsuccess = function () {
1683
+ var db = req.result;
1684
+ if (db) {
1685
+ db.close();
1686
+ }
1687
+ resolve(db);
1688
+ };
1689
+ });
1690
+
1691
+ return dropDBPromise.then(function (db) {
1692
+ dbContext.db = db;
1693
+ for (var i = 0; i < forages.length; i++) {
1694
+ var _forage = forages[i];
1695
+ _advanceReadiness(_forage._dbInfo);
1696
+ }
1697
+ })["catch"](function (err) {
1698
+ (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1699
+ throw err;
1700
+ });
1701
+ });
1702
+ } else {
1703
+ promise = dbPromise.then(function (db) {
1704
+ if (!db.objectStoreNames.contains(options.storeName)) {
1705
+ return;
1706
+ }
1707
+
1708
+ var newVersion = db.version + 1;
1709
+
1710
+ _deferReadiness(options);
1711
+
1712
+ var dbContext = dbContexts[options.name];
1713
+ var forages = dbContext.forages;
1714
+
1715
+ db.close();
1716
+ for (var i = 0; i < forages.length; i++) {
1717
+ var forage = forages[i];
1718
+ forage._dbInfo.db = null;
1719
+ forage._dbInfo.version = newVersion;
1720
+ }
1721
+
1722
+ var dropObjectPromise = new Promise$1(function (resolve, reject) {
1723
+ var req = idb.open(options.name, newVersion);
1724
+
1725
+ req.onerror = function (err) {
1726
+ var db = req.result;
1727
+ db.close();
1728
+ reject(err);
1729
+ };
1730
+
1731
+ req.onupgradeneeded = function () {
1732
+ var db = req.result;
1733
+ db.deleteObjectStore(options.storeName);
1734
+ };
1735
+
1736
+ req.onsuccess = function () {
1737
+ var db = req.result;
1738
+ db.close();
1739
+ resolve(db);
1740
+ };
1741
+ });
1742
+
1743
+ return dropObjectPromise.then(function (db) {
1744
+ dbContext.db = db;
1745
+ for (var j = 0; j < forages.length; j++) {
1746
+ var _forage2 = forages[j];
1747
+ _forage2._dbInfo.db = db;
1748
+ _advanceReadiness(_forage2._dbInfo);
1749
+ }
1750
+ })["catch"](function (err) {
1751
+ (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1752
+ throw err;
1753
+ });
1754
+ });
1755
+ }
1756
+ }
1757
+
1758
+ executeCallback(promise, callback);
1759
+ return promise;
1760
+ }
1761
+
1762
+ var asyncStorage = {
1763
+ _driver: 'asyncStorage',
1764
+ _initStorage: _initStorage,
1765
+ _support: isIndexedDBValid(),
1766
+ iterate: iterate,
1767
+ getItem: getItem,
1768
+ setItem: setItem,
1769
+ removeItem: removeItem,
1770
+ clear: clear,
1771
+ length: length,
1772
+ key: key,
1773
+ keys: keys,
1774
+ dropInstance: dropInstance
1775
+ };
1776
+
1777
+ function isWebSQLValid() {
1778
+ return typeof openDatabase === 'function';
1779
+ }
1780
+
1781
+ // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
1782
+ // it to Base64, so this is how we store it to prevent very strange errors with less
1783
+ // verbose ways of binary <-> string data storage.
1784
+ var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1785
+
1786
+ var BLOB_TYPE_PREFIX = '~~local_forage_type~';
1787
+ var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
1788
+
1789
+ var SERIALIZED_MARKER = '__lfsc__:';
1790
+ var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
1791
+
1792
+ // OMG the serializations!
1793
+ var TYPE_ARRAYBUFFER = 'arbf';
1794
+ var TYPE_BLOB = 'blob';
1795
+ var TYPE_INT8ARRAY = 'si08';
1796
+ var TYPE_UINT8ARRAY = 'ui08';
1797
+ var TYPE_UINT8CLAMPEDARRAY = 'uic8';
1798
+ var TYPE_INT16ARRAY = 'si16';
1799
+ var TYPE_INT32ARRAY = 'si32';
1800
+ var TYPE_UINT16ARRAY = 'ur16';
1801
+ var TYPE_UINT32ARRAY = 'ui32';
1802
+ var TYPE_FLOAT32ARRAY = 'fl32';
1803
+ var TYPE_FLOAT64ARRAY = 'fl64';
1804
+ var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
1805
+
1806
+ var toString$1 = Object.prototype.toString;
1807
+
1808
+ function stringToBuffer(serializedString) {
1809
+ // Fill the string into a ArrayBuffer.
1810
+ var bufferLength = serializedString.length * 0.75;
1811
+ var len = serializedString.length;
1812
+ var i;
1813
+ var p = 0;
1814
+ var encoded1, encoded2, encoded3, encoded4;
1815
+
1816
+ if (serializedString[serializedString.length - 1] === '=') {
1817
+ bufferLength--;
1818
+ if (serializedString[serializedString.length - 2] === '=') {
1819
+ bufferLength--;
1820
+ }
1821
+ }
1822
+
1823
+ var buffer = new ArrayBuffer(bufferLength);
1824
+ var bytes = new Uint8Array(buffer);
1825
+
1826
+ for (i = 0; i < len; i += 4) {
1827
+ encoded1 = BASE_CHARS.indexOf(serializedString[i]);
1828
+ encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
1829
+ encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
1830
+ encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
1831
+
1832
+ /*jslint bitwise: true */
1833
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
1834
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
1835
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
1836
+ }
1837
+ return buffer;
1838
+ }
1839
+
1840
+ // Converts a buffer to a string to store, serialized, in the backend
1841
+ // storage library.
1842
+ function bufferToString(buffer) {
1843
+ // base64-arraybuffer
1844
+ var bytes = new Uint8Array(buffer);
1845
+ var base64String = '';
1846
+ var i;
1847
+
1848
+ for (i = 0; i < bytes.length; i += 3) {
1849
+ /*jslint bitwise: true */
1850
+ base64String += BASE_CHARS[bytes[i] >> 2];
1851
+ base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
1852
+ base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
1853
+ base64String += BASE_CHARS[bytes[i + 2] & 63];
1854
+ }
1855
+
1856
+ if (bytes.length % 3 === 2) {
1857
+ base64String = base64String.substring(0, base64String.length - 1) + '=';
1858
+ } else if (bytes.length % 3 === 1) {
1859
+ base64String = base64String.substring(0, base64String.length - 2) + '==';
1860
+ }
1861
+
1862
+ return base64String;
1863
+ }
1864
+
1865
+ // Serialize a value, afterwards executing a callback (which usually
1866
+ // instructs the `setItem()` callback/promise to be executed). This is how
1867
+ // we store binary data with localStorage.
1868
+ function serialize(value, callback) {
1869
+ var valueType = '';
1870
+ if (value) {
1871
+ valueType = toString$1.call(value);
1872
+ }
1873
+
1874
+ // Cannot use `value instanceof ArrayBuffer` or such here, as these
1875
+ // checks fail when running the tests using casper.js...
1876
+ //
1877
+ // TODO: See why those tests fail and use a better solution.
1878
+ if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
1879
+ // Convert binary arrays to a string and prefix the string with
1880
+ // a special marker.
1881
+ var buffer;
1882
+ var marker = SERIALIZED_MARKER;
1883
+
1884
+ if (value instanceof ArrayBuffer) {
1885
+ buffer = value;
1886
+ marker += TYPE_ARRAYBUFFER;
1887
+ } else {
1888
+ buffer = value.buffer;
1889
+
1890
+ if (valueType === '[object Int8Array]') {
1891
+ marker += TYPE_INT8ARRAY;
1892
+ } else if (valueType === '[object Uint8Array]') {
1893
+ marker += TYPE_UINT8ARRAY;
1894
+ } else if (valueType === '[object Uint8ClampedArray]') {
1895
+ marker += TYPE_UINT8CLAMPEDARRAY;
1896
+ } else if (valueType === '[object Int16Array]') {
1897
+ marker += TYPE_INT16ARRAY;
1898
+ } else if (valueType === '[object Uint16Array]') {
1899
+ marker += TYPE_UINT16ARRAY;
1900
+ } else if (valueType === '[object Int32Array]') {
1901
+ marker += TYPE_INT32ARRAY;
1902
+ } else if (valueType === '[object Uint32Array]') {
1903
+ marker += TYPE_UINT32ARRAY;
1904
+ } else if (valueType === '[object Float32Array]') {
1905
+ marker += TYPE_FLOAT32ARRAY;
1906
+ } else if (valueType === '[object Float64Array]') {
1907
+ marker += TYPE_FLOAT64ARRAY;
1908
+ } else {
1909
+ callback(new Error('Failed to get type for BinaryArray'));
1910
+ }
1911
+ }
1912
+
1913
+ callback(marker + bufferToString(buffer));
1914
+ } else if (valueType === '[object Blob]') {
1915
+ // Conver the blob to a binaryArray and then to a string.
1916
+ var fileReader = new FileReader();
1917
+
1918
+ fileReader.onload = function () {
1919
+ // Backwards-compatible prefix for the blob type.
1920
+ var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
1921
+
1922
+ callback(SERIALIZED_MARKER + TYPE_BLOB + str);
1923
+ };
1924
+
1925
+ fileReader.readAsArrayBuffer(value);
1926
+ } else {
1927
+ try {
1928
+ callback(JSON.stringify(value));
1929
+ } catch (e) {
1930
+ console.error("Couldn't convert value into a JSON string: ", value);
1931
+
1932
+ callback(null, e);
1933
+ }
1934
+ }
1935
+ }
1936
+
1937
+ // Deserialize data we've inserted into a value column/field. We place
1938
+ // special markers into our strings to mark them as encoded; this isn't
1939
+ // as nice as a meta field, but it's the only sane thing we can do whilst
1940
+ // keeping localStorage support intact.
1941
+ //
1942
+ // Oftentimes this will just deserialize JSON content, but if we have a
1943
+ // special marker (SERIALIZED_MARKER, defined above), we will extract
1944
+ // some kind of arraybuffer/binary data/typed array out of the string.
1945
+ function deserialize(value) {
1946
+ // If we haven't marked this string as being specially serialized (i.e.
1947
+ // something other than serialized JSON), we can just return it and be
1948
+ // done with it.
1949
+ if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
1950
+ return JSON.parse(value);
1951
+ }
1952
+
1953
+ // The following code deals with deserializing some kind of Blob or
1954
+ // TypedArray. First we separate out the type of data we're dealing
1955
+ // with from the data itself.
1956
+ var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
1957
+ var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
1958
+
1959
+ var blobType;
1960
+ // Backwards-compatible blob type serialization strategy.
1961
+ // DBs created with older versions of localForage will simply not have the blob type.
1962
+ if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
1963
+ var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
1964
+ blobType = matcher[1];
1965
+ serializedString = serializedString.substring(matcher[0].length);
1966
+ }
1967
+ var buffer = stringToBuffer(serializedString);
1968
+
1969
+ // Return the right type based on the code/type set during
1970
+ // serialization.
1971
+ switch (type) {
1972
+ case TYPE_ARRAYBUFFER:
1973
+ return buffer;
1974
+ case TYPE_BLOB:
1975
+ return createBlob([buffer], { type: blobType });
1976
+ case TYPE_INT8ARRAY:
1977
+ return new Int8Array(buffer);
1978
+ case TYPE_UINT8ARRAY:
1979
+ return new Uint8Array(buffer);
1980
+ case TYPE_UINT8CLAMPEDARRAY:
1981
+ return new Uint8ClampedArray(buffer);
1982
+ case TYPE_INT16ARRAY:
1983
+ return new Int16Array(buffer);
1984
+ case TYPE_UINT16ARRAY:
1985
+ return new Uint16Array(buffer);
1986
+ case TYPE_INT32ARRAY:
1987
+ return new Int32Array(buffer);
1988
+ case TYPE_UINT32ARRAY:
1989
+ return new Uint32Array(buffer);
1990
+ case TYPE_FLOAT32ARRAY:
1991
+ return new Float32Array(buffer);
1992
+ case TYPE_FLOAT64ARRAY:
1993
+ return new Float64Array(buffer);
1994
+ default:
1995
+ throw new Error('Unkown type: ' + type);
1996
+ }
1997
+ }
1998
+
1999
+ var localforageSerializer = {
2000
+ serialize: serialize,
2001
+ deserialize: deserialize,
2002
+ stringToBuffer: stringToBuffer,
2003
+ bufferToString: bufferToString
2004
+ };
2005
+
2006
+ /*
2007
+ * Includes code from:
2008
+ *
2009
+ * base64-arraybuffer
2010
+ * https://github.com/niklasvh/base64-arraybuffer
2011
+ *
2012
+ * Copyright (c) 2012 Niklas von Hertzen
2013
+ * Licensed under the MIT license.
2014
+ */
2015
+
2016
+ function createDbTable(t, dbInfo, callback, errorCallback) {
2017
+ t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
2018
+ }
2019
+
2020
+ // Open the WebSQL database (automatically creates one if one didn't
2021
+ // previously exist), using any options set in the config.
2022
+ function _initStorage$1(options) {
2023
+ var self = this;
2024
+ var dbInfo = {
2025
+ db: null
2026
+ };
2027
+
2028
+ if (options) {
2029
+ for (var i in options) {
2030
+ dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
2031
+ }
2032
+ }
2033
+
2034
+ var dbInfoPromise = new Promise$1(function (resolve, reject) {
2035
+ // Open the database; the openDatabase API will automatically
2036
+ // create it for us if it doesn't exist.
2037
+ try {
2038
+ dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
2039
+ } catch (e) {
2040
+ return reject(e);
2041
+ }
2042
+
2043
+ // Create our key/value table if it doesn't exist.
2044
+ dbInfo.db.transaction(function (t) {
2045
+ createDbTable(t, dbInfo, function () {
2046
+ self._dbInfo = dbInfo;
2047
+ resolve();
2048
+ }, function (t, error) {
2049
+ reject(error);
2050
+ });
2051
+ }, reject);
2052
+ });
2053
+
2054
+ dbInfo.serializer = localforageSerializer;
2055
+ return dbInfoPromise;
2056
+ }
2057
+
2058
+ function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
2059
+ t.executeSql(sqlStatement, args, callback, function (t, error) {
2060
+ if (error.code === error.SYNTAX_ERR) {
2061
+ t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
2062
+ if (!results.rows.length) {
2063
+ // if the table is missing (was deleted)
2064
+ // re-create it table and retry
2065
+ createDbTable(t, dbInfo, function () {
2066
+ t.executeSql(sqlStatement, args, callback, errorCallback);
2067
+ }, errorCallback);
2068
+ } else {
2069
+ errorCallback(t, error);
2070
+ }
2071
+ }, errorCallback);
2072
+ } else {
2073
+ errorCallback(t, error);
2074
+ }
2075
+ }, errorCallback);
2076
+ }
2077
+
2078
+ function getItem$1(key, callback) {
2079
+ var self = this;
2080
+
2081
+ key = normalizeKey(key);
2082
+
2083
+ var promise = new Promise$1(function (resolve, reject) {
2084
+ self.ready().then(function () {
2085
+ var dbInfo = self._dbInfo;
2086
+ dbInfo.db.transaction(function (t) {
2087
+ tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
2088
+ var result = results.rows.length ? results.rows.item(0).value : null;
2089
+
2090
+ // Check to see if this is serialized content we need to
2091
+ // unpack.
2092
+ if (result) {
2093
+ result = dbInfo.serializer.deserialize(result);
2094
+ }
2095
+
2096
+ resolve(result);
2097
+ }, function (t, error) {
2098
+ reject(error);
2099
+ });
2100
+ });
2101
+ })["catch"](reject);
2102
+ });
2103
+
2104
+ executeCallback(promise, callback);
2105
+ return promise;
2106
+ }
2107
+
2108
+ function iterate$1(iterator, callback) {
2109
+ var self = this;
2110
+
2111
+ var promise = new Promise$1(function (resolve, reject) {
2112
+ self.ready().then(function () {
2113
+ var dbInfo = self._dbInfo;
2114
+
2115
+ dbInfo.db.transaction(function (t) {
2116
+ tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
2117
+ var rows = results.rows;
2118
+ var length = rows.length;
2119
+
2120
+ for (var i = 0; i < length; i++) {
2121
+ var item = rows.item(i);
2122
+ var result = item.value;
2123
+
2124
+ // Check to see if this is serialized content
2125
+ // we need to unpack.
2126
+ if (result) {
2127
+ result = dbInfo.serializer.deserialize(result);
2128
+ }
2129
+
2130
+ result = iterator(result, item.key, i + 1);
2131
+
2132
+ // void(0) prevents problems with redefinition
2133
+ // of `undefined`.
2134
+ if (result !== void 0) {
2135
+ resolve(result);
2136
+ return;
2137
+ }
2138
+ }
2139
+
2140
+ resolve();
2141
+ }, function (t, error) {
2142
+ reject(error);
2143
+ });
2144
+ });
2145
+ })["catch"](reject);
2146
+ });
2147
+
2148
+ executeCallback(promise, callback);
2149
+ return promise;
2150
+ }
2151
+
2152
+ function _setItem(key, value, callback, retriesLeft) {
2153
+ var self = this;
2154
+
2155
+ key = normalizeKey(key);
2156
+
2157
+ var promise = new Promise$1(function (resolve, reject) {
2158
+ self.ready().then(function () {
2159
+ // The localStorage API doesn't return undefined values in an
2160
+ // "expected" way, so undefined is always cast to null in all
2161
+ // drivers. See: https://github.com/mozilla/localForage/pull/42
2162
+ if (value === undefined) {
2163
+ value = null;
2164
+ }
2165
+
2166
+ // Save the original value to pass to the callback.
2167
+ var originalValue = value;
2168
+
2169
+ var dbInfo = self._dbInfo;
2170
+ dbInfo.serializer.serialize(value, function (value, error) {
2171
+ if (error) {
2172
+ reject(error);
2173
+ } else {
2174
+ dbInfo.db.transaction(function (t) {
2175
+ tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
2176
+ resolve(originalValue);
2177
+ }, function (t, error) {
2178
+ reject(error);
2179
+ });
2180
+ }, function (sqlError) {
2181
+ // The transaction failed; check
2182
+ // to see if it's a quota error.
2183
+ if (sqlError.code === sqlError.QUOTA_ERR) {
2184
+ // We reject the callback outright for now, but
2185
+ // it's worth trying to re-run the transaction.
2186
+ // Even if the user accepts the prompt to use
2187
+ // more storage on Safari, this error will
2188
+ // be called.
2189
+ //
2190
+ // Try to re-run the transaction.
2191
+ if (retriesLeft > 0) {
2192
+ resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
2193
+ return;
2194
+ }
2195
+ reject(sqlError);
2196
+ }
2197
+ });
2198
+ }
2199
+ });
2200
+ })["catch"](reject);
2201
+ });
2202
+
2203
+ executeCallback(promise, callback);
2204
+ return promise;
2205
+ }
2206
+
2207
+ function setItem$1(key, value, callback) {
2208
+ return _setItem.apply(this, [key, value, callback, 1]);
2209
+ }
2210
+
2211
+ function removeItem$1(key, callback) {
2212
+ var self = this;
2213
+
2214
+ key = normalizeKey(key);
2215
+
2216
+ var promise = new Promise$1(function (resolve, reject) {
2217
+ self.ready().then(function () {
2218
+ var dbInfo = self._dbInfo;
2219
+ dbInfo.db.transaction(function (t) {
2220
+ tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
2221
+ resolve();
2222
+ }, function (t, error) {
2223
+ reject(error);
2224
+ });
2225
+ });
2226
+ })["catch"](reject);
2227
+ });
2228
+
2229
+ executeCallback(promise, callback);
2230
+ return promise;
2231
+ }
2232
+
2233
+ // Deletes every item in the table.
2234
+ // TODO: Find out if this resets the AUTO_INCREMENT number.
2235
+ function clear$1(callback) {
2236
+ var self = this;
2237
+
2238
+ var promise = new Promise$1(function (resolve, reject) {
2239
+ self.ready().then(function () {
2240
+ var dbInfo = self._dbInfo;
2241
+ dbInfo.db.transaction(function (t) {
2242
+ tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
2243
+ resolve();
2244
+ }, function (t, error) {
2245
+ reject(error);
2246
+ });
2247
+ });
2248
+ })["catch"](reject);
2249
+ });
2250
+
2251
+ executeCallback(promise, callback);
2252
+ return promise;
2253
+ }
2254
+
2255
+ // Does a simple `COUNT(key)` to get the number of items stored in
2256
+ // localForage.
2257
+ function length$1(callback) {
2258
+ var self = this;
2259
+
2260
+ var promise = new Promise$1(function (resolve, reject) {
2261
+ self.ready().then(function () {
2262
+ var dbInfo = self._dbInfo;
2263
+ dbInfo.db.transaction(function (t) {
2264
+ // Ahhh, SQL makes this one soooooo easy.
2265
+ tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
2266
+ var result = results.rows.item(0).c;
2267
+ resolve(result);
2268
+ }, function (t, error) {
2269
+ reject(error);
2270
+ });
2271
+ });
2272
+ })["catch"](reject);
2273
+ });
2274
+
2275
+ executeCallback(promise, callback);
2276
+ return promise;
2277
+ }
2278
+
2279
+ // Return the key located at key index X; essentially gets the key from a
2280
+ // `WHERE id = ?`. This is the most efficient way I can think to implement
2281
+ // this rarely-used (in my experience) part of the API, but it can seem
2282
+ // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
2283
+ // the ID of each key will change every time it's updated. Perhaps a stored
2284
+ // procedure for the `setItem()` SQL would solve this problem?
2285
+ // TODO: Don't change ID on `setItem()`.
2286
+ function key$1(n, callback) {
2287
+ var self = this;
2288
+
2289
+ var promise = new Promise$1(function (resolve, reject) {
2290
+ self.ready().then(function () {
2291
+ var dbInfo = self._dbInfo;
2292
+ dbInfo.db.transaction(function (t) {
2293
+ tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
2294
+ var result = results.rows.length ? results.rows.item(0).key : null;
2295
+ resolve(result);
2296
+ }, function (t, error) {
2297
+ reject(error);
2298
+ });
2299
+ });
2300
+ })["catch"](reject);
2301
+ });
2302
+
2303
+ executeCallback(promise, callback);
2304
+ return promise;
2305
+ }
2306
+
2307
+ function keys$1(callback) {
2308
+ var self = this;
2309
+
2310
+ var promise = new Promise$1(function (resolve, reject) {
2311
+ self.ready().then(function () {
2312
+ var dbInfo = self._dbInfo;
2313
+ dbInfo.db.transaction(function (t) {
2314
+ tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
2315
+ var keys = [];
2316
+
2317
+ for (var i = 0; i < results.rows.length; i++) {
2318
+ keys.push(results.rows.item(i).key);
2319
+ }
2320
+
2321
+ resolve(keys);
2322
+ }, function (t, error) {
2323
+ reject(error);
2324
+ });
2325
+ });
2326
+ })["catch"](reject);
2327
+ });
2328
+
2329
+ executeCallback(promise, callback);
2330
+ return promise;
2331
+ }
2332
+
2333
+ // https://www.w3.org/TR/webdatabase/#databases
2334
+ // > There is no way to enumerate or delete the databases available for an origin from this API.
2335
+ function getAllStoreNames(db) {
2336
+ return new Promise$1(function (resolve, reject) {
2337
+ db.transaction(function (t) {
2338
+ t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
2339
+ var storeNames = [];
2340
+
2341
+ for (var i = 0; i < results.rows.length; i++) {
2342
+ storeNames.push(results.rows.item(i).name);
2343
+ }
2344
+
2345
+ resolve({
2346
+ db: db,
2347
+ storeNames: storeNames
2348
+ });
2349
+ }, function (t, error) {
2350
+ reject(error);
2351
+ });
2352
+ }, function (sqlError) {
2353
+ reject(sqlError);
2354
+ });
2355
+ });
2356
+ }
2357
+
2358
+ function dropInstance$1(options, callback) {
2359
+ callback = getCallback.apply(this, arguments);
2360
+
2361
+ var currentConfig = this.config();
2362
+ options = typeof options !== 'function' && options || {};
2363
+ if (!options.name) {
2364
+ options.name = options.name || currentConfig.name;
2365
+ options.storeName = options.storeName || currentConfig.storeName;
2366
+ }
2367
+
2368
+ var self = this;
2369
+ var promise;
2370
+ if (!options.name) {
2371
+ promise = Promise$1.reject('Invalid arguments');
2372
+ } else {
2373
+ promise = new Promise$1(function (resolve) {
2374
+ var db;
2375
+ if (options.name === currentConfig.name) {
2376
+ // use the db reference of the current instance
2377
+ db = self._dbInfo.db;
2378
+ } else {
2379
+ db = openDatabase(options.name, '', '', 0);
2380
+ }
2381
+
2382
+ if (!options.storeName) {
2383
+ // drop all database tables
2384
+ resolve(getAllStoreNames(db));
2385
+ } else {
2386
+ resolve({
2387
+ db: db,
2388
+ storeNames: [options.storeName]
2389
+ });
2390
+ }
2391
+ }).then(function (operationInfo) {
2392
+ return new Promise$1(function (resolve, reject) {
2393
+ operationInfo.db.transaction(function (t) {
2394
+ function dropTable(storeName) {
2395
+ return new Promise$1(function (resolve, reject) {
2396
+ t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
2397
+ resolve();
2398
+ }, function (t, error) {
2399
+ reject(error);
2400
+ });
2401
+ });
2402
+ }
2403
+
2404
+ var operations = [];
2405
+ for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
2406
+ operations.push(dropTable(operationInfo.storeNames[i]));
2407
+ }
2408
+
2409
+ Promise$1.all(operations).then(function () {
2410
+ resolve();
2411
+ })["catch"](function (e) {
2412
+ reject(e);
2413
+ });
2414
+ }, function (sqlError) {
2415
+ reject(sqlError);
2416
+ });
2417
+ });
2418
+ });
2419
+ }
2420
+
2421
+ executeCallback(promise, callback);
2422
+ return promise;
2423
+ }
2424
+
2425
+ var webSQLStorage = {
2426
+ _driver: 'webSQLStorage',
2427
+ _initStorage: _initStorage$1,
2428
+ _support: isWebSQLValid(),
2429
+ iterate: iterate$1,
2430
+ getItem: getItem$1,
2431
+ setItem: setItem$1,
2432
+ removeItem: removeItem$1,
2433
+ clear: clear$1,
2434
+ length: length$1,
2435
+ key: key$1,
2436
+ keys: keys$1,
2437
+ dropInstance: dropInstance$1
2438
+ };
2439
+
2440
+ function isLocalStorageValid() {
2441
+ try {
2442
+ return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
2443
+ // in IE8 typeof localStorage.setItem === 'object'
2444
+ !!localStorage.setItem;
2445
+ } catch (e) {
2446
+ return false;
2447
+ }
2448
+ }
2449
+
2450
+ function _getKeyPrefix(options, defaultConfig) {
2451
+ var keyPrefix = options.name + '/';
2452
+
2453
+ if (options.storeName !== defaultConfig.storeName) {
2454
+ keyPrefix += options.storeName + '/';
2455
+ }
2456
+ return keyPrefix;
2457
+ }
2458
+
2459
+ // Check if localStorage throws when saving an item
2460
+ function checkIfLocalStorageThrows() {
2461
+ var localStorageTestKey = '_localforage_support_test';
2462
+
2463
+ try {
2464
+ localStorage.setItem(localStorageTestKey, true);
2465
+ localStorage.removeItem(localStorageTestKey);
2466
+
2467
+ return false;
2468
+ } catch (e) {
2469
+ return true;
2470
+ }
2471
+ }
2472
+
2473
+ // Check if localStorage is usable and allows to save an item
2474
+ // This method checks if localStorage is usable in Safari Private Browsing
2475
+ // mode, or in any other case where the available quota for localStorage
2476
+ // is 0 and there wasn't any saved items yet.
2477
+ function _isLocalStorageUsable() {
2478
+ return !checkIfLocalStorageThrows() || localStorage.length > 0;
2479
+ }
2480
+
2481
+ // Config the localStorage backend, using options set in the config.
2482
+ function _initStorage$2(options) {
2483
+ var self = this;
2484
+ var dbInfo = {};
2485
+ if (options) {
2486
+ for (var i in options) {
2487
+ dbInfo[i] = options[i];
2488
+ }
2489
+ }
2490
+
2491
+ dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
2492
+
2493
+ if (!_isLocalStorageUsable()) {
2494
+ return Promise$1.reject();
2495
+ }
2496
+
2497
+ self._dbInfo = dbInfo;
2498
+ dbInfo.serializer = localforageSerializer;
2499
+
2500
+ return Promise$1.resolve();
2501
+ }
2502
+
2503
+ // Remove all keys from the datastore, effectively destroying all data in
2504
+ // the app's key/value store!
2505
+ function clear$2(callback) {
2506
+ var self = this;
2507
+ var promise = self.ready().then(function () {
2508
+ var keyPrefix = self._dbInfo.keyPrefix;
2509
+
2510
+ for (var i = localStorage.length - 1; i >= 0; i--) {
2511
+ var key = localStorage.key(i);
2512
+
2513
+ if (key.indexOf(keyPrefix) === 0) {
2514
+ localStorage.removeItem(key);
2515
+ }
2516
+ }
2517
+ });
2518
+
2519
+ executeCallback(promise, callback);
2520
+ return promise;
2521
+ }
2522
+
2523
+ // Retrieve an item from the store. Unlike the original async_storage
2524
+ // library in Gaia, we don't modify return values at all. If a key's value
2525
+ // is `undefined`, we pass that value to the callback function.
2526
+ function getItem$2(key, callback) {
2527
+ var self = this;
2528
+
2529
+ key = normalizeKey(key);
2530
+
2531
+ var promise = self.ready().then(function () {
2532
+ var dbInfo = self._dbInfo;
2533
+ var result = localStorage.getItem(dbInfo.keyPrefix + key);
2534
+
2535
+ // If a result was found, parse it from the serialized
2536
+ // string into a JS object. If result isn't truthy, the key
2537
+ // is likely undefined and we'll pass it straight to the
2538
+ // callback.
2539
+ if (result) {
2540
+ result = dbInfo.serializer.deserialize(result);
2541
+ }
2542
+
2543
+ return result;
2544
+ });
2545
+
2546
+ executeCallback(promise, callback);
2547
+ return promise;
2548
+ }
2549
+
2550
+ // Iterate over all items in the store.
2551
+ function iterate$2(iterator, callback) {
2552
+ var self = this;
2553
+
2554
+ var promise = self.ready().then(function () {
2555
+ var dbInfo = self._dbInfo;
2556
+ var keyPrefix = dbInfo.keyPrefix;
2557
+ var keyPrefixLength = keyPrefix.length;
2558
+ var length = localStorage.length;
2559
+
2560
+ // We use a dedicated iterator instead of the `i` variable below
2561
+ // so other keys we fetch in localStorage aren't counted in
2562
+ // the `iterationNumber` argument passed to the `iterate()`
2563
+ // callback.
2564
+ //
2565
+ // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
2566
+ var iterationNumber = 1;
2567
+
2568
+ for (var i = 0; i < length; i++) {
2569
+ var key = localStorage.key(i);
2570
+ if (key.indexOf(keyPrefix) !== 0) {
2571
+ continue;
2572
+ }
2573
+ var value = localStorage.getItem(key);
2574
+
2575
+ // If a result was found, parse it from the serialized
2576
+ // string into a JS object. If result isn't truthy, the
2577
+ // key is likely undefined and we'll pass it straight
2578
+ // to the iterator.
2579
+ if (value) {
2580
+ value = dbInfo.serializer.deserialize(value);
2581
+ }
2582
+
2583
+ value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
2584
+
2585
+ if (value !== void 0) {
2586
+ return value;
2587
+ }
2588
+ }
2589
+ });
2590
+
2591
+ executeCallback(promise, callback);
2592
+ return promise;
2593
+ }
2594
+
2595
+ // Same as localStorage's key() method, except takes a callback.
2596
+ function key$2(n, callback) {
2597
+ var self = this;
2598
+ var promise = self.ready().then(function () {
2599
+ var dbInfo = self._dbInfo;
2600
+ var result;
2601
+ try {
2602
+ result = localStorage.key(n);
2603
+ } catch (error) {
2604
+ result = null;
2605
+ }
2606
+
2607
+ // Remove the prefix from the key, if a key is found.
2608
+ if (result) {
2609
+ result = result.substring(dbInfo.keyPrefix.length);
2610
+ }
2611
+
2612
+ return result;
2613
+ });
2614
+
2615
+ executeCallback(promise, callback);
2616
+ return promise;
2617
+ }
2618
+
2619
+ function keys$2(callback) {
2620
+ var self = this;
2621
+ var promise = self.ready().then(function () {
2622
+ var dbInfo = self._dbInfo;
2623
+ var length = localStorage.length;
2624
+ var keys = [];
2625
+
2626
+ for (var i = 0; i < length; i++) {
2627
+ var itemKey = localStorage.key(i);
2628
+ if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
2629
+ keys.push(itemKey.substring(dbInfo.keyPrefix.length));
2630
+ }
2631
+ }
2632
+
2633
+ return keys;
2634
+ });
2635
+
2636
+ executeCallback(promise, callback);
2637
+ return promise;
2638
+ }
2639
+
2640
+ // Supply the number of keys in the datastore to the callback function.
2641
+ function length$2(callback) {
2642
+ var self = this;
2643
+ var promise = self.keys().then(function (keys) {
2644
+ return keys.length;
2645
+ });
2646
+
2647
+ executeCallback(promise, callback);
2648
+ return promise;
2649
+ }
2650
+
2651
+ // Remove an item from the store, nice and simple.
2652
+ function removeItem$2(key, callback) {
2653
+ var self = this;
2654
+
2655
+ key = normalizeKey(key);
2656
+
2657
+ var promise = self.ready().then(function () {
2658
+ var dbInfo = self._dbInfo;
2659
+ localStorage.removeItem(dbInfo.keyPrefix + key);
2660
+ });
2661
+
2662
+ executeCallback(promise, callback);
2663
+ return promise;
2664
+ }
2665
+
2666
+ // Set a key's value and run an optional callback once the value is set.
2667
+ // Unlike Gaia's implementation, the callback function is passed the value,
2668
+ // in case you want to operate on that value only after you're sure it
2669
+ // saved, or something like that.
2670
+ function setItem$2(key, value, callback) {
2671
+ var self = this;
2672
+
2673
+ key = normalizeKey(key);
2674
+
2675
+ var promise = self.ready().then(function () {
2676
+ // Convert undefined values to null.
2677
+ // https://github.com/mozilla/localForage/pull/42
2678
+ if (value === undefined) {
2679
+ value = null;
2680
+ }
2681
+
2682
+ // Save the original value to pass to the callback.
2683
+ var originalValue = value;
2684
+
2685
+ return new Promise$1(function (resolve, reject) {
2686
+ var dbInfo = self._dbInfo;
2687
+ dbInfo.serializer.serialize(value, function (value, error) {
2688
+ if (error) {
2689
+ reject(error);
2690
+ } else {
2691
+ try {
2692
+ localStorage.setItem(dbInfo.keyPrefix + key, value);
2693
+ resolve(originalValue);
2694
+ } catch (e) {
2695
+ // localStorage capacity exceeded.
2696
+ // TODO: Make this a specific error/event.
2697
+ if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
2698
+ reject(e);
2699
+ }
2700
+ reject(e);
2701
+ }
2702
+ }
2703
+ });
2704
+ });
2705
+ });
2706
+
2707
+ executeCallback(promise, callback);
2708
+ return promise;
2709
+ }
2710
+
2711
+ function dropInstance$2(options, callback) {
2712
+ callback = getCallback.apply(this, arguments);
2713
+
2714
+ options = typeof options !== 'function' && options || {};
2715
+ if (!options.name) {
2716
+ var currentConfig = this.config();
2717
+ options.name = options.name || currentConfig.name;
2718
+ options.storeName = options.storeName || currentConfig.storeName;
2719
+ }
2720
+
2721
+ var self = this;
2722
+ var promise;
2723
+ if (!options.name) {
2724
+ promise = Promise$1.reject('Invalid arguments');
2725
+ } else {
2726
+ promise = new Promise$1(function (resolve) {
2727
+ if (!options.storeName) {
2728
+ resolve(options.name + '/');
2729
+ } else {
2730
+ resolve(_getKeyPrefix(options, self._defaultConfig));
2731
+ }
2732
+ }).then(function (keyPrefix) {
2733
+ for (var i = localStorage.length - 1; i >= 0; i--) {
2734
+ var key = localStorage.key(i);
2735
+
2736
+ if (key.indexOf(keyPrefix) === 0) {
2737
+ localStorage.removeItem(key);
2738
+ }
2739
+ }
2740
+ });
2741
+ }
2742
+
2743
+ executeCallback(promise, callback);
2744
+ return promise;
2745
+ }
2746
+
2747
+ var localStorageWrapper = {
2748
+ _driver: 'localStorageWrapper',
2749
+ _initStorage: _initStorage$2,
2750
+ _support: isLocalStorageValid(),
2751
+ iterate: iterate$2,
2752
+ getItem: getItem$2,
2753
+ setItem: setItem$2,
2754
+ removeItem: removeItem$2,
2755
+ clear: clear$2,
2756
+ length: length$2,
2757
+ key: key$2,
2758
+ keys: keys$2,
2759
+ dropInstance: dropInstance$2
2760
+ };
2761
+
2762
+ var sameValue = function sameValue(x, y) {
2763
+ return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
2764
+ };
2765
+
2766
+ var includes = function includes(array, searchElement) {
2767
+ var len = array.length;
2768
+ var i = 0;
2769
+ while (i < len) {
2770
+ if (sameValue(array[i], searchElement)) {
2771
+ return true;
2772
+ }
2773
+ i++;
2774
+ }
2775
+
2776
+ return false;
2777
+ };
2778
+
2779
+ var isArray = Array.isArray || function (arg) {
2780
+ return Object.prototype.toString.call(arg) === '[object Array]';
2781
+ };
2782
+
2783
+ // Drivers are stored here when `defineDriver()` is called.
2784
+ // They are shared across all instances of localForage.
2785
+ var DefinedDrivers = {};
2786
+
2787
+ var DriverSupport = {};
2788
+
2789
+ var DefaultDrivers = {
2790
+ INDEXEDDB: asyncStorage,
2791
+ WEBSQL: webSQLStorage,
2792
+ LOCALSTORAGE: localStorageWrapper
2793
+ };
2794
+
2795
+ var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
2796
+
2797
+ var OptionalDriverMethods = ['dropInstance'];
2798
+
2799
+ var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
2800
+
2801
+ var DefaultConfig = {
2802
+ description: '',
2803
+ driver: DefaultDriverOrder.slice(),
2804
+ name: 'localforage',
2805
+ // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
2806
+ // we can use without a prompt.
2807
+ size: 4980736,
2808
+ storeName: 'keyvaluepairs',
2809
+ version: 1.0
2810
+ };
2811
+
2812
+ function callWhenReady(localForageInstance, libraryMethod) {
2813
+ localForageInstance[libraryMethod] = function () {
2814
+ var _args = arguments;
2815
+ return localForageInstance.ready().then(function () {
2816
+ return localForageInstance[libraryMethod].apply(localForageInstance, _args);
2817
+ });
2818
+ };
2819
+ }
2820
+
2821
+ function extend() {
2822
+ for (var i = 1; i < arguments.length; i++) {
2823
+ var arg = arguments[i];
2824
+
2825
+ if (arg) {
2826
+ for (var _key in arg) {
2827
+ if (arg.hasOwnProperty(_key)) {
2828
+ if (isArray(arg[_key])) {
2829
+ arguments[0][_key] = arg[_key].slice();
2830
+ } else {
2831
+ arguments[0][_key] = arg[_key];
2832
+ }
2833
+ }
2834
+ }
2835
+ }
2836
+ }
2837
+
2838
+ return arguments[0];
2839
+ }
2840
+
2841
+ var LocalForage = function () {
2842
+ function LocalForage(options) {
2843
+ _classCallCheck(this, LocalForage);
2844
+
2845
+ for (var driverTypeKey in DefaultDrivers) {
2846
+ if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
2847
+ var driver = DefaultDrivers[driverTypeKey];
2848
+ var driverName = driver._driver;
2849
+ this[driverTypeKey] = driverName;
2850
+
2851
+ if (!DefinedDrivers[driverName]) {
2852
+ // we don't need to wait for the promise,
2853
+ // since the default drivers can be defined
2854
+ // in a blocking manner
2855
+ this.defineDriver(driver);
2856
+ }
2857
+ }
2858
+ }
2859
+
2860
+ this._defaultConfig = extend({}, DefaultConfig);
2861
+ this._config = extend({}, this._defaultConfig, options);
2862
+ this._driverSet = null;
2863
+ this._initDriver = null;
2864
+ this._ready = false;
2865
+ this._dbInfo = null;
2866
+
2867
+ this._wrapLibraryMethodsWithReady();
2868
+ this.setDriver(this._config.driver)["catch"](function () {});
2869
+ }
2870
+
2871
+ // Set any config values for localForage; can be called anytime before
2872
+ // the first API call (e.g. `getItem`, `setItem`).
2873
+ // We loop through options so we don't overwrite existing config
2874
+ // values.
2875
+
2876
+
2877
+ LocalForage.prototype.config = function config(options) {
2878
+ // If the options argument is an object, we use it to set values.
2879
+ // Otherwise, we return either a specified config value or all
2880
+ // config values.
2881
+ if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
2882
+ // If localforage is ready and fully initialized, we can't set
2883
+ // any new configuration values. Instead, we return an error.
2884
+ if (this._ready) {
2885
+ return new Error("Can't call config() after localforage " + 'has been used.');
2886
+ }
2887
+
2888
+ for (var i in options) {
2889
+ if (i === 'storeName') {
2890
+ options[i] = options[i].replace(/\W/g, '_');
2891
+ }
2892
+
2893
+ if (i === 'version' && typeof options[i] !== 'number') {
2894
+ return new Error('Database version must be a number.');
2895
+ }
2896
+
2897
+ this._config[i] = options[i];
2898
+ }
2899
+
2900
+ // after all config options are set and
2901
+ // the driver option is used, try setting it
2902
+ if ('driver' in options && options.driver) {
2903
+ return this.setDriver(this._config.driver);
2904
+ }
2905
+
2906
+ return true;
2907
+ } else if (typeof options === 'string') {
2908
+ return this._config[options];
2909
+ } else {
2910
+ return this._config;
2911
+ }
2912
+ };
2913
+
2914
+ // Used to define a custom driver, shared across all instances of
2915
+ // localForage.
2916
+
2917
+
2918
+ LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
2919
+ var promise = new Promise$1(function (resolve, reject) {
2920
+ try {
2921
+ var driverName = driverObject._driver;
2922
+ var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
2923
+
2924
+ // A driver name should be defined and not overlap with the
2925
+ // library-defined, default drivers.
2926
+ if (!driverObject._driver) {
2927
+ reject(complianceError);
2928
+ return;
2929
+ }
2930
+
2931
+ var driverMethods = LibraryMethods.concat('_initStorage');
2932
+ for (var i = 0, len = driverMethods.length; i < len; i++) {
2933
+ var driverMethodName = driverMethods[i];
2934
+
2935
+ // when the property is there,
2936
+ // it should be a method even when optional
2937
+ var isRequired = !includes(OptionalDriverMethods, driverMethodName);
2938
+ if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
2939
+ reject(complianceError);
2940
+ return;
2941
+ }
2942
+ }
2943
+
2944
+ var configureMissingMethods = function configureMissingMethods() {
2945
+ var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
2946
+ return function () {
2947
+ var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
2948
+ var promise = Promise$1.reject(error);
2949
+ executeCallback(promise, arguments[arguments.length - 1]);
2950
+ return promise;
2951
+ };
2952
+ };
2953
+
2954
+ for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
2955
+ var optionalDriverMethod = OptionalDriverMethods[_i];
2956
+ if (!driverObject[optionalDriverMethod]) {
2957
+ driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
2958
+ }
2959
+ }
2960
+ };
2961
+
2962
+ configureMissingMethods();
2963
+
2964
+ var setDriverSupport = function setDriverSupport(support) {
2965
+ if (DefinedDrivers[driverName]) {
2966
+ console.info('Redefining LocalForage driver: ' + driverName);
2967
+ }
2968
+ DefinedDrivers[driverName] = driverObject;
2969
+ DriverSupport[driverName] = support;
2970
+ // don't use a then, so that we can define
2971
+ // drivers that have simple _support methods
2972
+ // in a blocking manner
2973
+ resolve();
2974
+ };
2975
+
2976
+ if ('_support' in driverObject) {
2977
+ if (driverObject._support && typeof driverObject._support === 'function') {
2978
+ driverObject._support().then(setDriverSupport, reject);
2979
+ } else {
2980
+ setDriverSupport(!!driverObject._support);
2981
+ }
2982
+ } else {
2983
+ setDriverSupport(true);
2984
+ }
2985
+ } catch (e) {
2986
+ reject(e);
2987
+ }
2988
+ });
2989
+
2990
+ executeTwoCallbacks(promise, callback, errorCallback);
2991
+ return promise;
2992
+ };
2993
+
2994
+ LocalForage.prototype.driver = function driver() {
2995
+ return this._driver || null;
2996
+ };
2997
+
2998
+ LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
2999
+ var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
3000
+
3001
+ executeTwoCallbacks(getDriverPromise, callback, errorCallback);
3002
+ return getDriverPromise;
3003
+ };
3004
+
3005
+ LocalForage.prototype.getSerializer = function getSerializer(callback) {
3006
+ var serializerPromise = Promise$1.resolve(localforageSerializer);
3007
+ executeTwoCallbacks(serializerPromise, callback);
3008
+ return serializerPromise;
3009
+ };
3010
+
3011
+ LocalForage.prototype.ready = function ready(callback) {
3012
+ var self = this;
3013
+
3014
+ var promise = self._driverSet.then(function () {
3015
+ if (self._ready === null) {
3016
+ self._ready = self._initDriver();
3017
+ }
3018
+
3019
+ return self._ready;
3020
+ });
3021
+
3022
+ executeTwoCallbacks(promise, callback, callback);
3023
+ return promise;
3024
+ };
3025
+
3026
+ LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
3027
+ var self = this;
3028
+
3029
+ if (!isArray(drivers)) {
3030
+ drivers = [drivers];
3031
+ }
3032
+
3033
+ var supportedDrivers = this._getSupportedDrivers(drivers);
3034
+
3035
+ function setDriverToConfig() {
3036
+ self._config.driver = self.driver();
3037
+ }
3038
+
3039
+ function extendSelfWithDriver(driver) {
3040
+ self._extend(driver);
3041
+ setDriverToConfig();
3042
+
3043
+ self._ready = self._initStorage(self._config);
3044
+ return self._ready;
3045
+ }
3046
+
3047
+ function initDriver(supportedDrivers) {
3048
+ return function () {
3049
+ var currentDriverIndex = 0;
3050
+
3051
+ function driverPromiseLoop() {
3052
+ while (currentDriverIndex < supportedDrivers.length) {
3053
+ var driverName = supportedDrivers[currentDriverIndex];
3054
+ currentDriverIndex++;
3055
+
3056
+ self._dbInfo = null;
3057
+ self._ready = null;
3058
+
3059
+ return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
3060
+ }
3061
+
3062
+ setDriverToConfig();
3063
+ var error = new Error('No available storage method found.');
3064
+ self._driverSet = Promise$1.reject(error);
3065
+ return self._driverSet;
3066
+ }
3067
+
3068
+ return driverPromiseLoop();
3069
+ };
3070
+ }
3071
+
3072
+ // There might be a driver initialization in progress
3073
+ // so wait for it to finish in order to avoid a possible
3074
+ // race condition to set _dbInfo
3075
+ var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
3076
+ return Promise$1.resolve();
3077
+ }) : Promise$1.resolve();
3078
+
3079
+ this._driverSet = oldDriverSetDone.then(function () {
3080
+ var driverName = supportedDrivers[0];
3081
+ self._dbInfo = null;
3082
+ self._ready = null;
3083
+
3084
+ return self.getDriver(driverName).then(function (driver) {
3085
+ self._driver = driver._driver;
3086
+ setDriverToConfig();
3087
+ self._wrapLibraryMethodsWithReady();
3088
+ self._initDriver = initDriver(supportedDrivers);
3089
+ });
3090
+ })["catch"](function () {
3091
+ setDriverToConfig();
3092
+ var error = new Error('No available storage method found.');
3093
+ self._driverSet = Promise$1.reject(error);
3094
+ return self._driverSet;
3095
+ });
3096
+
3097
+ executeTwoCallbacks(this._driverSet, callback, errorCallback);
3098
+ return this._driverSet;
3099
+ };
3100
+
3101
+ LocalForage.prototype.supports = function supports(driverName) {
3102
+ return !!DriverSupport[driverName];
3103
+ };
3104
+
3105
+ LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
3106
+ extend(this, libraryMethodsAndProperties);
3107
+ };
3108
+
3109
+ LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
3110
+ var supportedDrivers = [];
3111
+ for (var i = 0, len = drivers.length; i < len; i++) {
3112
+ var driverName = drivers[i];
3113
+ if (this.supports(driverName)) {
3114
+ supportedDrivers.push(driverName);
3115
+ }
3116
+ }
3117
+ return supportedDrivers;
3118
+ };
3119
+
3120
+ LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
3121
+ // Add a stub for each driver API method that delays the call to the
3122
+ // corresponding driver method until localForage is ready. These stubs
3123
+ // will be replaced by the driver methods as soon as the driver is
3124
+ // loaded, so there is no performance impact.
3125
+ for (var i = 0, len = LibraryMethods.length; i < len; i++) {
3126
+ callWhenReady(this, LibraryMethods[i]);
3127
+ }
3128
+ };
3129
+
3130
+ LocalForage.prototype.createInstance = function createInstance(options) {
3131
+ return new LocalForage(options);
3132
+ };
3133
+
3134
+ return LocalForage;
3135
+ }();
3136
+
3137
+ // The actual localForage object that we expose as a module or via a
3138
+ // global. It's extended by pulling in one of our other libraries.
3139
+
3140
+
3141
+ var localforage_js = new LocalForage();
3142
+
3143
+ module.exports = localforage_js;
3144
+
3145
+ },{"3":3}]},{},[4])(4)
3146
+ });
3147
+ });
3148
+
3149
+ var ObjectUtils;
3150
+ (function (ObjectUtils) {
325
3151
  /**
326
- * @param id
327
- * @param data
328
- * @param duration in seconds until considered expired.
3152
+ * Generates a Bruce compatible UID.
3153
+ * @returns
329
3154
  */
330
- constructor(id, data, duration) {
331
- this.Id = id;
332
- this.Data = data;
333
- this.Duration = duration;
334
- this._created = duration > -1 ? new Date() : null;
335
- }
336
- IsExpired() {
337
- if (this._created == null) {
338
- return false;
3155
+ function UId() {
3156
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
3157
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
3158
+ return v.toString(16);
3159
+ });
3160
+ }
3161
+ ObjectUtils.UId = UId;
3162
+ })(ObjectUtils || (ObjectUtils = {}));
3163
+
3164
+ class CacheDictionary {
3165
+ constructor(id) {
3166
+ this.memory = Object.create(null);
3167
+ if (!id) {
3168
+ id = "BRUCE_UI_MODELS_CACHE_DICT_" + ObjectUtils.UId();
339
3169
  }
340
- return (new Date().getTime() - this._created.getTime()) / 1000 > this.Duration;
3170
+ this.id = id;
3171
+ this.store = localforage.createInstance({
3172
+ name: id
3173
+ });
3174
+ }
3175
+ get Id() {
3176
+ return this.id;
3177
+ }
3178
+ GetItems() {
3179
+ return __awaiter(this, void 0, void 0, function* () {
3180
+ if (this.items == null) {
3181
+ const raw = yield this.store.getItem(this.id);
3182
+ if (raw == null) {
3183
+ this.items = [];
3184
+ }
3185
+ else {
3186
+ // Check if any are expired.
3187
+ // We can clean this every first time we load.
3188
+ const now = new Date().getTime();
3189
+ for (const item of raw) {
3190
+ if (item.duration > -1 && (now - item.created) / 1000 > item.duration) {
3191
+ if (item.inMemory) {
3192
+ this.memory[item.key] = null;
3193
+ delete this.memory[item.key];
3194
+ }
3195
+ else {
3196
+ yield this.store.removeItem(item.key);
3197
+ }
3198
+ }
3199
+ }
3200
+ this.items = raw;
3201
+ }
3202
+ }
3203
+ return this.items;
3204
+ });
3205
+ }
3206
+ GetKeys() {
3207
+ return __awaiter(this, void 0, void 0, function* () {
3208
+ return (yield this.GetItems()).map(x => "" + x.key);
3209
+ });
3210
+ }
3211
+ Set(key, value, duration) {
3212
+ return __awaiter(this, void 0, void 0, function* () {
3213
+ key = "" + key;
3214
+ const items = yield this.GetItems();
3215
+ const itemIndex = items.findIndex(x => x.key == key);
3216
+ if (itemIndex > -1) {
3217
+ const item = items[itemIndex];
3218
+ if (item.inMemory) {
3219
+ this.memory[item.key] = null;
3220
+ delete this.memory[item.key];
3221
+ }
3222
+ else {
3223
+ yield this.store.removeItem(item.key);
3224
+ }
3225
+ items.splice(itemIndex, 1);
3226
+ }
3227
+ const item = {
3228
+ key: key,
3229
+ duration: duration,
3230
+ created: new Date().getTime(),
3231
+ inMemory: false
3232
+ };
3233
+ // Short duration, keep in memory.
3234
+ if (duration < 60) {
3235
+ item.inMemory = true;
3236
+ this.memory[item.key] = value;
3237
+ }
3238
+ // Let's resolve and store the value in local-storage.
3239
+ // If resolution crashes then we'll keep retaining that in memory.
3240
+ else if (value instanceof Promise) {
3241
+ value.then((x) => __awaiter(this, void 0, void 0, function* () {
3242
+ try {
3243
+ const items = yield this.GetItems();
3244
+ const item = items.find(x => x.key == key);
3245
+ if (!item) {
3246
+ console.log("Item was removed from cache before promise resolved.", key, items);
3247
+ return;
3248
+ }
3249
+ try {
3250
+ yield this.store.setItem(item.key, x);
3251
+ item.inMemory = false;
3252
+ this.memory[item.key] = null;
3253
+ delete this.memory[item.key];
3254
+ yield this.store.setItem(this.id, items);
3255
+ }
3256
+ catch (e) {
3257
+ console.warn(e);
3258
+ }
3259
+ }
3260
+ catch (e) {
3261
+ console.warn(e);
3262
+ }
3263
+ }));
3264
+ item.inMemory = true;
3265
+ this.memory[item.key] = value;
3266
+ }
3267
+ if (!item.inMemory) {
3268
+ try {
3269
+ yield this.store.setItem(item.key, value);
3270
+ }
3271
+ catch (e) {
3272
+ item.inMemory = true;
3273
+ this.memory[item.key] = value;
3274
+ console.warn(e);
3275
+ }
3276
+ }
3277
+ items.push(item);
3278
+ yield this.store.setItem(this.id, items);
3279
+ this.items = items;
3280
+ });
3281
+ }
3282
+ Remove(key) {
3283
+ return __awaiter(this, void 0, void 0, function* () {
3284
+ key = "" + key;
3285
+ const items = yield this.GetItems();
3286
+ const index = items.findIndex(x => x.key == key);
3287
+ if (index >= 0) {
3288
+ const item = items[index];
3289
+ if (item.inMemory) {
3290
+ this.memory[item.key] = null;
3291
+ delete this.memory[item.key];
3292
+ }
3293
+ else {
3294
+ this.store.removeItem(item.key);
3295
+ }
3296
+ items.splice(index, 1);
3297
+ this.store.setItem(this.id, items);
3298
+ }
3299
+ this.items = items;
3300
+ });
3301
+ }
3302
+ Clear() {
3303
+ return __awaiter(this, void 0, void 0, function* () {
3304
+ const items = yield this.GetItems();
3305
+ for (const item of items) {
3306
+ if (item.inMemory) {
3307
+ this.store.removeItem(item.key);
3308
+ }
3309
+ }
3310
+ this.store.setItem(this.id, []);
3311
+ this.items = [];
3312
+ this.memory = Object.create(null);
3313
+ });
3314
+ }
3315
+ GetData(key) {
3316
+ return __awaiter(this, void 0, void 0, function* () {
3317
+ key = "" + key;
3318
+ const item = (yield this.GetItems()).find(x => x.key == key);
3319
+ const isExpired = item == null || item.duration > -1 && (new Date().getTime() - item.created) / 1000 > item.duration;
3320
+ if (isExpired) {
3321
+ this.Remove(key);
3322
+ return null;
3323
+ }
3324
+ if (item.inMemory) {
3325
+ return this.memory[item.key];
3326
+ }
3327
+ const raw = yield this.store.getItem(item.key);
3328
+ if (raw == null) {
3329
+ return null;
3330
+ }
3331
+ return raw;
3332
+ });
341
3333
  }
342
3334
  }
343
- // Milliseconds between each data cleaning.
344
- const CLEANER_INTERVAL = 5000;
345
- // Max number of items to clean in each cleaning.
346
- const MAX_CLEAN_BATCH = 100;
347
- // (Default) Max idle time to keep the cleaner alive.
348
- // Set to default API cache duration by default.
349
- const DEFAULT_MAX_CLEAN_IDLE = 60 * 5;
350
- /**
351
- * Simple local cache controller.
352
- */
353
3335
  class CacheControl {
354
- constructor() {
355
- this.data = {};
3336
+ constructor(id) {
356
3337
  this.Disabled = false;
357
- this.cleanerInterval = null;
358
- // Max idle time to keep the cleaner alive.
359
- // This value is increased when a new item is added with a larger cache duration.
360
- this.maxCleanIdle = DEFAULT_MAX_CLEAN_IDLE;
3338
+ this.data = new CacheDictionary(id);
361
3339
  }
362
3340
  /**
363
3341
  * @param id
@@ -365,121 +3343,64 @@ class CacheControl {
365
3343
  * @param duration seconds to keep the data in cache. -1 for infinite.
366
3344
  */
367
3345
  Set(id, data, duration = -1) {
368
- this.data[id + ""] = new CacheItem(id + "", data, duration);
369
- if (duration > -1) {
370
- this.startCleaning();
371
- if (this.maxCleanIdle < duration) {
372
- // Add 5 seconds to be sure cleaner stays alive to get it.
373
- this.maxCleanIdle = duration + 5;
374
- }
375
- }
3346
+ return __awaiter(this, void 0, void 0, function* () {
3347
+ return this.data.Set(id, data, duration);
3348
+ });
376
3349
  }
377
3350
  Get(id) {
378
- if (this.Disabled) {
379
- return null;
380
- }
381
- const item = this.data[id + ""];
382
- if (item == null) {
383
- return null;
384
- }
385
- if (item.IsExpired()) {
386
- delete this.data[id + ""];
387
- return null;
388
- }
389
- return item.Data;
3351
+ return __awaiter(this, void 0, void 0, function* () {
3352
+ return this.data.GetData(id);
3353
+ });
390
3354
  }
391
3355
  Clear() {
392
- this.data = {};
393
- this.stopCleaning();
3356
+ return __awaiter(this, void 0, void 0, function* () {
3357
+ return this.data.Clear();
3358
+ });
394
3359
  }
395
3360
  Remove(id) {
396
- delete this.data[id + ""];
397
- if (Object.keys(this.data).length <= 0) {
398
- this.stopCleaning();
399
- }
3361
+ return __awaiter(this, void 0, void 0, function* () {
3362
+ return this.data.Remove(id);
3363
+ });
400
3364
  }
401
3365
  RemoveByStartsWith(text) {
402
- for (const key in this.data) {
403
- if (key.startsWith(text)) {
404
- delete this.data[key];
3366
+ return __awaiter(this, void 0, void 0, function* () {
3367
+ const items = [...(yield this.data.GetItems())];
3368
+ for (const item of items) {
3369
+ if (item.key.startsWith(text)) {
3370
+ yield this.data.Remove(item.key);
3371
+ }
405
3372
  }
406
- }
407
- if (Object.keys(this.data).length <= 0) {
408
- this.stopCleaning();
409
- }
3373
+ });
410
3374
  }
411
3375
  RemoveByContains(text) {
412
- for (const key in this.data) {
413
- if (key.includes(text)) {
414
- delete this.data[key];
3376
+ return __awaiter(this, void 0, void 0, function* () {
3377
+ const items = [...(yield this.data.GetItems())];
3378
+ for (const item of items) {
3379
+ if (item.key.includes(text)) {
3380
+ yield this.data.Remove(item.key);
3381
+ }
415
3382
  }
416
- }
417
- if (Object.keys(this.data).length <= 0) {
418
- this.stopCleaning();
419
- }
3383
+ });
420
3384
  }
421
3385
  GetKeys() {
422
- if (this.Disabled) {
423
- return [];
424
- }
425
- return Object.keys(this.data);
3386
+ return __awaiter(this, void 0, void 0, function* () {
3387
+ if (this.Disabled) {
3388
+ return [];
3389
+ }
3390
+ const items = yield this.data.GetItems();
3391
+ return items.map(x => x.key);
3392
+ });
426
3393
  }
427
3394
  GetValues() {
428
- if (this.Disabled) {
429
- return [];
430
- }
431
- const values = [];
432
- for (const key in this.data) {
433
- const data = this.Get(key);
434
- if (data != null) {
435
- values.push(data);
436
- }
437
- }
438
- return values;
439
- }
440
- startCleaning() {
441
- if (this.cleanerInterval == null) {
442
- let cleanIdleStart = null;
443
- this.cleanerInterval = setInterval(() => {
444
- let cleaned = 0;
445
- for (const key in this.data) {
446
- const item = this.data[key];
447
- if (item.IsExpired()) {
448
- delete this.data[key];
449
- cleaned += 1;
450
- }
451
- if (cleaned >= MAX_CLEAN_BATCH) {
452
- break;
453
- }
454
- }
455
- if (cleaned <= 0) {
456
- // Stop cleaner if nothing in cache.
457
- if (Object.keys(this.data).length <= 0) {
458
- this.stopCleaning();
459
- }
460
- // Stop cleaner if idle time is reached.
461
- else {
462
- if (cleanIdleStart == null) {
463
- cleanIdleStart = new Date().getTime();
464
- }
465
- const now = new Date().getTime();
466
- if (now - cleanIdleStart > this.maxCleanIdle * 1000) {
467
- this.stopCleaning();
468
- }
469
- }
470
- }
471
- else {
472
- cleanIdleStart = null;
473
- }
474
- }, CLEANER_INTERVAL);
475
- }
476
- }
477
- stopCleaning() {
478
- if (this.cleanerInterval != null) {
479
- clearInterval(this.cleanerInterval);
480
- this.cleanerInterval = null;
481
- this.maxCleanIdle = DEFAULT_MAX_CLEAN_IDLE;
482
- }
3395
+ return __awaiter(this, void 0, void 0, function* () {
3396
+ if (this.Disabled) {
3397
+ return [];
3398
+ }
3399
+ const items = yield this.data.GetItems();
3400
+ const keys = items.map(x => x.key);
3401
+ const values = yield Promise.all(keys.map(key => this.data.GetData(key)));
3402
+ return values.filter(x => x != null);
3403
+ });
483
3404
  }
484
3405
  }
485
3406
 
@@ -535,8 +3456,8 @@ class AbstractApi {
535
3456
  constructor(params) {
536
3457
  this.ssid = "";
537
3458
  this.baseUrl = "";
538
- this.Cache = new CacheControl();
539
3459
  this.ssidHeader = params === null || params === void 0 ? void 0 : params.ssidHeader;
3460
+ this.Cache = new CacheControl(params === null || params === void 0 ? void 0 : params.cacheId);
540
3461
  }
541
3462
  GetBaseUrl() {
542
3463
  return this.baseUrl;
@@ -548,28 +3469,32 @@ class AbstractApi {
548
3469
  }
549
3470
  }
550
3471
  GetCacheItem(key, reqParams) {
551
- let noCache = reqParams === null || reqParams === void 0 ? void 0 : reqParams.noCache;
552
- if (noCache == null) {
553
- noCache = Api.DEFAULT_NO_CACHE;
554
- }
555
- if (noCache) {
556
- return null;
557
- }
558
- return this.Cache.Get(key);
3472
+ return __awaiter(this, void 0, void 0, function* () {
3473
+ let noCache = reqParams === null || reqParams === void 0 ? void 0 : reqParams.noCache;
3474
+ if (noCache == null) {
3475
+ noCache = Api.DEFAULT_NO_CACHE;
3476
+ }
3477
+ if (noCache) {
3478
+ return null;
3479
+ }
3480
+ return this.Cache.Get(key);
3481
+ });
559
3482
  }
560
3483
  SetCacheItem(params) {
561
- let { key, value, duration, req } = params;
562
- let noCache = req === null || req === void 0 ? void 0 : req.noCache;
563
- if (noCache == null) {
564
- noCache = Api.DEFAULT_NO_CACHE;
565
- }
566
- if (noCache) {
567
- return;
568
- }
569
- if (isNaN(duration)) {
570
- duration = Api.DEFAULT_CACHE_DURATION;
571
- }
572
- this.Cache.Set(key, value, duration);
3484
+ return __awaiter(this, void 0, void 0, function* () {
3485
+ let { key, value, duration, req } = params;
3486
+ let noCache = req === null || req === void 0 ? void 0 : req.noCache;
3487
+ if (noCache == null) {
3488
+ noCache = Api.DEFAULT_NO_CACHE;
3489
+ }
3490
+ if (noCache) {
3491
+ return;
3492
+ }
3493
+ if (isNaN(duration)) {
3494
+ duration = Api.DEFAULT_CACHE_DURATION;
3495
+ }
3496
+ yield this.Cache.Set(key, value, duration);
3497
+ });
573
3498
  }
574
3499
  GetSessionId() {
575
3500
  return this.ssid;
@@ -771,7 +3696,7 @@ var Account;
771
3696
  function Get(params) {
772
3697
  return __awaiter(this, void 0, void 0, function* () {
773
3698
  const { api, accountId: id, req: reqParams } = params;
774
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
3699
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
775
3700
  if (cacheData) {
776
3701
  return cacheData;
777
3702
  }
@@ -779,7 +3704,7 @@ var Account;
779
3704
  const resData = {
780
3705
  account: req
781
3706
  };
782
- api.SetCacheItem({
3707
+ yield api.SetCacheItem({
783
3708
  key: GetCacheKey(id),
784
3709
  value: resData,
785
3710
  req: reqParams
@@ -791,7 +3716,7 @@ var Account;
791
3716
  function GetRelatedList(params) {
792
3717
  return __awaiter(this, void 0, void 0, function* () {
793
3718
  const { api, req: reqParams } = params;
794
- const cacheData = api.GetCacheItem(GetListCacheKey(api.GetSessionId()), reqParams);
3719
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(api.GetSessionId()), reqParams);
795
3720
  if (cacheData) {
796
3721
  return cacheData;
797
3722
  }
@@ -808,7 +3733,7 @@ var Account;
808
3733
  rej(e);
809
3734
  }
810
3735
  }));
811
- api.SetCacheItem({
3736
+ yield api.SetCacheItem({
812
3737
  key: GetListCacheKey(api.GetSessionId()),
813
3738
  value: prom,
814
3739
  req: reqParams
@@ -820,7 +3745,7 @@ var Account;
820
3745
  function GetAppSettings(params) {
821
3746
  return __awaiter(this, void 0, void 0, function* () {
822
3747
  const { api, accountId: id, appId, req: reqParams } = params;
823
- const cacheData = api.GetCacheItem(GetCacheKey(id, appId), reqParams);
3748
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id, appId), reqParams);
824
3749
  if (cacheData) {
825
3750
  return cacheData;
826
3751
  }
@@ -838,7 +3763,7 @@ var Account;
838
3763
  rej(e);
839
3764
  }
840
3765
  }));
841
- api.SetCacheItem({
3766
+ yield api.SetCacheItem({
842
3767
  key: GetCacheKey(id, appId),
843
3768
  value: prom,
844
3769
  req: reqParams
@@ -856,7 +3781,7 @@ var Account;
856
3781
  return __awaiter(this, void 0, void 0, function* () {
857
3782
  const { api, accountId: id, appId, settings: data, req: reqParams } = params;
858
3783
  const res = yield api.POST(`account/${id}/applicationSettings/${appId}`, data, reqParams);
859
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Account + Api.ECacheKey.Id + id);
3784
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Account + Api.ECacheKey.Id + id);
860
3785
  return {
861
3786
  settings: res
862
3787
  };
@@ -894,7 +3819,7 @@ var Account;
894
3819
  function GetDbRegions(params) {
895
3820
  return __awaiter(this, void 0, void 0, function* () {
896
3821
  const { api, req: reqParams, key } = params;
897
- const cacheData = api.GetCacheItem(GetDbRegionListCacheKey(), reqParams);
3822
+ const cacheData = yield api.GetCacheItem(GetDbRegionListCacheKey(), reqParams);
898
3823
  if (cacheData) {
899
3824
  return cacheData;
900
3825
  }
@@ -907,7 +3832,7 @@ var Account;
907
3832
  rej(e);
908
3833
  }
909
3834
  }));
910
- api.SetCacheItem({
3835
+ yield api.SetCacheItem({
911
3836
  key: GetDbRegionListCacheKey(),
912
3837
  value: prom,
913
3838
  req: reqParams
@@ -965,7 +3890,8 @@ var CamApi;
965
3890
  class Api$$1 extends AbstractApi {
966
3891
  constructor(params) {
967
3892
  super({
968
- ssidHeader: "x-sessionid"
3893
+ ssidHeader: "x-sessionid",
3894
+ cacheId: `CAM_API_${params === null || params === void 0 ? void 0 : params.env}_`
969
3895
  });
970
3896
  this.env = (params === null || params === void 0 ? void 0 : params.env) ? params.env : Api.EEnv.PROD;
971
3897
  this.setBaseUrl();
@@ -1179,7 +4105,8 @@ var BruceApi;
1179
4105
  */
1180
4106
  constructor(params) {
1181
4107
  super({
1182
- ssidHeader: "x-sessionid"
4108
+ ssidHeader: "x-sessionid",
4109
+ cacheId: `BRUCE_API_${params === null || params === void 0 ? void 0 : params.env}_${params === null || params === void 0 ? void 0 : params.accountId}_`
1183
4110
  });
1184
4111
  this.loadCancelled = false;
1185
4112
  let { accountId, env, cam, loadRegionalBaseUrl, loadConfig } = params;
@@ -1386,7 +4313,8 @@ var IdmApi;
1386
4313
  class Api$$1 extends AbstractApi {
1387
4314
  constructor(params) {
1388
4315
  super({
1389
- ssidHeader: "SSID"
4316
+ ssidHeader: "SSID",
4317
+ cacheId: `IDM_API_${params === null || params === void 0 ? void 0 : params.env}_`
1390
4318
  });
1391
4319
  this.env = (params === null || params === void 0 ? void 0 : params.env) ? params.env : Api.EEnv.PROD;
1392
4320
  this.setBaseUrl();
@@ -1458,7 +4386,8 @@ var GlobalApi;
1458
4386
  class Api$$1 extends AbstractApi {
1459
4387
  constructor(params) {
1460
4388
  super({
1461
- ssidHeader: "x-sessionid"
4389
+ ssidHeader: "x-sessionid",
4390
+ cacheId: `GLOBAL_API_${params === null || params === void 0 ? void 0 : params.env}_`
1462
4391
  });
1463
4392
  this.env = (params === null || params === void 0 ? void 0 : params.env) ? params.env : Api.EEnv.PROD;
1464
4393
  this.setBaseUrl();
@@ -1727,21 +4656,6 @@ var Color;
1727
4656
  Color.ColorFromStr = ColorFromStr;
1728
4657
  })(Color || (Color = {}));
1729
4658
 
1730
- var ObjectUtils;
1731
- (function (ObjectUtils) {
1732
- /**
1733
- * Generates a Bruce compatible UID.
1734
- * @returns
1735
- */
1736
- function UId() {
1737
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
1738
- const r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
1739
- return v.toString(16);
1740
- });
1741
- }
1742
- ObjectUtils.UId = UId;
1743
- })(ObjectUtils || (ObjectUtils = {}));
1744
-
1745
4659
  /**
1746
4660
  * Utility to help with parsing and wrapping Bruce paths.
1747
4661
  */
@@ -1819,7 +4733,7 @@ var Entity;
1819
4733
  throw ("Entity ID is required.");
1820
4734
  }
1821
4735
  const key = GetCacheKey(entityId, expandLocation);
1822
- const cacheData = api.GetCacheItem(key, reqParams);
4736
+ const cacheData = yield api.GetCacheItem(key, reqParams);
1823
4737
  if (cacheData) {
1824
4738
  return cacheData;
1825
4739
  }
@@ -1834,7 +4748,7 @@ var Entity;
1834
4748
  rej(e);
1835
4749
  }
1836
4750
  }));
1837
- api.SetCacheItem({
4751
+ yield api.SetCacheItem({
1838
4752
  key,
1839
4753
  value: prom,
1840
4754
  req: reqParams
@@ -1854,7 +4768,7 @@ var Entity;
1854
4768
  for (let i = 0; i < entityIds.length; i++) {
1855
4769
  const entityId = entityIds[i];
1856
4770
  const key = GetCacheKey(entityId);
1857
- const cacheData = api.GetCacheItem(key, reqParams);
4771
+ const cacheData = yield api.GetCacheItem(key, reqParams);
1858
4772
  if (cacheData) {
1859
4773
  reqs.push(cacheData);
1860
4774
  }
@@ -1888,7 +4802,7 @@ var Entity;
1888
4802
  }
1889
4803
  res(null);
1890
4804
  }));
1891
- api.SetCacheItem({
4805
+ yield api.SetCacheItem({
1892
4806
  key,
1893
4807
  value: prom,
1894
4808
  req: reqParams
@@ -2101,7 +5015,7 @@ var Entity;
2101
5015
  for (let i = 0; i < entities.length; i++) {
2102
5016
  const entity = entities[i];
2103
5017
  const id = entity.Bruce.ID;
2104
- api.SetCacheItem({
5018
+ yield api.SetCacheItem({
2105
5019
  key: GetCacheKey(id),
2106
5020
  value: {
2107
5021
  entity: entity
@@ -3006,6 +5920,28 @@ var UTC;
3006
5920
  UTC.FromDate = FromDate;
3007
5921
  })(UTC || (UTC = {}));
3008
5922
 
5923
+ class LRUCache {
5924
+ constructor(capacity) {
5925
+ this.capacity = capacity;
5926
+ this.cache = new Map();
5927
+ }
5928
+ Get(key) {
5929
+ const value = this.cache.get(key);
5930
+ if (value) {
5931
+ this.cache.delete(key);
5932
+ this.cache.set(key, value);
5933
+ }
5934
+ return value;
5935
+ }
5936
+ Set(key, value) {
5937
+ if (this.cache.size >= this.capacity) {
5938
+ const leastRecentlyUsedKey = this.cache.keys().next().value;
5939
+ this.cache.delete(leastRecentlyUsedKey);
5940
+ }
5941
+ this.cache.set(key, value);
5942
+ }
5943
+ }
5944
+
3009
5945
  /**
3010
5946
  * Describes the "Entity Attachment Type" concept within Bruce.
3011
5947
  * It is a record that describes the purpose of an attachment.
@@ -3055,7 +5991,7 @@ var EntityAttachmentType;
3055
5991
  function GetList(params) {
3056
5992
  return __awaiter(this, void 0, void 0, function* () {
3057
5993
  const { api, reqParams } = params;
3058
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
5994
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
3059
5995
  if (cacheData) {
3060
5996
  return cacheData;
3061
5997
  }
@@ -3070,7 +6006,7 @@ var EntityAttachmentType;
3070
6006
  rej(e);
3071
6007
  }
3072
6008
  }));
3073
- api.SetCacheItem({
6009
+ yield api.SetCacheItem({
3074
6010
  key: GetListCacheKey(),
3075
6011
  value: req,
3076
6012
  req: reqParams
@@ -3133,7 +6069,7 @@ var EntityAttachment;
3133
6069
  for (let i = 0; i < attachments.length; i++) {
3134
6070
  api.Cache.Remove(GetCacheKey(attachments[i].ID));
3135
6071
  }
3136
- api.Cache.RemoveByStartsWith(GetListCacheKey(entityId));
6072
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey(entityId));
3137
6073
  });
3138
6074
  }
3139
6075
  EntityAttachment.UpdateOrder = UpdateOrder;
@@ -3154,7 +6090,7 @@ var EntityAttachment;
3154
6090
  if (!entityId) {
3155
6091
  throw ("Entity ID is required.");
3156
6092
  }
3157
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId), reqParams);
6093
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId), reqParams);
3158
6094
  if (cacheData) {
3159
6095
  return cacheData;
3160
6096
  }
@@ -3169,7 +6105,7 @@ var EntityAttachment;
3169
6105
  rej(e);
3170
6106
  }
3171
6107
  }));
3172
- api.SetCacheItem({
6108
+ yield api.SetCacheItem({
3173
6109
  key: GetListCacheKey(entityId),
3174
6110
  value: req,
3175
6111
  req: reqParams
@@ -3218,7 +6154,7 @@ var EntityComment;
3218
6154
  const url = `entity/${data["TargetObject.ID"]}/comment` + (data.ID == null ? "" : "/" + data.ID);
3219
6155
  const res = yield api.POST(url, data, Api.PrepReqParams(reqParams));
3220
6156
  api.Cache.Remove(GetCacheKey(data.ID));
3221
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Comment + Api.ECacheKey.Entity);
6157
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Comment + Api.ECacheKey.Entity);
3222
6158
  return {
3223
6159
  comment: res
3224
6160
  };
@@ -3233,7 +6169,7 @@ var EntityComment;
3233
6169
  }
3234
6170
  yield api.DELETE(`entity/${entityId}/comment/${commentId}`, Api.PrepReqParams(reqParams));
3235
6171
  api.Cache.Remove(GetCacheKey(commentId));
3236
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Comment + Api.ECacheKey.Entity);
6172
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Comment + Api.ECacheKey.Entity);
3237
6173
  });
3238
6174
  }
3239
6175
  EntityComment.Delete = Delete;
@@ -3243,7 +6179,7 @@ var EntityComment;
3243
6179
  if (!entityId) {
3244
6180
  throw ("Entity ID is required.");
3245
6181
  }
3246
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId), reqParams);
6182
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId), reqParams);
3247
6183
  if (cacheData) {
3248
6184
  return cacheData;
3249
6185
  }
@@ -3258,7 +6194,7 @@ var EntityComment;
3258
6194
  rej(e);
3259
6195
  }
3260
6196
  }));
3261
- api.SetCacheItem({
6197
+ yield api.SetCacheItem({
3262
6198
  key: GetListCacheKey(entityId),
3263
6199
  value: req,
3264
6200
  req: reqParams
@@ -3292,7 +6228,7 @@ var EntityLink;
3292
6228
  const url = `entity/${data["Entity.ID"]}/link` + (data.ID == null ? "" : "/" + data.ID);
3293
6229
  const res = yield api.POST(url, data, Api.PrepReqParams(reqParams));
3294
6230
  api.Cache.Remove(GetCacheKey(data.ID));
3295
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Link + Api.ECacheKey.Entity);
6231
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Link + Api.ECacheKey.Entity);
3296
6232
  return {
3297
6233
  link: res
3298
6234
  };
@@ -3307,7 +6243,7 @@ var EntityLink;
3307
6243
  }
3308
6244
  yield api.DELETE(`entity/${entityId}/link/${linkId}`, Api.PrepReqParams(reqParams));
3309
6245
  api.Cache.Remove(GetCacheKey(linkId));
3310
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Link + Api.ECacheKey.Entity);
6246
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Link + Api.ECacheKey.Entity);
3311
6247
  });
3312
6248
  }
3313
6249
  EntityLink.Delete = Delete;
@@ -3317,7 +6253,7 @@ var EntityLink;
3317
6253
  if (!entityId) {
3318
6254
  throw ("Entity ID is required.");
3319
6255
  }
3320
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId), reqParams);
6256
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId), reqParams);
3321
6257
  if (cacheData) {
3322
6258
  return cacheData;
3323
6259
  }
@@ -3332,7 +6268,7 @@ var EntityLink;
3332
6268
  rej(e);
3333
6269
  }
3334
6270
  }));
3335
- api.SetCacheItem({
6271
+ yield api.SetCacheItem({
3336
6272
  key: GetListCacheKey(entityId),
3337
6273
  value: req,
3338
6274
  req: reqParams
@@ -3389,7 +6325,7 @@ var EntityLod;
3389
6325
  if (!url) {
3390
6326
  throw ("Url is required.");
3391
6327
  }
3392
- const cacheData = api.GetCacheItem(GetCacheKey(url), reqParams);
6328
+ const cacheData = yield api.GetCacheItem(GetCacheKey(url), reqParams);
3393
6329
  if (cacheData) {
3394
6330
  return cacheData;
3395
6331
  }
@@ -3404,7 +6340,7 @@ var EntityLod;
3404
6340
  rej(e);
3405
6341
  }
3406
6342
  }));
3407
- api.SetCacheItem({
6343
+ yield api.SetCacheItem({
3408
6344
  key: GetCacheKey(url),
3409
6345
  value: req,
3410
6346
  req: reqParams
@@ -3433,7 +6369,7 @@ var EntityLod;
3433
6369
  if (!entityId) {
3434
6370
  throw ("Entity id is required.");
3435
6371
  }
3436
- const cacheData = api.GetCacheItem(GetEntityListKey(entityId), reqParams);
6372
+ const cacheData = yield api.GetCacheItem(GetEntityListKey(entityId), reqParams);
3437
6373
  if (cacheData) {
3438
6374
  return cacheData;
3439
6375
  }
@@ -3449,7 +6385,7 @@ var EntityLod;
3449
6385
  rej(e);
3450
6386
  }
3451
6387
  }));
3452
- api.SetCacheItem({
6388
+ yield api.SetCacheItem({
3453
6389
  key: GetEntityListKey(entityId),
3454
6390
  value: prom,
3455
6391
  req: reqParams
@@ -3468,7 +6404,7 @@ var EntityLod;
3468
6404
  if (!group) {
3469
6405
  group = "DEFAULT";
3470
6406
  }
3471
- const cacheData = api.GetCacheItem(GetTypeListKey(typeId, group), reqParams);
6407
+ const cacheData = yield api.GetCacheItem(GetTypeListKey(typeId, group), reqParams);
3472
6408
  if (cacheData) {
3473
6409
  return cacheData;
3474
6410
  }
@@ -3485,7 +6421,7 @@ var EntityLod;
3485
6421
  rej(e);
3486
6422
  }
3487
6423
  }));
3488
- api.SetCacheItem({
6424
+ yield api.SetCacheItem({
3489
6425
  key: GetTypeListKey(typeId, group),
3490
6426
  value: prom,
3491
6427
  req: reqParams
@@ -3541,7 +6477,7 @@ var EntityLodCategory;
3541
6477
  function GetList(params) {
3542
6478
  return __awaiter(this, void 0, void 0, function* () {
3543
6479
  const { api, req: reqParams } = params;
3544
- const cacheKey = api.GetCacheItem(GetListCacheKey(), reqParams);
6480
+ const cacheKey = yield api.GetCacheItem(GetListCacheKey(), reqParams);
3545
6481
  if (cacheKey) {
3546
6482
  return cacheKey;
3547
6483
  }
@@ -3556,7 +6492,7 @@ var EntityLodCategory;
3556
6492
  rej(e);
3557
6493
  }
3558
6494
  }));
3559
- api.SetCacheItem({
6495
+ yield api.SetCacheItem({
3560
6496
  key: GetListCacheKey(),
3561
6497
  value: req,
3562
6498
  req: reqParams
@@ -3571,7 +6507,7 @@ var EntityLodCategory;
3571
6507
  if (!id) {
3572
6508
  throw ("Lod category id is required.");
3573
6509
  }
3574
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
6510
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
3575
6511
  if (cacheData) {
3576
6512
  return cacheData;
3577
6513
  }
@@ -3586,7 +6522,7 @@ var EntityLodCategory;
3586
6522
  rej(e);
3587
6523
  }
3588
6524
  }));
3589
- api.SetCacheItem({
6525
+ yield api.SetCacheItem({
3590
6526
  key: GetCacheKey(id),
3591
6527
  value: req,
3592
6528
  req: reqParams
@@ -3645,7 +6581,7 @@ var EntityRelationType;
3645
6581
  throw ("Type ID is required.");
3646
6582
  }
3647
6583
  const key = GetCacheKey(typeId);
3648
- const cacheData = api.GetCacheItem(key, reqParams);
6584
+ const cacheData = yield api.GetCacheItem(key, reqParams);
3649
6585
  if (cacheData) {
3650
6586
  return cacheData;
3651
6587
  }
@@ -3660,7 +6596,7 @@ var EntityRelationType;
3660
6596
  rej(e);
3661
6597
  }
3662
6598
  }));
3663
- api.SetCacheItem({
6599
+ yield api.SetCacheItem({
3664
6600
  key,
3665
6601
  value: prom,
3666
6602
  req: reqParams
@@ -3684,7 +6620,7 @@ var EntityRelationType;
3684
6620
  function GetList(params) {
3685
6621
  return __awaiter(this, void 0, void 0, function* () {
3686
6622
  const { api, req: reqParams } = params;
3687
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
6623
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
3688
6624
  if (cacheData) {
3689
6625
  return cacheData;
3690
6626
  }
@@ -3699,7 +6635,7 @@ var EntityRelationType;
3699
6635
  rej(e);
3700
6636
  }
3701
6637
  }));
3702
- api.SetCacheItem({
6638
+ yield api.SetCacheItem({
3703
6639
  key: GetListCacheKey(),
3704
6640
  value: req,
3705
6641
  req: reqParams
@@ -3762,11 +6698,11 @@ var EntityRelation;
3762
6698
  };
3763
6699
  const url = `entity/${data["Principal.Entity.ID"]}/relation/${data["Relation.Type.ID"]}/add`;
3764
6700
  yield api.POST(url, reqData, Api.PrepReqParams(reqParams));
3765
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Principal.Entity.ID"]);
3766
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Related.Entity.ID"]);
3767
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.RelationType + Api.ECacheKey.Id + data["Relation.Type.ID"]);
6701
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Principal.Entity.ID"]);
6702
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Related.Entity.ID"]);
6703
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.RelationType + Api.ECacheKey.Id + data["Relation.Type.ID"]);
3768
6704
  if (data["Data.Entity.ID"]) {
3769
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Entity + Api.ECacheKey.Id + data["Data.Entity.ID"]);
6705
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Entity + Api.ECacheKey.Id + data["Data.Entity.ID"]);
3770
6706
  }
3771
6707
  });
3772
6708
  }
@@ -3782,9 +6718,9 @@ var EntityRelation;
3782
6718
  "Related.Entity.ID": [relatedEntityId]
3783
6719
  }, Api.PrepReqParams(reqParams));
3784
6720
  // Remove related cache entries
3785
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + principalEntityId);
3786
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + relatedEntityId);
3787
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.RelationType + Api.ECacheKey.Id + relationTypeId);
6721
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + principalEntityId);
6722
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + relatedEntityId);
6723
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.RelationType + Api.ECacheKey.Id + relationTypeId);
3788
6724
  });
3789
6725
  }
3790
6726
  EntityRelation.Delete = Delete;
@@ -3796,11 +6732,11 @@ var EntityRelation;
3796
6732
  }
3797
6733
  const url = `entity/${data["Principal.Entity.ID"]}/otherEntityID/${data["Related.Entity.ID"]}/relation/${data["Relation.Type.ID"]}/update`;
3798
6734
  const res = yield api.POST(url, data, Api.PrepReqParams(reqParams));
3799
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Principal.Entity.ID"]);
3800
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Related.Entity.ID"]);
3801
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.RelationType + Api.ECacheKey.Id + data["Relation.Type.ID"]);
6735
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Principal.Entity.ID"]);
6736
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Id + data["Related.Entity.ID"]);
6737
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.RelationType + Api.ECacheKey.Id + data["Relation.Type.ID"]);
3802
6738
  if (data["Data.Entity.ID"]) {
3803
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Entity + Api.ECacheKey.Id + data["Data.Entity.ID"]);
6739
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Relation + Api.ECacheKey.Entity + Api.ECacheKey.Id + data["Data.Entity.ID"]);
3804
6740
  }
3805
6741
  });
3806
6742
  }
@@ -3812,7 +6748,7 @@ var EntityRelation;
3812
6748
  throw ("Entity ID is required.");
3813
6749
  }
3814
6750
  filter = Object.assign({ relationTypeId: "", oneWayOnly: false, loadEntityData: false }, filter);
3815
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId, filter), reqParams);
6751
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId, filter), reqParams);
3816
6752
  if (cacheData) {
3817
6753
  return cacheData;
3818
6754
  }
@@ -3832,7 +6768,7 @@ var EntityRelation;
3832
6768
  rej(e);
3833
6769
  }
3834
6770
  }));
3835
- api.SetCacheItem({
6771
+ yield api.SetCacheItem({
3836
6772
  key: GetListCacheKey(entityId, filter),
3837
6773
  value: req,
3838
6774
  req: reqParams
@@ -3847,7 +6783,7 @@ var EntityRelation;
3847
6783
  if (!entityId) {
3848
6784
  throw ("Entity ID is required.");
3849
6785
  }
3850
- const cacheData = api.GetCacheItem(GetEntityCacheKey(entityId), reqParams);
6786
+ const cacheData = yield api.GetCacheItem(GetEntityCacheKey(entityId), reqParams);
3851
6787
  if (cacheData) {
3852
6788
  return cacheData;
3853
6789
  }
@@ -3862,7 +6798,7 @@ var EntityRelation;
3862
6798
  rej(e);
3863
6799
  }
3864
6800
  }));
3865
- api.SetCacheItem({
6801
+ yield api.SetCacheItem({
3866
6802
  key: GetEntityCacheKey(entityId),
3867
6803
  value: prom,
3868
6804
  req: reqParams
@@ -3913,7 +6849,7 @@ var EntitySource;
3913
6849
  const reqs = [];
3914
6850
  for (let i = 0; i < sourceKeys.length; i++) {
3915
6851
  const sourceKey = sourceKeys[i];
3916
- const cacheData = api.GetCacheItem(GetCacheKey(sourceId, sourceKey), reqParams);
6852
+ const cacheData = yield api.GetCacheItem(GetCacheKey(sourceId, sourceKey), reqParams);
3917
6853
  if (cacheData) {
3918
6854
  reqs.push(cacheData);
3919
6855
  }
@@ -3988,7 +6924,7 @@ var EntitySource;
3988
6924
  }
3989
6925
  const res = yield params.api.POST("entitysource", source);
3990
6926
  const cacheKey = GetCacheKey(source["Source.ID"], source["SourceRecord.Key"]);
3991
- params.api.Cache.Remove(cacheKey);
6927
+ yield params.api.Cache.Remove(cacheKey);
3992
6928
  return {
3993
6929
  source: res
3994
6930
  };
@@ -4042,7 +6978,7 @@ var EntityTag;
4042
6978
  const reqs = [];
4043
6979
  for (let i = 0; i < tagIds.length; i++) {
4044
6980
  const tagId = tagIds[i];
4045
- const cacheData = api.GetCacheItem(GetCacheKey(tagId), reqParams);
6981
+ const cacheData = yield api.GetCacheItem(GetCacheKey(tagId), reqParams);
4046
6982
  if (cacheData) {
4047
6983
  reqs.push(cacheData);
4048
6984
  }
@@ -4074,7 +7010,7 @@ var EntityTag;
4074
7010
  rej(e);
4075
7011
  }
4076
7012
  }));
4077
- api.SetCacheItem({
7013
+ yield api.SetCacheItem({
4078
7014
  key: GetCacheKey(id),
4079
7015
  value: req,
4080
7016
  req: reqParams
@@ -4091,7 +7027,7 @@ var EntityTag;
4091
7027
  function GetList(params) {
4092
7028
  return __awaiter(this, void 0, void 0, function* () {
4093
7029
  const { api, entityTypeId, req: reqParams } = params;
4094
- const cacheData = api.GetCacheItem(GetListCacheKey(entityTypeId), reqParams);
7030
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityTypeId), reqParams);
4095
7031
  if (cacheData) {
4096
7032
  return cacheData;
4097
7033
  }
@@ -4106,7 +7042,7 @@ var EntityTag;
4106
7042
  rej(e);
4107
7043
  }
4108
7044
  }));
4109
- api.SetCacheItem({
7045
+ yield api.SetCacheItem({
4110
7046
  key: GetListCacheKey(entityTypeId),
4111
7047
  value: req,
4112
7048
  req: reqParams
@@ -4123,7 +7059,7 @@ var EntityTag;
4123
7059
  }
4124
7060
  yield api.DELETE(`layer/${tagId}`, Api.PrepReqParams(reqParams));
4125
7061
  api.Cache.Remove(GetCacheKey(tagId));
4126
- api.Cache.RemoveByStartsWith(GetListCacheKey());
7062
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey());
4127
7063
  });
4128
7064
  }
4129
7065
  EntityTag.Delete = Delete;
@@ -4133,7 +7069,7 @@ var EntityTag;
4133
7069
  const url = data.ID ? `layer/${data.ID}` : "layer";
4134
7070
  const res = yield api.POST(url, data, Api.PrepReqParams(reqParams));
4135
7071
  api.Cache.Remove(GetCacheKey(data.ID));
4136
- api.Cache.RemoveByStartsWith(GetListCacheKey());
7072
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey());
4137
7073
  return {
4138
7074
  tag: res
4139
7075
  };
@@ -4164,7 +7100,7 @@ var EntityType;
4164
7100
  throw ("Type ID is required.");
4165
7101
  }
4166
7102
  const key = GetCacheKey(typeId);
4167
- const cacheData = api.GetCacheItem(key, reqParams);
7103
+ const cacheData = yield api.GetCacheItem(key, reqParams);
4168
7104
  if (cacheData) {
4169
7105
  return cacheData;
4170
7106
  }
@@ -4179,7 +7115,7 @@ var EntityType;
4179
7115
  rej(e);
4180
7116
  }
4181
7117
  }));
4182
- api.SetCacheItem({
7118
+ yield api.SetCacheItem({
4183
7119
  key,
4184
7120
  value: prom,
4185
7121
  req: reqParams
@@ -4203,7 +7139,7 @@ var EntityType;
4203
7139
  function GetList(params) {
4204
7140
  return __awaiter(this, void 0, void 0, function* () {
4205
7141
  const { api, req: reqParams } = params;
4206
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
7142
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
4207
7143
  if (cacheData) {
4208
7144
  return cacheData;
4209
7145
  }
@@ -4218,10 +7154,11 @@ var EntityType;
4218
7154
  rej(e);
4219
7155
  }
4220
7156
  }));
4221
- api.SetCacheItem({
7157
+ yield api.SetCacheItem({
4222
7158
  key: GetListCacheKey(),
4223
7159
  value: req,
4224
- req: reqParams
7160
+ req: reqParams,
7161
+ duration: 60 * 5 // 5 minutes.
4225
7162
  });
4226
7163
  return req;
4227
7164
  });
@@ -4663,10 +7600,7 @@ var EntityFilterGetter;
4663
7600
  sortOrder: Api.ESortOrder.Asc,
4664
7601
  entityTypeConditions: this.attrFilter
4665
7602
  },
4666
- viaCdn: this.viaCdn,
4667
- req: {
4668
- noCache: true
4669
- }
7603
+ viaCdn: this.viaCdn
4670
7604
  });
4671
7605
  const integrity = this.getIntegrityId();
4672
7606
  if (loopIntegrity == integrity && entities) {
@@ -4854,7 +7788,7 @@ var EntityCoords;
4854
7788
  function GetEntityCoords(params) {
4855
7789
  return __awaiter(this, void 0, void 0, function* () {
4856
7790
  const { api, rootEntityId: entityId, req: reqParams } = params;
4857
- const cacheData = api.GetCacheItem(GetCacheKey(entityId), reqParams);
7791
+ const cacheData = yield api.GetCacheItem(GetCacheKey(entityId), reqParams);
4858
7792
  if (cacheData) {
4859
7793
  return cacheData;
4860
7794
  }
@@ -4869,7 +7803,7 @@ var EntityCoords;
4869
7803
  rej(e);
4870
7804
  }
4871
7805
  }));
4872
- api.SetCacheItem({
7806
+ yield api.SetCacheItem({
4873
7807
  key: GetCacheKey(entityId),
4874
7808
  value: prom,
4875
7809
  req: reqParams
@@ -5112,7 +8046,7 @@ var ClientFile;
5112
8046
  throw ("File ID is required.");
5113
8047
  }
5114
8048
  const key = GetCacheKey(fileId);
5115
- const cacheData = api.GetCacheItem(key, reqParams);
8049
+ const cacheData = yield api.GetCacheItem(key, reqParams);
5116
8050
  if (cacheData) {
5117
8051
  return cacheData;
5118
8052
  }
@@ -5127,7 +8061,7 @@ var ClientFile;
5127
8061
  rej(e);
5128
8062
  }
5129
8063
  }));
5130
- api.SetCacheItem({
8064
+ yield api.SetCacheItem({
5131
8065
  key,
5132
8066
  value: prom,
5133
8067
  req: reqParams
@@ -5348,7 +8282,7 @@ var ProgramKey;
5348
8282
  throw ("Program ID is required.");
5349
8283
  }
5350
8284
  const key = GetCacheKey(programId);
5351
- const cacheData = api.GetCacheItem(key, reqParams);
8285
+ const cacheData = yield api.GetCacheItem(key, reqParams);
5352
8286
  if (cacheData) {
5353
8287
  return cacheData;
5354
8288
  }
@@ -5363,7 +8297,7 @@ var ProgramKey;
5363
8297
  rej(e);
5364
8298
  }
5365
8299
  }));
5366
- api.SetCacheItem({
8300
+ yield api.SetCacheItem({
5367
8301
  key,
5368
8302
  value: prom,
5369
8303
  req: reqParams
@@ -5375,7 +8309,7 @@ var ProgramKey;
5375
8309
  function GetList(params) {
5376
8310
  return __awaiter(this, void 0, void 0, function* () {
5377
8311
  const { api, req: reqParams } = params;
5378
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
8312
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
5379
8313
  if (cacheData) {
5380
8314
  return cacheData;
5381
8315
  }
@@ -5390,7 +8324,7 @@ var ProgramKey;
5390
8324
  rej(e);
5391
8325
  }
5392
8326
  }));
5393
- api.SetCacheItem({
8327
+ yield api.SetCacheItem({
5394
8328
  key: GetListCacheKey(),
5395
8329
  value: req,
5396
8330
  req: reqParams
@@ -5490,7 +8424,7 @@ var Tileset;
5490
8424
  if (!tilesetId) {
5491
8425
  throw ("Tileset ID is required.");
5492
8426
  }
5493
- const cacheData = api.GetCacheItem(GetCacheKey(tilesetId, loadFiles), reqParams);
8427
+ const cacheData = yield api.GetCacheItem(GetCacheKey(tilesetId, loadFiles), reqParams);
5494
8428
  if (cacheData) {
5495
8429
  return cacheData;
5496
8430
  }
@@ -5505,7 +8439,7 @@ var Tileset;
5505
8439
  rej(e);
5506
8440
  }
5507
8441
  }));
5508
- api.SetCacheItem({
8442
+ yield api.SetCacheItem({
5509
8443
  key: GetCacheKey(tilesetId, loadFiles),
5510
8444
  value: prom,
5511
8445
  req: reqParams
@@ -5548,7 +8482,7 @@ var Tileset;
5548
8482
  function GetList(params) {
5549
8483
  return __awaiter(this, void 0, void 0, function* () {
5550
8484
  const { api, req: reqParams } = params;
5551
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
8485
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
5552
8486
  if (cacheData) {
5553
8487
  return cacheData;
5554
8488
  }
@@ -5563,7 +8497,7 @@ var Tileset;
5563
8497
  rej(e);
5564
8498
  }
5565
8499
  }));
5566
- api.SetCacheItem({
8500
+ yield api.SetCacheItem({
5567
8501
  key: GetListCacheKey(),
5568
8502
  value: req,
5569
8503
  req: reqParams
@@ -5579,8 +8513,8 @@ var Tileset;
5579
8513
  throw ("Tileset ID is required.");
5580
8514
  }
5581
8515
  yield api.DELETE(`tileset/delete/${tilesetId}`, reqParams);
5582
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset + Api.ECacheKey.Id + tilesetId);
5583
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset);
8516
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset + Api.ECacheKey.Id + tilesetId);
8517
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset);
5584
8518
  });
5585
8519
  }
5586
8520
  Tileset.Delete = Delete;
@@ -5596,8 +8530,8 @@ var Tileset;
5596
8530
  data = Object.assign(Object.assign(Object.assign({}, res), data), { settings: Object.assign(Object.assign({}, res.settings), data.settings), id: res.id });
5597
8531
  }
5598
8532
  yield api.POST(`tileset/update/${data.id}`, data, Api.PrepReqParams(reqParams));
5599
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset + Api.ECacheKey.Id + data.id);
5600
- api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset);
8533
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset + Api.ECacheKey.Id + data.id);
8534
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.Tileset);
5601
8535
  return {
5602
8536
  tileset: data
5603
8537
  };
@@ -5787,7 +8721,7 @@ var Tileset;
5787
8721
  if (!accountId || !tilesetId) {
5788
8722
  throw ("Client account ID and tileset ID are required.");
5789
8723
  }
5790
- const cacheData = api.GetCacheItem(GetCacheKey(accountId, tilesetId), reqParams);
8724
+ const cacheData = yield api.GetCacheItem(GetCacheKey(accountId, tilesetId), reqParams);
5791
8725
  if (cacheData) {
5792
8726
  return cacheData;
5793
8727
  }
@@ -5802,7 +8736,7 @@ var Tileset;
5802
8736
  rej(e);
5803
8737
  }
5804
8738
  }));
5805
- api.SetCacheItem({
8739
+ yield api.SetCacheItem({
5806
8740
  key: GetCacheKey(accountId, tilesetId),
5807
8741
  value: prom,
5808
8742
  req: reqParams
@@ -5817,7 +8751,7 @@ var Tileset;
5817
8751
  if (!accountId) {
5818
8752
  throw ("Client account ID is required.");
5819
8753
  }
5820
- const cacheData = api.GetCacheItem(GetCacheKey(accountId), reqParams);
8754
+ const cacheData = yield api.GetCacheItem(GetCacheKey(accountId), reqParams);
5821
8755
  if (cacheData) {
5822
8756
  return cacheData;
5823
8757
  }
@@ -5832,7 +8766,7 @@ var Tileset;
5832
8766
  rej(e);
5833
8767
  }
5834
8768
  }));
5835
- api.SetCacheItem({
8769
+ yield api.SetCacheItem({
5836
8770
  key: GetCacheKey(accountId),
5837
8771
  value: req,
5838
8772
  req: reqParams
@@ -6010,7 +8944,7 @@ var ProjectViewBookmark;
6010
8944
  throw ("View ID and Bookmark ID are required.");
6011
8945
  }
6012
8946
  const key = GetCacheKey(viewId, bookmarkId);
6013
- const cacheData = api.GetCacheItem(key, reqParams);
8947
+ const cacheData = yield api.GetCacheItem(key, reqParams);
6014
8948
  if (cacheData) {
6015
8949
  return cacheData;
6016
8950
  }
@@ -6025,7 +8959,7 @@ var ProjectViewBookmark;
6025
8959
  rej(e);
6026
8960
  }
6027
8961
  }));
6028
- api.SetCacheItem({
8962
+ yield api.SetCacheItem({
6029
8963
  key,
6030
8964
  value: prom,
6031
8965
  req: reqParams
@@ -6052,7 +8986,7 @@ var ProjectViewBookmark;
6052
8986
  if (!viewId) {
6053
8987
  throw ("View ID is required.");
6054
8988
  }
6055
- const cacheData = api.GetCacheItem(GetListCacheKey(viewId), reqParams);
8989
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(viewId), reqParams);
6056
8990
  if (cacheData) {
6057
8991
  return cacheData;
6058
8992
  }
@@ -6070,7 +9004,7 @@ var ProjectViewBookmark;
6070
9004
  bookmark: item
6071
9005
  });
6072
9006
  });
6073
- api.SetCacheItem({
9007
+ yield api.SetCacheItem({
6074
9008
  key: GetCacheKey(viewId, item.ID),
6075
9009
  value: prom,
6076
9010
  req: reqParams
@@ -6084,7 +9018,7 @@ var ProjectViewBookmark;
6084
9018
  rej(e);
6085
9019
  }
6086
9020
  }));
6087
- api.SetCacheItem({
9021
+ yield api.SetCacheItem({
6088
9022
  key: GetListCacheKey(viewId),
6089
9023
  value: req,
6090
9024
  req: reqParams
@@ -6116,7 +9050,7 @@ var ProjectViewBookmark;
6116
9050
  "DisplayOrder.Start": 0
6117
9051
  };
6118
9052
  yield api.POST(`ui.view/${viewId}/slides/setOrder`, reqData, Api.PrepReqParams(reqParams));
6119
- api.Cache.RemoveByStartsWith(GetListCacheKey(viewId));
9053
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey(viewId));
6120
9054
  });
6121
9055
  }
6122
9056
  ProjectViewBookmark.SetOrder = SetOrder;
@@ -6155,7 +9089,7 @@ var ProjectView;
6155
9089
  throw ("View ID is required.");
6156
9090
  }
6157
9091
  const key = GetCacheKey(viewId);
6158
- const cacheData = api.GetCacheItem(key, reqParams);
9092
+ const cacheData = yield api.GetCacheItem(key, reqParams);
6159
9093
  if (cacheData) {
6160
9094
  return cacheData;
6161
9095
  }
@@ -6170,7 +9104,7 @@ var ProjectView;
6170
9104
  rej(e);
6171
9105
  }
6172
9106
  }));
6173
- api.SetCacheItem({
9107
+ yield api.SetCacheItem({
6174
9108
  key,
6175
9109
  value: prom,
6176
9110
  req: reqParams
@@ -6182,7 +9116,7 @@ var ProjectView;
6182
9116
  function GetList(params) {
6183
9117
  return __awaiter(this, void 0, void 0, function* () {
6184
9118
  const { api, req: reqParams } = params;
6185
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
9119
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
6186
9120
  if (cacheData) {
6187
9121
  return cacheData;
6188
9122
  }
@@ -6197,7 +9131,7 @@ var ProjectView;
6197
9131
  rej(e);
6198
9132
  }
6199
9133
  }));
6200
- api.SetCacheItem({
9134
+ yield api.SetCacheItem({
6201
9135
  key: GetListCacheKey(),
6202
9136
  value: prom,
6203
9137
  req: reqParams
@@ -6537,56 +9471,60 @@ var Style;
6537
9471
  EPointType["Cylinder"] = "CYLINDER";
6538
9472
  })(EPointType = Style.EPointType || (Style.EPointType = {}));
6539
9473
  function GetList(params) {
6540
- const { api, req: reqParams } = params;
6541
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
6542
- if (cacheData) {
6543
- return cacheData;
6544
- }
6545
- const res = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
6546
- try {
6547
- const data = yield api.GET("ui.entityDisplaySettings", Api.PrepReqParams(reqParams));
6548
- res({
6549
- styles: data.Items
6550
- });
6551
- }
6552
- catch (e) {
6553
- rej(e);
9474
+ return __awaiter(this, void 0, void 0, function* () {
9475
+ const { api, req: reqParams } = params;
9476
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
9477
+ if (cacheData) {
9478
+ return cacheData;
6554
9479
  }
6555
- }));
6556
- api.SetCacheItem({
6557
- key: GetListCacheKey(),
6558
- value: res,
6559
- req: reqParams
9480
+ const res = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
9481
+ try {
9482
+ const data = yield api.GET("ui.entityDisplaySettings", Api.PrepReqParams(reqParams));
9483
+ res({
9484
+ styles: data.Items
9485
+ });
9486
+ }
9487
+ catch (e) {
9488
+ rej(e);
9489
+ }
9490
+ }));
9491
+ yield api.SetCacheItem({
9492
+ key: GetListCacheKey(),
9493
+ value: res,
9494
+ req: reqParams
9495
+ });
9496
+ return res;
6560
9497
  });
6561
- return res;
6562
9498
  }
6563
9499
  Style.GetList = GetList;
6564
9500
  function Get(params) {
6565
- const { api, styleId: id, req: reqParams } = params;
6566
- if (!id) {
6567
- throw ("Style ID is required.");
6568
- }
6569
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
6570
- if (cacheData) {
6571
- return cacheData;
6572
- }
6573
- const prom = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
6574
- try {
6575
- const data = yield api.GET(`ui.entityDisplaySetting/${id}`, Api.PrepReqParams(reqParams));
6576
- res({
6577
- style: data
6578
- });
9501
+ return __awaiter(this, void 0, void 0, function* () {
9502
+ const { api, styleId: id, req: reqParams } = params;
9503
+ if (!id) {
9504
+ throw ("Style ID is required.");
6579
9505
  }
6580
- catch (e) {
6581
- rej(e);
9506
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
9507
+ if (cacheData) {
9508
+ return cacheData;
6582
9509
  }
6583
- }));
6584
- api.SetCacheItem({
6585
- key: GetCacheKey(id),
6586
- value: prom,
6587
- req: reqParams
9510
+ const prom = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
9511
+ try {
9512
+ const data = yield api.GET(`ui.entityDisplaySetting/${id}`, Api.PrepReqParams(reqParams));
9513
+ res({
9514
+ style: data
9515
+ });
9516
+ }
9517
+ catch (e) {
9518
+ rej(e);
9519
+ }
9520
+ }));
9521
+ yield api.SetCacheItem({
9522
+ key: GetCacheKey(id),
9523
+ value: prom,
9524
+ req: reqParams
9525
+ });
9526
+ return prom;
6588
9527
  });
6589
- return prom;
6590
9528
  }
6591
9529
  Style.Get = Get;
6592
9530
  function Update(params) {
@@ -6656,7 +9594,7 @@ var Session;
6656
9594
  throw ("Session ID is required.");
6657
9595
  }
6658
9596
  const key = GetCacheKey(sessionId);
6659
- const cacheData = api.GetCacheItem(key, reqParams);
9597
+ const cacheData = yield api.GetCacheItem(key, reqParams);
6660
9598
  if (cacheData) {
6661
9599
  return cacheData;
6662
9600
  }
@@ -6671,7 +9609,7 @@ var Session;
6671
9609
  rej(e);
6672
9610
  }
6673
9611
  }));
6674
- api.SetCacheItem({
9612
+ yield api.SetCacheItem({
6675
9613
  key,
6676
9614
  value: prom,
6677
9615
  req: reqParams
@@ -6888,7 +9826,7 @@ var User;
6888
9826
  if (!id) {
6889
9827
  throw ("ID is required.");
6890
9828
  }
6891
- const cacheData = api.GetCacheItem(GetCacheKey(id, accountId), reqParams);
9829
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id, accountId), reqParams);
6892
9830
  if (cacheData) {
6893
9831
  return cacheData;
6894
9832
  }
@@ -6903,7 +9841,7 @@ var User;
6903
9841
  rej(e);
6904
9842
  }
6905
9843
  }));
6906
- api.SetCacheItem({
9844
+ yield api.SetCacheItem({
6907
9845
  key: GetCacheKey(id, accountId),
6908
9846
  value: prom,
6909
9847
  req: reqParams
@@ -6935,10 +9873,10 @@ var User;
6935
9873
  const res = yield api.POST(`user/${data.ID}`, data, reqParams);
6936
9874
  api.Cache.RemoveByContains(Api.ECacheKey.User + Api.ECacheKey.Id + data.ID);
6937
9875
  if (data.Type == EType.AccessToken) {
6938
- api.Cache.RemoveByStartsWith(Api.ECacheKey.AccessToken + Api.ECacheKey.Account);
9876
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.AccessToken + Api.ECacheKey.Account);
6939
9877
  }
6940
9878
  else if (data.Type == EType.User) {
6941
- api.Cache.RemoveByStartsWith(Api.ECacheKey.User + Api.ECacheKey.Account);
9879
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.User + Api.ECacheKey.Account);
6942
9880
  }
6943
9881
  return {
6944
9882
  user: res
@@ -6957,7 +9895,7 @@ var User;
6957
9895
  if (!userId || !appId) {
6958
9896
  throw ("UserId and appId are required.");
6959
9897
  }
6960
- const cacheData = api.GetCacheItem(GetSettingsCacheKey(userId, appId), req);
9898
+ const cacheData = yield api.GetCacheItem(GetSettingsCacheKey(userId, appId), req);
6961
9899
  if (cacheData) {
6962
9900
  return cacheData;
6963
9901
  }
@@ -6983,7 +9921,7 @@ var User;
6983
9921
  rej(e);
6984
9922
  }
6985
9923
  }));
6986
- api.SetCacheItem({
9924
+ yield api.SetCacheItem({
6987
9925
  key: GetSettingsCacheKey(userId, appId),
6988
9926
  value: prom,
6989
9927
  req: req
@@ -7049,7 +9987,7 @@ var User;
7049
9987
  if (!email) {
7050
9988
  throw ("Email is required.");
7051
9989
  }
7052
- const cacheData = api.GetCacheItem(GetEmailCacheKey(email, accountId), reqParams);
9990
+ const cacheData = yield api.GetCacheItem(GetEmailCacheKey(email, accountId), reqParams);
7053
9991
  if (cacheData) {
7054
9992
  return cacheData;
7055
9993
  }
@@ -7064,7 +10002,7 @@ var User;
7064
10002
  rej(e);
7065
10003
  }
7066
10004
  }));
7067
- api.SetCacheItem({
10005
+ yield api.SetCacheItem({
7068
10006
  key: GetEmailCacheKey(email, accountId),
7069
10007
  value: prom,
7070
10008
  req: reqParams
@@ -7082,7 +10020,7 @@ var User;
7082
10020
  if (!exclusive) {
7083
10021
  exclusive = false;
7084
10022
  }
7085
- const cacheData = exclusive ? null : api.GetCacheItem(GetListCacheKey(accountId), reqParams);
10023
+ const cacheData = exclusive ? null : yield api.GetCacheItem(GetListCacheKey(accountId), reqParams);
7086
10024
  if (cacheData) {
7087
10025
  return cacheData;
7088
10026
  }
@@ -7097,10 +10035,10 @@ var User;
7097
10035
  rej(e);
7098
10036
  }
7099
10037
  }));
7100
- req.then((data) => {
10038
+ req.then((data) => __awaiter(this, void 0, void 0, function* () {
7101
10039
  const users = data.users;
7102
10040
  for (let i = 0; i < users.length; i++) {
7103
- api.SetCacheItem({
10041
+ yield api.SetCacheItem({
7104
10042
  key: GetCacheKey(users[i].ID, accountId),
7105
10043
  value: {
7106
10044
  user: users[i]
@@ -7108,9 +10046,9 @@ var User;
7108
10046
  req: reqParams
7109
10047
  });
7110
10048
  }
7111
- });
10049
+ }));
7112
10050
  if (!exclusive) {
7113
- api.SetCacheItem({
10051
+ yield api.SetCacheItem({
7114
10052
  key: GetListCacheKey(accountId),
7115
10053
  value: req,
7116
10054
  req: reqParams
@@ -7244,7 +10182,7 @@ var User;
7244
10182
  function GetList(params) {
7245
10183
  return __awaiter(this, void 0, void 0, function* () {
7246
10184
  const { api, accountId, req: reqParams } = params;
7247
- const cacheData = api.GetCacheItem(GetListCacheKey(accountId), reqParams);
10185
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(accountId), reqParams);
7248
10186
  if (cacheData) {
7249
10187
  return cacheData;
7250
10188
  }
@@ -7259,10 +10197,10 @@ var User;
7259
10197
  rej(e);
7260
10198
  }
7261
10199
  }));
7262
- req.then((data) => {
10200
+ req.then((data) => __awaiter(this, void 0, void 0, function* () {
7263
10201
  const users = data.tokens;
7264
10202
  for (let i = 0; i < users.length; i++) {
7265
- api.SetCacheItem({
10203
+ yield api.SetCacheItem({
7266
10204
  key: GetCacheKey(users[i].ID, accountId),
7267
10205
  value: {
7268
10206
  user: users[i]
@@ -7270,8 +10208,8 @@ var User;
7270
10208
  req: reqParams
7271
10209
  });
7272
10210
  }
7273
- });
7274
- api.SetCacheItem({
10211
+ }));
10212
+ yield api.SetCacheItem({
7275
10213
  key: GetListCacheKey(accountId),
7276
10214
  value: req,
7277
10215
  req: reqParams
@@ -7285,7 +10223,7 @@ var User;
7285
10223
  const { api, tokenId: id, req: reqParams } = params;
7286
10224
  yield api.DELETE(`accessToken/${id}`, reqParams);
7287
10225
  api.Cache.RemoveByContains(Api.ECacheKey.User + Api.ECacheKey.Id + id);
7288
- api.Cache.RemoveByStartsWith(Api.ECacheKey.AccessToken + Api.ECacheKey.Account);
10226
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.AccessToken + Api.ECacheKey.Account);
7289
10227
  });
7290
10228
  }
7291
10229
  AccessToken.Delete = Delete;
@@ -7302,7 +10240,7 @@ var User;
7302
10240
  data.Type = EType.AccessToken;
7303
10241
  }
7304
10242
  data = yield api.POST("accessToken", data, reqParams);
7305
- api.Cache.RemoveByStartsWith(Api.ECacheKey.AccessToken + Api.ECacheKey.Account);
10243
+ yield api.Cache.RemoveByStartsWith(Api.ECacheKey.AccessToken + Api.ECacheKey.Account);
7306
10244
  return {
7307
10245
  user: data
7308
10246
  };
@@ -7556,7 +10494,7 @@ var ImportedFile;
7556
10494
  if (!pageIndex) {
7557
10495
  pageIndex = 0;
7558
10496
  }
7559
- const cacheData = api.GetCacheItem(GetListCacheKey(type, pageIndex), reqParams);
10497
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(type, pageIndex), reqParams);
7560
10498
  if (cacheData) {
7561
10499
  return cacheData;
7562
10500
  }
@@ -7581,7 +10519,7 @@ var ImportedFile;
7581
10519
  rej(e);
7582
10520
  }
7583
10521
  }));
7584
- api.SetCacheItem({
10522
+ yield api.SetCacheItem({
7585
10523
  key: GetListCacheKey(type, pageIndex),
7586
10524
  value: prom,
7587
10525
  req: reqParams
@@ -7593,7 +10531,7 @@ var ImportedFile;
7593
10531
  function Get(params) {
7594
10532
  return __awaiter(this, void 0, void 0, function* () {
7595
10533
  const { api, importedFileId: fileId, req: reqParams } = params;
7596
- const cacheData = api.GetCacheItem(GetCacheKey(fileId), reqParams);
10534
+ const cacheData = yield api.GetCacheItem(GetCacheKey(fileId), reqParams);
7597
10535
  if (cacheData) {
7598
10536
  return cacheData;
7599
10537
  }
@@ -7608,7 +10546,7 @@ var ImportedFile;
7608
10546
  rej(e);
7609
10547
  }
7610
10548
  }));
7611
- api.SetCacheItem({
10549
+ yield api.SetCacheItem({
7612
10550
  key: GetCacheKey(fileId),
7613
10551
  value: prom,
7614
10552
  req: reqParams
@@ -7818,7 +10756,7 @@ var Plugin;
7818
10756
  if (!pluginId) {
7819
10757
  throw ("Plugin ID is required.");
7820
10758
  }
7821
- const cacheData = api.GetCacheItem(GetCacheKey(pluginId), req);
10759
+ const cacheData = yield api.GetCacheItem(GetCacheKey(pluginId), req);
7822
10760
  if (cacheData) {
7823
10761
  return cacheData;
7824
10762
  }
@@ -7833,7 +10771,7 @@ var Plugin;
7833
10771
  rej(e);
7834
10772
  }
7835
10773
  }));
7836
- api.SetCacheItem({
10774
+ yield api.SetCacheItem({
7837
10775
  key: GetCacheKey(pluginId),
7838
10776
  value: prom,
7839
10777
  req: req
@@ -7845,7 +10783,7 @@ var Plugin;
7845
10783
  function GetList(params) {
7846
10784
  return __awaiter(this, void 0, void 0, function* () {
7847
10785
  const { api, req } = params;
7848
- const cacheData = api.GetCacheItem(GetListCacheKey(), req);
10786
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), req);
7849
10787
  if (cacheData) {
7850
10788
  return cacheData;
7851
10789
  }
@@ -7860,7 +10798,7 @@ var Plugin;
7860
10798
  rej(e);
7861
10799
  }
7862
10800
  }));
7863
- api.SetCacheItem({
10801
+ yield api.SetCacheItem({
7864
10802
  key: GetListCacheKey(),
7865
10803
  value: prom,
7866
10804
  req: req
@@ -7881,5 +10819,5 @@ var Plugin;
7881
10819
  Plugin.GetLoadUrl = GetLoadUrl;
7882
10820
  })(Plugin || (Plugin = {}));
7883
10821
 
7884
- export { AnnDocument, CustomForm, CustomFormContent, AbstractApi, Api, BruceApi, CamApi, IdmApi, GlobalApi, ApiGetters, Calculator, Bounds, BruceEvent, CacheControl, Camera, Cartes, Carto, Color, DelayQueue, Geometry, UTC, BruceVariable, EntityAttachmentType, EntityAttachment, EntityComment, EntityLink, EntityLod, EntityLodCategory, EntityRelationType, EntityRelation, EntitySource, EntityTag, EntityType, Entity, EntityGlobe, EntityFilterGetter, BatchedDataGetter, EntityCoords, EntityTypeVisualSettings, EntityAttribute, ClientFile, ProgramKey, ZoomControl, MenuItem, ProjectViewBookmark, ProjectView, ProjectViewLegacyTile, ProjectViewTile, PendingAction, MessageBroker, Style, Tileset, Permission, Session, UserGroup, User, Account, EncryptUtils, MathUtils, ObjectUtils, PathUtils, UrlUtils, DataLab, ImportCad, ImportCsv, ImportJson, ImportKml, ImportedFile, Markup, Uploader, Plugin };
10822
+ export { AnnDocument, CustomForm, CustomFormContent, AbstractApi, Api, BruceApi, CamApi, IdmApi, GlobalApi, ApiGetters, Calculator, Bounds, BruceEvent, CacheControl, Camera, Cartes, Carto, Color, DelayQueue, Geometry, UTC, BruceVariable, LRUCache, EntityAttachmentType, EntityAttachment, EntityComment, EntityLink, EntityLod, EntityLodCategory, EntityRelationType, EntityRelation, EntitySource, EntityTag, EntityType, Entity, EntityGlobe, EntityFilterGetter, BatchedDataGetter, EntityCoords, EntityTypeVisualSettings, EntityAttribute, ClientFile, ProgramKey, ZoomControl, MenuItem, ProjectViewBookmark, ProjectView, ProjectViewLegacyTile, ProjectViewTile, PendingAction, MessageBroker, Style, Tileset, Permission, Session, UserGroup, User, Account, EncryptUtils, MathUtils, ObjectUtils, PathUtils, UrlUtils, DataLab, ImportCad, ImportCsv, ImportJson, ImportKml, ImportedFile, Markup, Uploader, Plugin };
7885
10823
  //# sourceMappingURL=bruce-models.es5.js.map