bruce-models 2.1.2 → 2.1.4

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.
@@ -321,2951 +321,165 @@ var CustomFormContent;
321
321
  })(EFlowDirection = CustomFormContent.EFlowDirection || (CustomFormContent.EFlowDirection = {}));
322
322
  })(CustomFormContent || (CustomFormContent = {}));
323
323
 
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
- const CACHE_VERSION_PREFIX = "v2_";
3150
- class CacheUtil {
3151
- constructor(id) {
3152
- this.store = localforage.createInstance({
3153
- name: CACHE_VERSION_PREFIX + id,
3154
- });
3155
- this.inMemoryPromises = {};
3156
- this.keyVersions = {};
3157
- }
3158
- Set(key, value, duration = 300000) {
3159
- return __awaiter(this, void 0, void 0, function* () {
3160
- if (value instanceof Promise) {
3161
- this.inMemoryPromises[key] = value;
3162
- const currentVersion = (this.keyVersions[key] = (this.keyVersions[key] || 0) + 1);
3163
- value
3164
- .then((resolvedValue) => {
3165
- if (this.keyVersions[key] === currentVersion) {
3166
- this.Set(key, resolvedValue, duration);
3167
- }
3168
- })
3169
- .catch((error) => {
3170
- if (this.keyVersions[key] === currentVersion) {
3171
- this.Set(key, error, duration);
3172
- }
3173
- })
3174
- .finally(() => {
3175
- delete this.inMemoryPromises[key];
3176
- });
3177
- }
3178
- else {
3179
- const item = {
3180
- value,
3181
- expiry: Date.now() + duration,
3182
- };
3183
- yield this.store.setItem(key, item);
3184
- }
3185
- });
3186
- }
3187
- Get(key) {
3188
- return __awaiter(this, void 0, void 0, function* () {
3189
- if (this.inMemoryPromises[key]) {
3190
- return this.inMemoryPromises[key];
3191
- }
3192
- const item = (yield this.store.getItem(key));
3193
- if (!item) {
3194
- return null;
3195
- }
3196
- if (Date.now() > item.expiry) {
3197
- yield this.store.removeItem(key);
3198
- return null;
3199
- }
3200
- return item.value;
3201
- });
3202
- }
3203
- ClearCache(pattern, mode = "equals") {
3204
- return __awaiter(this, void 0, void 0, function* () {
3205
- const keys = yield this.store.keys();
3206
- const checkFuncs = {
3207
- equals: (key) => key === pattern,
3208
- contains: (key) => key.includes(pattern),
3209
- startswith: (key) => key.startsWith(pattern),
3210
- };
3211
- const check = checkFuncs[mode];
3212
- if (!check) {
3213
- throw new Error("Invalid mode");
3214
- }
3215
- for (const key of keys) {
3216
- if (check(key)) {
3217
- yield this.store.removeItem(key);
3218
- }
3219
- }
3220
- for (const key in this.inMemoryPromises) {
3221
- if (check(key)) {
3222
- delete this.inMemoryPromises[key];
3223
- this.keyVersions[key]++;
3224
- }
3225
- }
3226
- });
324
+ class CacheItem {
325
+ /**
326
+ * @param id
327
+ * @param data
328
+ * @param duration in seconds until considered expired.
329
+ */
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;
339
+ }
340
+ return (new Date().getTime() - this._created.getTime()) / 1000 > this.Duration;
3227
341
  }
3228
342
  }
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
+ */
3229
353
  class CacheControl {
3230
354
  constructor(id) {
355
+ this.data = {};
3231
356
  this.Disabled = false;
3232
- this.data = new CacheUtil(id);
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;
3233
361
  }
3234
362
  /**
3235
363
  * @param id
3236
364
  * @param data
3237
365
  * @param duration seconds to keep the data in cache. -1 for infinite.
3238
366
  */
3239
- Set(id, data, duration = 300) {
3240
- return __awaiter(this, void 0, void 0, function* () {
3241
- const durationMs = duration === -1 ? undefined : duration * 1000;
3242
- return this.data.Set(String(id), data, durationMs);
3243
- });
367
+ 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
+ }
3244
376
  }
3245
377
  Get(id) {
3246
- return __awaiter(this, void 0, void 0, function* () {
3247
- return (yield this.data.Get(String(id)));
3248
- });
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;
3249
390
  }
3250
391
  Clear() {
3251
- return __awaiter(this, void 0, void 0, function* () {
3252
- return this.data.ClearCache("");
3253
- });
392
+ this.data = {};
393
+ this.stopCleaning();
3254
394
  }
3255
395
  Remove(id) {
3256
- return __awaiter(this, void 0, void 0, function* () {
3257
- return this.data.ClearCache(String(id), "equals");
3258
- });
396
+ delete this.data[id + ""];
397
+ if (Object.keys(this.data).length <= 0) {
398
+ this.stopCleaning();
399
+ }
3259
400
  }
3260
401
  RemoveByStartsWith(text) {
3261
- return __awaiter(this, void 0, void 0, function* () {
3262
- return this.data.ClearCache(text, "startswith");
3263
- });
402
+ for (const key in this.data) {
403
+ if (key.startsWith(text)) {
404
+ delete this.data[key];
405
+ }
406
+ }
407
+ if (Object.keys(this.data).length <= 0) {
408
+ this.stopCleaning();
409
+ }
3264
410
  }
3265
411
  RemoveByContains(text) {
3266
- return __awaiter(this, void 0, void 0, function* () {
3267
- return this.data.ClearCache(text, "contains");
3268
- });
412
+ for (const key in this.data) {
413
+ if (key.includes(text)) {
414
+ delete this.data[key];
415
+ }
416
+ }
417
+ if (Object.keys(this.data).length <= 0) {
418
+ this.stopCleaning();
419
+ }
420
+ }
421
+ GetKeys() {
422
+ if (this.Disabled) {
423
+ return [];
424
+ }
425
+ return Object.keys(this.data);
426
+ }
427
+ 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
+ }
3269
483
  }
3270
484
  }
3271
485
 
@@ -7120,7 +4334,7 @@ var EntityGlobe;
7120
4334
  constructor() {
7121
4335
  this.cells = {};
7122
4336
  }
7123
- GetCellsForView(viewRect) {
4337
+ GetCellsForView(cameraPos, viewRect) {
7124
4338
  const cells = [];
7125
4339
  const minLat = viewRect.south;
7126
4340
  const minLon = viewRect.west;
@@ -7130,31 +4344,35 @@ var EntityGlobe;
7130
4344
  const cellDegreeSize = getCellSizeFromHeight(viewRect.alt);
7131
4345
  const curMinLon = floorValueToCellSize(cellDegreeSize, minLon);
7132
4346
  const curMinLat = floorValueToCellSize(cellDegreeSize, minLat);
7133
- const width = (maxLon - curMinLon) / cellDegreeSize;
7134
- const height = (maxLat - curMinLat) / cellDegreeSize;
7135
- const centerX = (minLon + maxLon) / 2;
7136
- const centerY = (minLat + maxLat) / 2;
4347
+ let centerX = cameraPos === null || cameraPos === void 0 ? void 0 : cameraPos.longitude;
4348
+ let centerY = cameraPos === null || cameraPos === void 0 ? void 0 : cameraPos.latitude;
4349
+ if (isNaN(centerX) || isNaN(centerY)) {
4350
+ centerX = (minLon + maxLon) / 2;
4351
+ centerY = (minLat + maxLat) / 2;
4352
+ }
4353
+ const width = Math.ceil((maxLon - curMinLon) / cellDegreeSize);
4354
+ const height = Math.ceil((maxLat - curMinLat) / cellDegreeSize);
4355
+ const cellDistances = [];
7137
4356
  for (let x = 0; x < width; x++) {
7138
4357
  for (let y = 0; y < height; y++) {
7139
4358
  const lon = x * cellDegreeSize + curMinLon;
7140
4359
  const lat = y * cellDegreeSize + curMinLat;
7141
- const [id, cell] = getOrCreateCell(this.cells, cellDegreeSize, lon, lon + cellDegreeSize, lat, lat + cellDegreeSize);
7142
- cells.push(cell);
7143
- if (cells.length > MAX_CELLS) {
7144
- break;
7145
- }
4360
+ const cellCenterX = lon + cellDegreeSize / 2;
4361
+ const cellCenterY = lat + cellDegreeSize / 2;
4362
+ const dist = Math.sqrt(Math.pow(cellCenterX - centerX, 2) + Math.pow(cellCenterY - centerY, 2));
4363
+ cellDistances.push({ x, y, dist });
4364
+ }
4365
+ }
4366
+ cellDistances.sort((a, b) => a.dist - b.dist);
4367
+ for (const { x, y } of cellDistances) {
4368
+ const lon = x * cellDegreeSize + curMinLon;
4369
+ const lat = y * cellDegreeSize + curMinLat;
4370
+ const [id, cell] = getOrCreateCell(this.cells, cellDegreeSize, lon, lon + cellDegreeSize, lat, lat + cellDegreeSize);
4371
+ cells.push(cell);
4372
+ if (cells.length >= MAX_CELLS) {
4373
+ break;
7146
4374
  }
7147
4375
  }
7148
- // Sort cells so that the ones closest to the center are first
7149
- cells.sort((a, b) => {
7150
- const aCenterX = (a.Boundaries.minLongitude + a.Boundaries.maxLongitude) / 2;
7151
- const aCenterY = (a.Boundaries.minLatitude + a.Boundaries.maxLatitude) / 2;
7152
- const bCenterX = (b.Boundaries.minLongitude + b.Boundaries.maxLongitude) / 2;
7153
- const bCenterY = (b.Boundaries.minLatitude + b.Boundaries.maxLatitude) / 2;
7154
- const aDist = Math.sqrt(Math.pow(aCenterX - centerX, 2) + Math.pow(aCenterY - centerY, 2));
7155
- const bDist = Math.sqrt(Math.pow(bCenterX - centerX, 2) + Math.pow(bCenterY - centerY, 2));
7156
- return aDist - bDist;
7157
- });
7158
4376
  return cells;
7159
4377
  }
7160
4378
  }
@@ -7410,7 +4628,7 @@ var EntityFilterGetter;
7410
4628
  if (alt > MAX_HEIGHT || (alt < MIN_HEIGHT && MIN_HEIGHT > 0)) {
7411
4629
  return;
7412
4630
  }
7413
- const cells = this.cells.GetCellsForView(this.viewRect);
4631
+ const cells = this.cells.GetCellsForView(this.viewCenter, this.viewRect);
7414
4632
  (_a = this.onScanUpdate) === null || _a === void 0 ? void 0 : _a.Trigger(cells);
7415
4633
  let curCellIndex = cells.length > 0 ? 0 : null;
7416
4634
  let postedScanning = false;