UNPKG

91 kBJavaScriptView Raw
1/*!
2 localForage -- Offline Storage, Improved
3 Version 1.5.4
4 https://localforage.github.io/localForage
5 (c) 2013-2017 Mozilla, Apache License 2.0
6*/
7(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
8(function (global){
9'use strict';
10var Mutation = global.MutationObserver || global.WebKitMutationObserver;
11
12var scheduleDrain;
13
14{
15 if (Mutation) {
16 var called = 0;
17 var observer = new Mutation(nextTick);
18 var element = global.document.createTextNode('');
19 observer.observe(element, {
20 characterData: true
21 });
22 scheduleDrain = function () {
23 element.data = (called = ++called % 2);
24 };
25 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
26 var channel = new global.MessageChannel();
27 channel.port1.onmessage = nextTick;
28 scheduleDrain = function () {
29 channel.port2.postMessage(0);
30 };
31 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
32 scheduleDrain = function () {
33
34 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
35 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
36 var scriptEl = global.document.createElement('script');
37 scriptEl.onreadystatechange = function () {
38 nextTick();
39
40 scriptEl.onreadystatechange = null;
41 scriptEl.parentNode.removeChild(scriptEl);
42 scriptEl = null;
43 };
44 global.document.documentElement.appendChild(scriptEl);
45 };
46 } else {
47 scheduleDrain = function () {
48 setTimeout(nextTick, 0);
49 };
50 }
51}
52
53var draining;
54var queue = [];
55//named nextTick for less confusing stack traces
56function nextTick() {
57 draining = true;
58 var i, oldQueue;
59 var len = queue.length;
60 while (len) {
61 oldQueue = queue;
62 queue = [];
63 i = -1;
64 while (++i < len) {
65 oldQueue[i]();
66 }
67 len = queue.length;
68 }
69 draining = false;
70}
71
72module.exports = immediate;
73function immediate(task) {
74 if (queue.push(task) === 1 && !draining) {
75 scheduleDrain();
76 }
77}
78
79}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
80},{}],2:[function(_dereq_,module,exports){
81'use strict';
82var immediate = _dereq_(1);
83
84/* istanbul ignore next */
85function INTERNAL() {}
86
87var handlers = {};
88
89var REJECTED = ['REJECTED'];
90var FULFILLED = ['FULFILLED'];
91var PENDING = ['PENDING'];
92
93module.exports = exports = Promise;
94
95function Promise(resolver) {
96 if (typeof resolver !== 'function') {
97 throw new TypeError('resolver must be a function');
98 }
99 this.state = PENDING;
100 this.queue = [];
101 this.outcome = void 0;
102 if (resolver !== INTERNAL) {
103 safelyResolveThenable(this, resolver);
104 }
105}
106
107Promise.prototype["catch"] = function (onRejected) {
108 return this.then(null, onRejected);
109};
110Promise.prototype.then = function (onFulfilled, onRejected) {
111 if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
112 typeof onRejected !== 'function' && this.state === REJECTED) {
113 return this;
114 }
115 var promise = new this.constructor(INTERNAL);
116 if (this.state !== PENDING) {
117 var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
118 unwrap(promise, resolver, this.outcome);
119 } else {
120 this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
121 }
122
123 return promise;
124};
125function QueueItem(promise, onFulfilled, onRejected) {
126 this.promise = promise;
127 if (typeof onFulfilled === 'function') {
128 this.onFulfilled = onFulfilled;
129 this.callFulfilled = this.otherCallFulfilled;
130 }
131 if (typeof onRejected === 'function') {
132 this.onRejected = onRejected;
133 this.callRejected = this.otherCallRejected;
134 }
135}
136QueueItem.prototype.callFulfilled = function (value) {
137 handlers.resolve(this.promise, value);
138};
139QueueItem.prototype.otherCallFulfilled = function (value) {
140 unwrap(this.promise, this.onFulfilled, value);
141};
142QueueItem.prototype.callRejected = function (value) {
143 handlers.reject(this.promise, value);
144};
145QueueItem.prototype.otherCallRejected = function (value) {
146 unwrap(this.promise, this.onRejected, value);
147};
148
149function unwrap(promise, func, value) {
150 immediate(function () {
151 var returnValue;
152 try {
153 returnValue = func(value);
154 } catch (e) {
155 return handlers.reject(promise, e);
156 }
157 if (returnValue === promise) {
158 handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
159 } else {
160 handlers.resolve(promise, returnValue);
161 }
162 });
163}
164
165handlers.resolve = function (self, value) {
166 var result = tryCatch(getThen, value);
167 if (result.status === 'error') {
168 return handlers.reject(self, result.value);
169 }
170 var thenable = result.value;
171
172 if (thenable) {
173 safelyResolveThenable(self, thenable);
174 } else {
175 self.state = FULFILLED;
176 self.outcome = value;
177 var i = -1;
178 var len = self.queue.length;
179 while (++i < len) {
180 self.queue[i].callFulfilled(value);
181 }
182 }
183 return self;
184};
185handlers.reject = function (self, error) {
186 self.state = REJECTED;
187 self.outcome = error;
188 var i = -1;
189 var len = self.queue.length;
190 while (++i < len) {
191 self.queue[i].callRejected(error);
192 }
193 return self;
194};
195
196function getThen(obj) {
197 // Make sure we only access the accessor once as required by the spec
198 var then = obj && obj.then;
199 if (obj && typeof obj === 'object' && typeof then === 'function') {
200 return function appyThen() {
201 then.apply(obj, arguments);
202 };
203 }
204}
205
206function safelyResolveThenable(self, thenable) {
207 // Either fulfill, reject or reject with error
208 var called = false;
209 function onError(value) {
210 if (called) {
211 return;
212 }
213 called = true;
214 handlers.reject(self, value);
215 }
216
217 function onSuccess(value) {
218 if (called) {
219 return;
220 }
221 called = true;
222 handlers.resolve(self, value);
223 }
224
225 function tryToUnwrap() {
226 thenable(onSuccess, onError);
227 }
228
229 var result = tryCatch(tryToUnwrap);
230 if (result.status === 'error') {
231 onError(result.value);
232 }
233}
234
235function tryCatch(func, value) {
236 var out = {};
237 try {
238 out.value = func(value);
239 out.status = 'success';
240 } catch (e) {
241 out.status = 'error';
242 out.value = e;
243 }
244 return out;
245}
246
247exports.resolve = resolve;
248function resolve(value) {
249 if (value instanceof this) {
250 return value;
251 }
252 return handlers.resolve(new this(INTERNAL), value);
253}
254
255exports.reject = reject;
256function reject(reason) {
257 var promise = new this(INTERNAL);
258 return handlers.reject(promise, reason);
259}
260
261exports.all = all;
262function all(iterable) {
263 var self = this;
264 if (Object.prototype.toString.call(iterable) !== '[object Array]') {
265 return this.reject(new TypeError('must be an array'));
266 }
267
268 var len = iterable.length;
269 var called = false;
270 if (!len) {
271 return this.resolve([]);
272 }
273
274 var values = new Array(len);
275 var resolved = 0;
276 var i = -1;
277 var promise = new this(INTERNAL);
278
279 while (++i < len) {
280 allResolver(iterable[i], i);
281 }
282 return promise;
283 function allResolver(value, i) {
284 self.resolve(value).then(resolveFromAll, function (error) {
285 if (!called) {
286 called = true;
287 handlers.reject(promise, error);
288 }
289 });
290 function resolveFromAll(outValue) {
291 values[i] = outValue;
292 if (++resolved === len && !called) {
293 called = true;
294 handlers.resolve(promise, values);
295 }
296 }
297 }
298}
299
300exports.race = race;
301function race(iterable) {
302 var self = this;
303 if (Object.prototype.toString.call(iterable) !== '[object Array]') {
304 return this.reject(new TypeError('must be an array'));
305 }
306
307 var len = iterable.length;
308 var called = false;
309 if (!len) {
310 return this.resolve([]);
311 }
312
313 var i = -1;
314 var promise = new this(INTERNAL);
315
316 while (++i < len) {
317 resolver(iterable[i]);
318 }
319 return promise;
320 function resolver(value) {
321 self.resolve(value).then(function (response) {
322 if (!called) {
323 called = true;
324 handlers.resolve(promise, response);
325 }
326 }, function (error) {
327 if (!called) {
328 called = true;
329 handlers.reject(promise, error);
330 }
331 });
332 }
333}
334
335},{"1":1}],3:[function(_dereq_,module,exports){
336(function (global){
337'use strict';
338if (typeof global.Promise !== 'function') {
339 global.Promise = _dereq_(2);
340}
341
342}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
343},{"2":2}],4:[function(_dereq_,module,exports){
344'use strict';
345
346var _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; };
347
348function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
349
350function getIDB() {
351 /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
352 try {
353 if (typeof indexedDB !== 'undefined') {
354 return indexedDB;
355 }
356 if (typeof webkitIndexedDB !== 'undefined') {
357 return webkitIndexedDB;
358 }
359 if (typeof mozIndexedDB !== 'undefined') {
360 return mozIndexedDB;
361 }
362 if (typeof OIndexedDB !== 'undefined') {
363 return OIndexedDB;
364 }
365 if (typeof msIndexedDB !== 'undefined') {
366 return msIndexedDB;
367 }
368 } catch (e) {
369 return;
370 }
371}
372
373var idb = getIDB();
374
375function isIndexedDBValid() {
376 try {
377 // Initialize IndexedDB; fall back to vendor-prefixed versions
378 // if needed.
379 if (!idb) {
380 return false;
381 }
382 // We mimic PouchDB here;
383 //
384 // We test for openDatabase because IE Mobile identifies itself
385 // as Safari. Oh the lulz...
386 var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
387
388 var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
389
390 // Safari <10.1 does not meet our requirements for IDB support (#5572)
391 // since Safari 10.1 shipped with fetch, we can use that to detect it
392 return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
393 // some outdated implementations of IDB that appear on Samsung
394 // and HTC Android devices <4.4 are missing IDBKeyRange
395 // See: https://github.com/mozilla/localForage/issues/128
396 // See: https://github.com/mozilla/localForage/issues/272
397 typeof IDBKeyRange !== 'undefined';
398 } catch (e) {
399 return false;
400 }
401}
402
403// Abstracts constructing a Blob object, so it also works in older
404// browsers that don't support the native Blob constructor. (i.e.
405// old QtWebKit versions, at least).
406// Abstracts constructing a Blob object, so it also works in older
407// browsers that don't support the native Blob constructor. (i.e.
408// old QtWebKit versions, at least).
409function createBlob(parts, properties) {
410 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
411 parts = parts || [];
412 properties = properties || {};
413 try {
414 return new Blob(parts, properties);
415 } catch (e) {
416 if (e.name !== 'TypeError') {
417 throw e;
418 }
419 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
420 var builder = new Builder();
421 for (var i = 0; i < parts.length; i += 1) {
422 builder.append(parts[i]);
423 }
424 return builder.getBlob(properties.type);
425 }
426}
427
428// This is CommonJS because lie is an external dependency, so Rollup
429// can just ignore it.
430if (typeof Promise === 'undefined') {
431 // In the "nopromises" build this will just throw if you don't have
432 // a global promise object, but it would throw anyway later.
433 _dereq_(3);
434}
435var Promise$1 = Promise;
436
437function executeCallback(promise, callback) {
438 if (callback) {
439 promise.then(function (result) {
440 callback(null, result);
441 }, function (error) {
442 callback(error);
443 });
444 }
445}
446
447function executeTwoCallbacks(promise, callback, errorCallback) {
448 if (typeof callback === 'function') {
449 promise.then(callback);
450 }
451
452 if (typeof errorCallback === 'function') {
453 promise["catch"](errorCallback);
454 }
455}
456
457function normalizeKey(key) {
458 // Cast the key to a string, as that's all we can set as a key.
459 if (typeof key !== 'string') {
460 console.warn(key + ' used as a key, but it is not a string.');
461 key = String(key);
462 }
463
464 return key;
465}
466
467function getCallback() {
468 if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
469 return arguments[arguments.length - 1];
470 }
471}
472
473// Some code originally from async_storage.js in
474// [Gaia](https://github.com/mozilla-b2g/gaia).
475
476var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
477var supportsBlobs;
478var dbContexts;
479var toString = Object.prototype.toString;
480
481// Transaction Modes
482var READ_ONLY = 'readonly';
483var READ_WRITE = 'readwrite';
484
485// Transform a binary string to an array buffer, because otherwise
486// weird stuff happens when you try to work with the binary string directly.
487// It is known.
488// From http://stackoverflow.com/questions/14967647/ (continues on next line)
489// encode-decode-image-with-base64-breaks-image (2013-04-21)
490function _binStringToArrayBuffer(bin) {
491 var length = bin.length;
492 var buf = new ArrayBuffer(length);
493 var arr = new Uint8Array(buf);
494 for (var i = 0; i < length; i++) {
495 arr[i] = bin.charCodeAt(i);
496 }
497 return buf;
498}
499
500//
501// Blobs are not supported in all versions of IndexedDB, notably
502// Chrome <37 and Android <5. In those versions, storing a blob will throw.
503//
504// Various other blob bugs exist in Chrome v37-42 (inclusive).
505// Detecting them is expensive and confusing to users, and Chrome 37-42
506// is at very low usage worldwide, so we do a hacky userAgent check instead.
507//
508// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
509// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
510// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
511//
512// Code borrowed from PouchDB. See:
513// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
514//
515function _checkBlobSupportWithoutCaching(idb) {
516 return new Promise$1(function (resolve) {
517 var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
518 var blob = createBlob(['']);
519 txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
520
521 txn.onabort = function (e) {
522 // If the transaction aborts now its due to not being able to
523 // write to the database, likely due to the disk being full
524 e.preventDefault();
525 e.stopPropagation();
526 resolve(false);
527 };
528
529 txn.oncomplete = function () {
530 var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
531 var matchedEdge = navigator.userAgent.match(/Edge\//);
532 // MS Edge pretends to be Chrome 42:
533 // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
534 resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
535 };
536 })["catch"](function () {
537 return false; // error, so assume unsupported
538 });
539}
540
541function _checkBlobSupport(idb) {
542 if (typeof supportsBlobs === 'boolean') {
543 return Promise$1.resolve(supportsBlobs);
544 }
545 return _checkBlobSupportWithoutCaching(idb).then(function (value) {
546 supportsBlobs = value;
547 return supportsBlobs;
548 });
549}
550
551function _deferReadiness(dbInfo) {
552 var dbContext = dbContexts[dbInfo.name];
553
554 // Create a deferred object representing the current database operation.
555 var deferredOperation = {};
556
557 deferredOperation.promise = new Promise$1(function (resolve, reject) {
558 deferredOperation.resolve = resolve;
559 deferredOperation.reject = reject;
560 });
561
562 // Enqueue the deferred operation.
563 dbContext.deferredOperations.push(deferredOperation);
564
565 // Chain its promise to the database readiness.
566 if (!dbContext.dbReady) {
567 dbContext.dbReady = deferredOperation.promise;
568 } else {
569 dbContext.dbReady = dbContext.dbReady.then(function () {
570 return deferredOperation.promise;
571 });
572 }
573}
574
575function _advanceReadiness(dbInfo) {
576 var dbContext = dbContexts[dbInfo.name];
577
578 // Dequeue a deferred operation.
579 var deferredOperation = dbContext.deferredOperations.pop();
580
581 // Resolve its promise (which is part of the database readiness
582 // chain of promises).
583 if (deferredOperation) {
584 deferredOperation.resolve();
585 return deferredOperation.promise;
586 }
587}
588
589function _rejectReadiness(dbInfo, err) {
590 var dbContext = dbContexts[dbInfo.name];
591
592 // Dequeue a deferred operation.
593 var deferredOperation = dbContext.deferredOperations.pop();
594
595 // Reject its promise (which is part of the database readiness
596 // chain of promises).
597 if (deferredOperation) {
598 deferredOperation.reject(err);
599 return deferredOperation.promise;
600 }
601}
602
603function _getConnection(dbInfo, upgradeNeeded) {
604 return new Promise$1(function (resolve, reject) {
605
606 if (dbInfo.db) {
607 if (upgradeNeeded) {
608 _deferReadiness(dbInfo);
609 dbInfo.db.close();
610 } else {
611 return resolve(dbInfo.db);
612 }
613 }
614
615 var dbArgs = [dbInfo.name];
616
617 if (upgradeNeeded) {
618 dbArgs.push(dbInfo.version);
619 }
620
621 var openreq = idb.open.apply(idb, dbArgs);
622
623 if (upgradeNeeded) {
624 openreq.onupgradeneeded = function (e) {
625 var db = openreq.result;
626 try {
627 db.createObjectStore(dbInfo.storeName);
628 if (e.oldVersion <= 1) {
629 // Added when support for blob shims was added
630 db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
631 }
632 } catch (ex) {
633 if (ex.name === 'ConstraintError') {
634 console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
635 } else {
636 throw ex;
637 }
638 }
639 };
640 }
641
642 openreq.onerror = function (e) {
643 e.preventDefault();
644 reject(openreq.error);
645 };
646
647 openreq.onsuccess = function () {
648 resolve(openreq.result);
649 _advanceReadiness(dbInfo);
650 };
651 });
652}
653
654function _getOriginalConnection(dbInfo) {
655 return _getConnection(dbInfo, false);
656}
657
658function _getUpgradedConnection(dbInfo) {
659 return _getConnection(dbInfo, true);
660}
661
662function _isUpgradeNeeded(dbInfo, defaultVersion) {
663 if (!dbInfo.db) {
664 return true;
665 }
666
667 var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
668 var isDowngrade = dbInfo.version < dbInfo.db.version;
669 var isUpgrade = dbInfo.version > dbInfo.db.version;
670
671 if (isDowngrade) {
672 // If the version is not the default one
673 // then warn for impossible downgrade.
674 if (dbInfo.version !== defaultVersion) {
675 console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
676 }
677 // Align the versions to prevent errors.
678 dbInfo.version = dbInfo.db.version;
679 }
680
681 if (isUpgrade || isNewStore) {
682 // If the store is new then increment the version (if needed).
683 // This will trigger an "upgradeneeded" event which is required
684 // for creating a store.
685 if (isNewStore) {
686 var incVersion = dbInfo.db.version + 1;
687 if (incVersion > dbInfo.version) {
688 dbInfo.version = incVersion;
689 }
690 }
691
692 return true;
693 }
694
695 return false;
696}
697
698// encode a blob for indexeddb engines that don't support blobs
699function _encodeBlob(blob) {
700 return new Promise$1(function (resolve, reject) {
701 var reader = new FileReader();
702 reader.onerror = reject;
703 reader.onloadend = function (e) {
704 var base64 = btoa(e.target.result || '');
705 resolve({
706 __local_forage_encoded_blob: true,
707 data: base64,
708 type: blob.type
709 });
710 };
711 reader.readAsBinaryString(blob);
712 });
713}
714
715// decode an encoded blob
716function _decodeBlob(encodedBlob) {
717 var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
718 return createBlob([arrayBuff], { type: encodedBlob.type });
719}
720
721// is this one of our fancy encoded blobs?
722function _isEncodedBlob(value) {
723 return value && value.__local_forage_encoded_blob;
724}
725
726// Specialize the default `ready()` function by making it dependent
727// on the current database operations. Thus, the driver will be actually
728// ready when it's been initialized (default) *and* there are no pending
729// operations on the database (initiated by some other instances).
730function _fullyReady(callback) {
731 var self = this;
732
733 var promise = self._initReady().then(function () {
734 var dbContext = dbContexts[self._dbInfo.name];
735
736 if (dbContext && dbContext.dbReady) {
737 return dbContext.dbReady;
738 }
739 });
740
741 executeTwoCallbacks(promise, callback, callback);
742 return promise;
743}
744
745// Try to establish a new db connection to replace the
746// current one which is broken (i.e. experiencing
747// InvalidStateError while creating a transaction).
748function _tryReconnect(dbInfo) {
749 _deferReadiness(dbInfo);
750
751 var dbContext = dbContexts[dbInfo.name];
752 var forages = dbContext.forages;
753
754 for (var i = 0; i < forages.length; i++) {
755 var forage = forages[i];
756 if (forage._dbInfo.db) {
757 forage._dbInfo.db.close();
758 forage._dbInfo.db = null;
759 }
760 }
761
762 return _getOriginalConnection(dbInfo).then(function (db) {
763 for (var j = 0; j < forages.length; j++) {
764 forages[j]._dbInfo.db = db;
765 }
766 dbInfo.db = db;
767 }).then(function () {
768 if (_isUpgradeNeeded(dbInfo)) {
769 // Reopen the database for upgrading.
770 return _getUpgradedConnection(dbInfo);
771 }
772 })["catch"](function (err) {
773 _rejectReadiness(dbInfo, err);
774 throw err;
775 });
776}
777
778// FF doesn't like Promises (micro-tasks) and IDDB store operations,
779// so we have to do it with callbacks
780function createTransaction(dbInfo, mode, callback, retries) {
781 if (retries === undefined) {
782 retries = 1;
783 }
784
785 try {
786 var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
787 callback(null, tx);
788 } catch (err) {
789 if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
790
791 return Promise$1.resolve().then(function () {
792 if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
793 // increase the db version, to create the new ObjectStore
794 if (dbInfo.db) {
795 dbInfo.version = dbInfo.db.version + 1;
796 }
797 // Reopen the database for upgrading.
798 return _getUpgradedConnection(dbInfo);
799 }
800 }).then(function () {
801 return _tryReconnect(dbInfo).then(function () {
802 createTransaction(dbInfo, mode, callback, retries - 1);
803 });
804 })["catch"](callback);
805 }
806
807 callback(err);
808 }
809}
810
811// Open the IndexedDB database (automatically creates one if one didn't
812// previously exist), using any options set in the config.
813function _initStorage(options) {
814 var self = this;
815 var dbInfo = {
816 db: null
817 };
818
819 if (options) {
820 for (var i in options) {
821 dbInfo[i] = options[i];
822 }
823 }
824
825 // Initialize a singleton container for all running localForages.
826 if (!dbContexts) {
827 dbContexts = {};
828 }
829
830 // Get the current context of the database;
831 var dbContext = dbContexts[dbInfo.name];
832
833 // ...or create a new context.
834 if (!dbContext) {
835 dbContext = {
836 // Running localForages sharing a database.
837 forages: [],
838 // Shared database.
839 db: null,
840 // Database readiness (promise).
841 dbReady: null,
842 // Deferred operations on the database.
843 deferredOperations: []
844 };
845 // Register the new context in the global container.
846 dbContexts[dbInfo.name] = dbContext;
847 }
848
849 // Register itself as a running localForage in the current context.
850 dbContext.forages.push(self);
851
852 // Replace the default `ready()` function with the specialized one.
853 if (!self._initReady) {
854 self._initReady = self.ready;
855 self.ready = _fullyReady;
856 }
857
858 // Create an array of initialization states of the related localForages.
859 var initPromises = [];
860
861 function ignoreErrors() {
862 // Don't handle errors here,
863 // just makes sure related localForages aren't pending.
864 return Promise$1.resolve();
865 }
866
867 for (var j = 0; j < dbContext.forages.length; j++) {
868 var forage = dbContext.forages[j];
869 if (forage !== self) {
870 // Don't wait for itself...
871 initPromises.push(forage._initReady()["catch"](ignoreErrors));
872 }
873 }
874
875 // Take a snapshot of the related localForages.
876 var forages = dbContext.forages.slice(0);
877
878 // Initialize the connection process only when
879 // all the related localForages aren't pending.
880 return Promise$1.all(initPromises).then(function () {
881 dbInfo.db = dbContext.db;
882 // Get the connection or open a new one without upgrade.
883 return _getOriginalConnection(dbInfo);
884 }).then(function (db) {
885 dbInfo.db = db;
886 if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
887 // Reopen the database for upgrading.
888 return _getUpgradedConnection(dbInfo);
889 }
890 return db;
891 }).then(function (db) {
892 dbInfo.db = dbContext.db = db;
893 self._dbInfo = dbInfo;
894 // Share the final connection amongst related localForages.
895 for (var k = 0; k < forages.length; k++) {
896 var forage = forages[k];
897 if (forage !== self) {
898 // Self is already up-to-date.
899 forage._dbInfo.db = dbInfo.db;
900 forage._dbInfo.version = dbInfo.version;
901 }
902 }
903 });
904}
905
906function getItem(key, callback) {
907 var self = this;
908
909 key = normalizeKey(key);
910
911 var promise = new Promise$1(function (resolve, reject) {
912 self.ready().then(function () {
913 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
914 if (err) {
915 return reject(err);
916 }
917
918 try {
919 var store = transaction.objectStore(self._dbInfo.storeName);
920 var req = store.get(key);
921
922 req.onsuccess = function () {
923 var value = req.result;
924 if (value === undefined) {
925 value = null;
926 }
927 if (_isEncodedBlob(value)) {
928 value = _decodeBlob(value);
929 }
930 resolve(value);
931 };
932
933 req.onerror = function () {
934 reject(req.error);
935 };
936 } catch (e) {
937 reject(e);
938 }
939 });
940 })["catch"](reject);
941 });
942
943 executeCallback(promise, callback);
944 return promise;
945}
946
947// Iterate over all items stored in database.
948function iterate(iterator, callback) {
949 var self = this;
950
951 var promise = new Promise$1(function (resolve, reject) {
952 self.ready().then(function () {
953 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
954 if (err) {
955 return reject(err);
956 }
957
958 try {
959 var store = transaction.objectStore(self._dbInfo.storeName);
960 var req = store.openCursor();
961 var iterationNumber = 1;
962
963 req.onsuccess = function () {
964 var cursor = req.result;
965
966 if (cursor) {
967 var value = cursor.value;
968 if (_isEncodedBlob(value)) {
969 value = _decodeBlob(value);
970 }
971 var result = iterator(value, cursor.key, iterationNumber++);
972
973 // when the iterator callback retuns any
974 // (non-`undefined`) value, then we stop
975 // the iteration immediately
976 if (result !== void 0) {
977 resolve(result);
978 } else {
979 cursor["continue"]();
980 }
981 } else {
982 resolve();
983 }
984 };
985
986 req.onerror = function () {
987 reject(req.error);
988 };
989 } catch (e) {
990 reject(e);
991 }
992 });
993 })["catch"](reject);
994 });
995
996 executeCallback(promise, callback);
997
998 return promise;
999}
1000
1001function setItem(key, value, callback) {
1002 var self = this;
1003
1004 key = normalizeKey(key);
1005
1006 var promise = new Promise$1(function (resolve, reject) {
1007 var dbInfo;
1008 self.ready().then(function () {
1009 dbInfo = self._dbInfo;
1010 if (toString.call(value) === '[object Blob]') {
1011 return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
1012 if (blobSupport) {
1013 return value;
1014 }
1015 return _encodeBlob(value);
1016 });
1017 }
1018 return value;
1019 }).then(function (value) {
1020 createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1021 if (err) {
1022 return reject(err);
1023 }
1024
1025 try {
1026 var store = transaction.objectStore(self._dbInfo.storeName);
1027
1028 // The reason we don't _save_ null is because IE 10 does
1029 // not support saving the `null` type in IndexedDB. How
1030 // ironic, given the bug below!
1031 // See: https://github.com/mozilla/localForage/issues/161
1032 if (value === null) {
1033 value = undefined;
1034 }
1035
1036 var req = store.put(value, key);
1037
1038 transaction.oncomplete = function () {
1039 // Cast to undefined so the value passed to
1040 // callback/promise is the same as what one would get out
1041 // of `getItem()` later. This leads to some weirdness
1042 // (setItem('foo', undefined) will return `null`), but
1043 // it's not my fault localStorage is our baseline and that
1044 // it's weird.
1045 if (value === undefined) {
1046 value = null;
1047 }
1048
1049 resolve(value);
1050 };
1051 transaction.onabort = transaction.onerror = function () {
1052 var err = req.error ? req.error : req.transaction.error;
1053 reject(err);
1054 };
1055 } catch (e) {
1056 reject(e);
1057 }
1058 });
1059 })["catch"](reject);
1060 });
1061
1062 executeCallback(promise, callback);
1063 return promise;
1064}
1065
1066function removeItem(key, callback) {
1067 var self = this;
1068
1069 key = normalizeKey(key);
1070
1071 var promise = new Promise$1(function (resolve, reject) {
1072 self.ready().then(function () {
1073 createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1074 if (err) {
1075 return reject(err);
1076 }
1077
1078 try {
1079 var store = transaction.objectStore(self._dbInfo.storeName);
1080 // We use a Grunt task to make this safe for IE and some
1081 // versions of Android (including those used by Cordova).
1082 // Normally IE won't like `.delete()` and will insist on
1083 // using `['delete']()`, but we have a build step that
1084 // fixes this for us now.
1085 var req = store["delete"](key);
1086 transaction.oncomplete = function () {
1087 resolve();
1088 };
1089
1090 transaction.onerror = function () {
1091 reject(req.error);
1092 };
1093
1094 // The request will be also be aborted if we've exceeded our storage
1095 // space.
1096 transaction.onabort = function () {
1097 var err = req.error ? req.error : req.transaction.error;
1098 reject(err);
1099 };
1100 } catch (e) {
1101 reject(e);
1102 }
1103 });
1104 })["catch"](reject);
1105 });
1106
1107 executeCallback(promise, callback);
1108 return promise;
1109}
1110
1111function clear(callback) {
1112 var self = this;
1113
1114 var promise = new Promise$1(function (resolve, reject) {
1115 self.ready().then(function () {
1116 createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1117 if (err) {
1118 return reject(err);
1119 }
1120
1121 try {
1122 var store = transaction.objectStore(self._dbInfo.storeName);
1123 var req = store.clear();
1124
1125 transaction.oncomplete = function () {
1126 resolve();
1127 };
1128
1129 transaction.onabort = transaction.onerror = function () {
1130 var err = req.error ? req.error : req.transaction.error;
1131 reject(err);
1132 };
1133 } catch (e) {
1134 reject(e);
1135 }
1136 });
1137 })["catch"](reject);
1138 });
1139
1140 executeCallback(promise, callback);
1141 return promise;
1142}
1143
1144function length(callback) {
1145 var self = this;
1146
1147 var promise = new Promise$1(function (resolve, reject) {
1148 self.ready().then(function () {
1149 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1150 if (err) {
1151 return reject(err);
1152 }
1153
1154 try {
1155 var store = transaction.objectStore(self._dbInfo.storeName);
1156 var req = store.count();
1157
1158 req.onsuccess = function () {
1159 resolve(req.result);
1160 };
1161
1162 req.onerror = function () {
1163 reject(req.error);
1164 };
1165 } catch (e) {
1166 reject(e);
1167 }
1168 });
1169 })["catch"](reject);
1170 });
1171
1172 executeCallback(promise, callback);
1173 return promise;
1174}
1175
1176function key(n, callback) {
1177 var self = this;
1178
1179 var promise = new Promise$1(function (resolve, reject) {
1180 if (n < 0) {
1181 resolve(null);
1182
1183 return;
1184 }
1185
1186 self.ready().then(function () {
1187 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1188 if (err) {
1189 return reject(err);
1190 }
1191
1192 try {
1193 var store = transaction.objectStore(self._dbInfo.storeName);
1194 var advanced = false;
1195 var req = store.openCursor();
1196
1197 req.onsuccess = function () {
1198 var cursor = req.result;
1199 if (!cursor) {
1200 // this means there weren't enough keys
1201 resolve(null);
1202
1203 return;
1204 }
1205
1206 if (n === 0) {
1207 // We have the first key, return it if that's what they
1208 // wanted.
1209 resolve(cursor.key);
1210 } else {
1211 if (!advanced) {
1212 // Otherwise, ask the cursor to skip ahead n
1213 // records.
1214 advanced = true;
1215 cursor.advance(n);
1216 } else {
1217 // When we get here, we've got the nth key.
1218 resolve(cursor.key);
1219 }
1220 }
1221 };
1222
1223 req.onerror = function () {
1224 reject(req.error);
1225 };
1226 } catch (e) {
1227 reject(e);
1228 }
1229 });
1230 })["catch"](reject);
1231 });
1232
1233 executeCallback(promise, callback);
1234 return promise;
1235}
1236
1237function keys(callback) {
1238 var self = this;
1239
1240 var promise = new Promise$1(function (resolve, reject) {
1241 self.ready().then(function () {
1242 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1243 if (err) {
1244 return reject(err);
1245 }
1246
1247 try {
1248 var store = transaction.objectStore(self._dbInfo.storeName);
1249 var req = store.openCursor();
1250 var keys = [];
1251
1252 req.onsuccess = function () {
1253 var cursor = req.result;
1254
1255 if (!cursor) {
1256 resolve(keys);
1257 return;
1258 }
1259
1260 keys.push(cursor.key);
1261 cursor["continue"]();
1262 };
1263
1264 req.onerror = function () {
1265 reject(req.error);
1266 };
1267 } catch (e) {
1268 reject(e);
1269 }
1270 });
1271 })["catch"](reject);
1272 });
1273
1274 executeCallback(promise, callback);
1275 return promise;
1276}
1277
1278function dropInstance(options, callback) {
1279 callback = getCallback.apply(this, arguments);
1280
1281 var currentConfig = this.config();
1282 options = typeof options !== 'function' && options || {};
1283 if (!options.name) {
1284 options.name = options.name || currentConfig.name;
1285 options.storeName = options.storeName || currentConfig.storeName;
1286 }
1287
1288 var self = this;
1289 var promise;
1290 if (!options.name) {
1291 promise = Promise$1.reject('Invalid arguments');
1292 } else {
1293 var dbPromise = options.name === currentConfig.name && self._dbInfo.db ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options);
1294
1295 if (!options.storeName) {
1296 promise = dbPromise.then(function () {
1297
1298 _deferReadiness(options);
1299
1300 var dbContext = dbContexts[options.name];
1301 var forages = dbContext.forages;
1302
1303 for (var i = 0; i < forages.length; i++) {
1304 var forage = forages[i];
1305 if (forage._dbInfo.db) {
1306 forage._dbInfo.db.close();
1307 forage._dbInfo.db = null;
1308 }
1309 }
1310
1311 var dropDBPromise = new Promise$1(function (resolve, reject) {
1312 var req = idb.deleteDatabase(options.name);
1313
1314 req.onerror = req.onblocked = reject;
1315
1316 req.onsuccess = resolve;
1317 });
1318
1319 return dropDBPromise.then(function () {
1320 for (var j = 0; j < forages.length; j++) {
1321 _advanceReadiness(forage._dbInfo);
1322 }
1323 })["catch"](function (err) {
1324 (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1325 throw err;
1326 });
1327 });
1328 } else {
1329 promise = dbPromise.then(function (db) {
1330 if (!db.objectStoreNames.contains(options.storeName)) {
1331 return;
1332 }
1333
1334 var newVersion = db.version + 1;
1335
1336 _deferReadiness(options);
1337
1338 var dbContext = dbContexts[options.name];
1339 var forages = dbContext.forages;
1340
1341 for (var i = 0; i < forages.length; i++) {
1342 var forage = forages[i];
1343 if (forage._dbInfo.db) {
1344 forage._dbInfo.db.close();
1345 forage._dbInfo.db = null;
1346 forage._dbInfo.version = newVersion;
1347 }
1348 }
1349
1350 var dropObjectPromise = new Promise$1(function (resolve, reject) {
1351 var req = idb.open(options.name, newVersion);
1352
1353 req.onerror = reject;
1354
1355 req.onupgradeneeded = function () {
1356 var db = req.result;
1357 db.deleteObjectStore(options.storeName);
1358 };
1359
1360 req.onsuccess = function () {
1361 var db = req.result;
1362 resolve(db);
1363 };
1364 });
1365
1366 return dropObjectPromise.then(function (db) {
1367 for (var j = 0; j < forages.length; j++) {
1368 var forage = forages[j];
1369 forage._dbInfo.db = db;
1370 _advanceReadiness(forage._dbInfo);
1371 }
1372 })["catch"](function (err) {
1373 (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1374 throw err;
1375 });
1376 });
1377 }
1378 }
1379
1380 executeCallback(promise, callback);
1381 return promise;
1382}
1383
1384var asyncStorage = {
1385 _driver: 'asyncStorage',
1386 _initStorage: _initStorage,
1387 _support: isIndexedDBValid(),
1388 iterate: iterate,
1389 getItem: getItem,
1390 setItem: setItem,
1391 removeItem: removeItem,
1392 clear: clear,
1393 length: length,
1394 key: key,
1395 keys: keys,
1396 dropInstance: dropInstance
1397};
1398
1399function isWebSQLValid() {
1400 return typeof openDatabase === 'function';
1401}
1402
1403// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
1404// it to Base64, so this is how we store it to prevent very strange errors with less
1405// verbose ways of binary <-> string data storage.
1406var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1407
1408var BLOB_TYPE_PREFIX = '~~local_forage_type~';
1409var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
1410
1411var SERIALIZED_MARKER = '__lfsc__:';
1412var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
1413
1414// OMG the serializations!
1415var TYPE_ARRAYBUFFER = 'arbf';
1416var TYPE_BLOB = 'blob';
1417var TYPE_INT8ARRAY = 'si08';
1418var TYPE_UINT8ARRAY = 'ui08';
1419var TYPE_UINT8CLAMPEDARRAY = 'uic8';
1420var TYPE_INT16ARRAY = 'si16';
1421var TYPE_INT32ARRAY = 'si32';
1422var TYPE_UINT16ARRAY = 'ur16';
1423var TYPE_UINT32ARRAY = 'ui32';
1424var TYPE_FLOAT32ARRAY = 'fl32';
1425var TYPE_FLOAT64ARRAY = 'fl64';
1426var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
1427
1428var toString$1 = Object.prototype.toString;
1429
1430function stringToBuffer(serializedString) {
1431 // Fill the string into a ArrayBuffer.
1432 var bufferLength = serializedString.length * 0.75;
1433 var len = serializedString.length;
1434 var i;
1435 var p = 0;
1436 var encoded1, encoded2, encoded3, encoded4;
1437
1438 if (serializedString[serializedString.length - 1] === '=') {
1439 bufferLength--;
1440 if (serializedString[serializedString.length - 2] === '=') {
1441 bufferLength--;
1442 }
1443 }
1444
1445 var buffer = new ArrayBuffer(bufferLength);
1446 var bytes = new Uint8Array(buffer);
1447
1448 for (i = 0; i < len; i += 4) {
1449 encoded1 = BASE_CHARS.indexOf(serializedString[i]);
1450 encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
1451 encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
1452 encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
1453
1454 /*jslint bitwise: true */
1455 bytes[p++] = encoded1 << 2 | encoded2 >> 4;
1456 bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
1457 bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
1458 }
1459 return buffer;
1460}
1461
1462// Converts a buffer to a string to store, serialized, in the backend
1463// storage library.
1464function bufferToString(buffer) {
1465 // base64-arraybuffer
1466 var bytes = new Uint8Array(buffer);
1467 var base64String = '';
1468 var i;
1469
1470 for (i = 0; i < bytes.length; i += 3) {
1471 /*jslint bitwise: true */
1472 base64String += BASE_CHARS[bytes[i] >> 2];
1473 base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
1474 base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
1475 base64String += BASE_CHARS[bytes[i + 2] & 63];
1476 }
1477
1478 if (bytes.length % 3 === 2) {
1479 base64String = base64String.substring(0, base64String.length - 1) + '=';
1480 } else if (bytes.length % 3 === 1) {
1481 base64String = base64String.substring(0, base64String.length - 2) + '==';
1482 }
1483
1484 return base64String;
1485}
1486
1487// Serialize a value, afterwards executing a callback (which usually
1488// instructs the `setItem()` callback/promise to be executed). This is how
1489// we store binary data with localStorage.
1490function serialize(value, callback) {
1491 var valueType = '';
1492 if (value) {
1493 valueType = toString$1.call(value);
1494 }
1495
1496 // Cannot use `value instanceof ArrayBuffer` or such here, as these
1497 // checks fail when running the tests using casper.js...
1498 //
1499 // TODO: See why those tests fail and use a better solution.
1500 if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
1501 // Convert binary arrays to a string and prefix the string with
1502 // a special marker.
1503 var buffer;
1504 var marker = SERIALIZED_MARKER;
1505
1506 if (value instanceof ArrayBuffer) {
1507 buffer = value;
1508 marker += TYPE_ARRAYBUFFER;
1509 } else {
1510 buffer = value.buffer;
1511
1512 if (valueType === '[object Int8Array]') {
1513 marker += TYPE_INT8ARRAY;
1514 } else if (valueType === '[object Uint8Array]') {
1515 marker += TYPE_UINT8ARRAY;
1516 } else if (valueType === '[object Uint8ClampedArray]') {
1517 marker += TYPE_UINT8CLAMPEDARRAY;
1518 } else if (valueType === '[object Int16Array]') {
1519 marker += TYPE_INT16ARRAY;
1520 } else if (valueType === '[object Uint16Array]') {
1521 marker += TYPE_UINT16ARRAY;
1522 } else if (valueType === '[object Int32Array]') {
1523 marker += TYPE_INT32ARRAY;
1524 } else if (valueType === '[object Uint32Array]') {
1525 marker += TYPE_UINT32ARRAY;
1526 } else if (valueType === '[object Float32Array]') {
1527 marker += TYPE_FLOAT32ARRAY;
1528 } else if (valueType === '[object Float64Array]') {
1529 marker += TYPE_FLOAT64ARRAY;
1530 } else {
1531 callback(new Error('Failed to get type for BinaryArray'));
1532 }
1533 }
1534
1535 callback(marker + bufferToString(buffer));
1536 } else if (valueType === '[object Blob]') {
1537 // Conver the blob to a binaryArray and then to a string.
1538 var fileReader = new FileReader();
1539
1540 fileReader.onload = function () {
1541 // Backwards-compatible prefix for the blob type.
1542 var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
1543
1544 callback(SERIALIZED_MARKER + TYPE_BLOB + str);
1545 };
1546
1547 fileReader.readAsArrayBuffer(value);
1548 } else {
1549 try {
1550 callback(JSON.stringify(value));
1551 } catch (e) {
1552 console.error("Couldn't convert value into a JSON string: ", value);
1553
1554 callback(null, e);
1555 }
1556 }
1557}
1558
1559// Deserialize data we've inserted into a value column/field. We place
1560// special markers into our strings to mark them as encoded; this isn't
1561// as nice as a meta field, but it's the only sane thing we can do whilst
1562// keeping localStorage support intact.
1563//
1564// Oftentimes this will just deserialize JSON content, but if we have a
1565// special marker (SERIALIZED_MARKER, defined above), we will extract
1566// some kind of arraybuffer/binary data/typed array out of the string.
1567function deserialize(value) {
1568 // If we haven't marked this string as being specially serialized (i.e.
1569 // something other than serialized JSON), we can just return it and be
1570 // done with it.
1571 if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
1572 return JSON.parse(value);
1573 }
1574
1575 // The following code deals with deserializing some kind of Blob or
1576 // TypedArray. First we separate out the type of data we're dealing
1577 // with from the data itself.
1578 var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
1579 var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
1580
1581 var blobType;
1582 // Backwards-compatible blob type serialization strategy.
1583 // DBs created with older versions of localForage will simply not have the blob type.
1584 if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
1585 var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
1586 blobType = matcher[1];
1587 serializedString = serializedString.substring(matcher[0].length);
1588 }
1589 var buffer = stringToBuffer(serializedString);
1590
1591 // Return the right type based on the code/type set during
1592 // serialization.
1593 switch (type) {
1594 case TYPE_ARRAYBUFFER:
1595 return buffer;
1596 case TYPE_BLOB:
1597 return createBlob([buffer], { type: blobType });
1598 case TYPE_INT8ARRAY:
1599 return new Int8Array(buffer);
1600 case TYPE_UINT8ARRAY:
1601 return new Uint8Array(buffer);
1602 case TYPE_UINT8CLAMPEDARRAY:
1603 return new Uint8ClampedArray(buffer);
1604 case TYPE_INT16ARRAY:
1605 return new Int16Array(buffer);
1606 case TYPE_UINT16ARRAY:
1607 return new Uint16Array(buffer);
1608 case TYPE_INT32ARRAY:
1609 return new Int32Array(buffer);
1610 case TYPE_UINT32ARRAY:
1611 return new Uint32Array(buffer);
1612 case TYPE_FLOAT32ARRAY:
1613 return new Float32Array(buffer);
1614 case TYPE_FLOAT64ARRAY:
1615 return new Float64Array(buffer);
1616 default:
1617 throw new Error('Unkown type: ' + type);
1618 }
1619}
1620
1621var localforageSerializer = {
1622 serialize: serialize,
1623 deserialize: deserialize,
1624 stringToBuffer: stringToBuffer,
1625 bufferToString: bufferToString
1626};
1627
1628/*
1629 * Includes code from:
1630 *
1631 * base64-arraybuffer
1632 * https://github.com/niklasvh/base64-arraybuffer
1633 *
1634 * Copyright (c) 2012 Niklas von Hertzen
1635 * Licensed under the MIT license.
1636 */
1637
1638function createDbTable(t, dbInfo, callback, errorCallback) {
1639 t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
1640}
1641
1642// Open the WebSQL database (automatically creates one if one didn't
1643// previously exist), using any options set in the config.
1644function _initStorage$1(options) {
1645 var self = this;
1646 var dbInfo = {
1647 db: null
1648 };
1649
1650 if (options) {
1651 for (var i in options) {
1652 dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
1653 }
1654 }
1655
1656 var dbInfoPromise = new Promise$1(function (resolve, reject) {
1657 // Open the database; the openDatabase API will automatically
1658 // create it for us if it doesn't exist.
1659 try {
1660 dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
1661 } catch (e) {
1662 return reject(e);
1663 }
1664
1665 // Create our key/value table if it doesn't exist.
1666 dbInfo.db.transaction(function (t) {
1667 createDbTable(t, dbInfo, function () {
1668 self._dbInfo = dbInfo;
1669 resolve();
1670 }, function (t, error) {
1671 reject(error);
1672 });
1673 }, reject);
1674 });
1675
1676 dbInfo.serializer = localforageSerializer;
1677 return dbInfoPromise;
1678}
1679
1680function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
1681 t.executeSql(sqlStatement, args, callback, function (t, error) {
1682 if (error.code === error.SYNTAX_ERR) {
1683 t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [name], function (t, results) {
1684 if (!results.rows.length) {
1685 // if the table is missing (was deleted)
1686 // re-create it table and retry
1687 createDbTable(t, dbInfo, function () {
1688 t.executeSql(sqlStatement, args, callback, errorCallback);
1689 }, errorCallback);
1690 } else {
1691 errorCallback(t, error);
1692 }
1693 }, errorCallback);
1694 } else {
1695 errorCallback(t, error);
1696 }
1697 }, errorCallback);
1698}
1699
1700function getItem$1(key, callback) {
1701 var self = this;
1702
1703 key = normalizeKey(key);
1704
1705 var promise = new Promise$1(function (resolve, reject) {
1706 self.ready().then(function () {
1707 var dbInfo = self._dbInfo;
1708 dbInfo.db.transaction(function (t) {
1709 tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
1710 var result = results.rows.length ? results.rows.item(0).value : null;
1711
1712 // Check to see if this is serialized content we need to
1713 // unpack.
1714 if (result) {
1715 result = dbInfo.serializer.deserialize(result);
1716 }
1717
1718 resolve(result);
1719 }, function (t, error) {
1720
1721 reject(error);
1722 });
1723 });
1724 })["catch"](reject);
1725 });
1726
1727 executeCallback(promise, callback);
1728 return promise;
1729}
1730
1731function iterate$1(iterator, callback) {
1732 var self = this;
1733
1734 var promise = new Promise$1(function (resolve, reject) {
1735 self.ready().then(function () {
1736 var dbInfo = self._dbInfo;
1737
1738 dbInfo.db.transaction(function (t) {
1739 tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
1740 var rows = results.rows;
1741 var length = rows.length;
1742
1743 for (var i = 0; i < length; i++) {
1744 var item = rows.item(i);
1745 var result = item.value;
1746
1747 // Check to see if this is serialized content
1748 // we need to unpack.
1749 if (result) {
1750 result = dbInfo.serializer.deserialize(result);
1751 }
1752
1753 result = iterator(result, item.key, i + 1);
1754
1755 // void(0) prevents problems with redefinition
1756 // of `undefined`.
1757 if (result !== void 0) {
1758 resolve(result);
1759 return;
1760 }
1761 }
1762
1763 resolve();
1764 }, function (t, error) {
1765 reject(error);
1766 });
1767 });
1768 })["catch"](reject);
1769 });
1770
1771 executeCallback(promise, callback);
1772 return promise;
1773}
1774
1775function _setItem(key, value, callback, retriesLeft) {
1776 var self = this;
1777
1778 key = normalizeKey(key);
1779
1780 var promise = new Promise$1(function (resolve, reject) {
1781 self.ready().then(function () {
1782 // The localStorage API doesn't return undefined values in an
1783 // "expected" way, so undefined is always cast to null in all
1784 // drivers. See: https://github.com/mozilla/localForage/pull/42
1785 if (value === undefined) {
1786 value = null;
1787 }
1788
1789 // Save the original value to pass to the callback.
1790 var originalValue = value;
1791
1792 var dbInfo = self._dbInfo;
1793 dbInfo.serializer.serialize(value, function (value, error) {
1794 if (error) {
1795 reject(error);
1796 } else {
1797 dbInfo.db.transaction(function (t) {
1798 tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
1799 resolve(originalValue);
1800 }, function (t, error) {
1801 reject(error);
1802 });
1803 }, function (sqlError) {
1804 // The transaction failed; check
1805 // to see if it's a quota error.
1806 if (sqlError.code === sqlError.QUOTA_ERR) {
1807 // We reject the callback outright for now, but
1808 // it's worth trying to re-run the transaction.
1809 // Even if the user accepts the prompt to use
1810 // more storage on Safari, this error will
1811 // be called.
1812 //
1813 // Try to re-run the transaction.
1814 if (retriesLeft > 0) {
1815 resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
1816 return;
1817 }
1818 reject(sqlError);
1819 }
1820 });
1821 }
1822 });
1823 })["catch"](reject);
1824 });
1825
1826 executeCallback(promise, callback);
1827 return promise;
1828}
1829
1830function setItem$1(key, value, callback) {
1831 return _setItem.apply(this, [key, value, callback, 1]);
1832}
1833
1834function removeItem$1(key, callback) {
1835 var self = this;
1836
1837 key = normalizeKey(key);
1838
1839 var promise = new Promise$1(function (resolve, reject) {
1840 self.ready().then(function () {
1841 var dbInfo = self._dbInfo;
1842 dbInfo.db.transaction(function (t) {
1843 tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
1844 resolve();
1845 }, function (t, error) {
1846 reject(error);
1847 });
1848 });
1849 })["catch"](reject);
1850 });
1851
1852 executeCallback(promise, callback);
1853 return promise;
1854}
1855
1856// Deletes every item in the table.
1857// TODO: Find out if this resets the AUTO_INCREMENT number.
1858function clear$1(callback) {
1859 var self = this;
1860
1861 var promise = new Promise$1(function (resolve, reject) {
1862 self.ready().then(function () {
1863 var dbInfo = self._dbInfo;
1864 dbInfo.db.transaction(function (t) {
1865 tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
1866 resolve();
1867 }, function (t, error) {
1868 reject(error);
1869 });
1870 });
1871 })["catch"](reject);
1872 });
1873
1874 executeCallback(promise, callback);
1875 return promise;
1876}
1877
1878// Does a simple `COUNT(key)` to get the number of items stored in
1879// localForage.
1880function length$1(callback) {
1881 var self = this;
1882
1883 var promise = new Promise$1(function (resolve, reject) {
1884 self.ready().then(function () {
1885 var dbInfo = self._dbInfo;
1886 dbInfo.db.transaction(function (t) {
1887 // Ahhh, SQL makes this one soooooo easy.
1888 tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
1889 var result = results.rows.item(0).c;
1890 resolve(result);
1891 }, function (t, error) {
1892 reject(error);
1893 });
1894 });
1895 })["catch"](reject);
1896 });
1897
1898 executeCallback(promise, callback);
1899 return promise;
1900}
1901
1902// Return the key located at key index X; essentially gets the key from a
1903// `WHERE id = ?`. This is the most efficient way I can think to implement
1904// this rarely-used (in my experience) part of the API, but it can seem
1905// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
1906// the ID of each key will change every time it's updated. Perhaps a stored
1907// procedure for the `setItem()` SQL would solve this problem?
1908// TODO: Don't change ID on `setItem()`.
1909function key$1(n, callback) {
1910 var self = this;
1911
1912 var promise = new Promise$1(function (resolve, reject) {
1913 self.ready().then(function () {
1914 var dbInfo = self._dbInfo;
1915 dbInfo.db.transaction(function (t) {
1916 tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
1917 var result = results.rows.length ? results.rows.item(0).key : null;
1918 resolve(result);
1919 }, function (t, error) {
1920 reject(error);
1921 });
1922 });
1923 })["catch"](reject);
1924 });
1925
1926 executeCallback(promise, callback);
1927 return promise;
1928}
1929
1930function keys$1(callback) {
1931 var self = this;
1932
1933 var promise = new Promise$1(function (resolve, reject) {
1934 self.ready().then(function () {
1935 var dbInfo = self._dbInfo;
1936 dbInfo.db.transaction(function (t) {
1937 tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
1938 var keys = [];
1939
1940 for (var i = 0; i < results.rows.length; i++) {
1941 keys.push(results.rows.item(i).key);
1942 }
1943
1944 resolve(keys);
1945 }, function (t, error) {
1946 reject(error);
1947 });
1948 });
1949 })["catch"](reject);
1950 });
1951
1952 executeCallback(promise, callback);
1953 return promise;
1954}
1955
1956// https://www.w3.org/TR/webdatabase/#databases
1957// > There is no way to enumerate or delete the databases available for an origin from this API.
1958function getAllStoreNames(db) {
1959 return new Promise$1(function (resolve, reject) {
1960 db.transaction(function (t) {
1961 t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
1962 var storeNames = [];
1963
1964 for (var i = 0; i < results.rows.length; i++) {
1965 storeNames.push(results.rows.item(i).name);
1966 }
1967
1968 resolve({
1969 db: db,
1970 storeNames: storeNames
1971 });
1972 }, function (t, error) {
1973 reject(error);
1974 });
1975 }, function (sqlError) {
1976 reject(sqlError);
1977 });
1978 });
1979}
1980
1981function dropInstance$1(options, callback) {
1982 callback = getCallback.apply(this, arguments);
1983
1984 var currentConfig = this.config();
1985 options = typeof options !== 'function' && options || {};
1986 if (!options.name) {
1987 options.name = options.name || currentConfig.name;
1988 options.storeName = options.storeName || currentConfig.storeName;
1989 }
1990
1991 var self = this;
1992 var promise;
1993 if (!options.name) {
1994 promise = Promise$1.reject('Invalid arguments');
1995 } else {
1996 promise = new Promise$1(function (resolve) {
1997 var db;
1998 if (options.name === currentConfig.name) {
1999 // use the db reference of the current instance
2000 db = self._dbInfo.db;
2001 } else {
2002 db = openDatabase(options.name, '', '', 0);
2003 }
2004
2005 if (!options.storeName) {
2006 // drop all database tables
2007 resolve(getAllStoreNames(db));
2008 } else {
2009 resolve({
2010 db: db,
2011 storeNames: [options.storeName]
2012 });
2013 }
2014 }).then(function (operationInfo) {
2015 return new Promise$1(function (resolve, reject) {
2016 operationInfo.db.transaction(function (t) {
2017 function dropTable(storeName) {
2018 return new Promise$1(function (resolve, reject) {
2019 t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
2020 resolve();
2021 }, function (t, error) {
2022 reject(error);
2023 });
2024 });
2025 }
2026
2027 var operations = [];
2028 for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
2029 operations.push(dropTable(operationInfo.storeNames[i]));
2030 }
2031
2032 Promise$1.all(operations).then(function () {
2033 resolve();
2034 })["catch"](function (e) {
2035 reject(e);
2036 });
2037 }, function (sqlError) {
2038 reject(sqlError);
2039 });
2040 });
2041 });
2042 }
2043
2044 executeCallback(promise, callback);
2045 return promise;
2046}
2047
2048var webSQLStorage = {
2049 _driver: 'webSQLStorage',
2050 _initStorage: _initStorage$1,
2051 _support: isWebSQLValid(),
2052 iterate: iterate$1,
2053 getItem: getItem$1,
2054 setItem: setItem$1,
2055 removeItem: removeItem$1,
2056 clear: clear$1,
2057 length: length$1,
2058 key: key$1,
2059 keys: keys$1,
2060 dropInstance: dropInstance$1
2061};
2062
2063function isLocalStorageValid() {
2064 try {
2065 return typeof localStorage !== 'undefined' && 'setItem' in localStorage && typeof localStorage.setItem === 'function';
2066 } catch (e) {
2067 return false;
2068 }
2069}
2070
2071function _getKeyPrefix(options, defaultConfig) {
2072 var keyPrefix = options.name + '/';
2073
2074 if (options.storeName !== defaultConfig.storeName) {
2075 keyPrefix += options.storeName + '/';
2076 }
2077 return keyPrefix;
2078}
2079
2080// Check if localStorage throws when saving an item
2081function checkIfLocalStorageThrows() {
2082 var localStorageTestKey = '_localforage_support_test';
2083
2084 try {
2085 localStorage.setItem(localStorageTestKey, true);
2086 localStorage.removeItem(localStorageTestKey);
2087
2088 return false;
2089 } catch (e) {
2090 return true;
2091 }
2092}
2093
2094// Check if localStorage is usable and allows to save an item
2095// This method checks if localStorage is usable in Safari Private Browsing
2096// mode, or in any other case where the available quota for localStorage
2097// is 0 and there wasn't any saved items yet.
2098function _isLocalStorageUsable() {
2099 return !checkIfLocalStorageThrows() || localStorage.length > 0;
2100}
2101
2102// Config the localStorage backend, using options set in the config.
2103function _initStorage$2(options) {
2104 var self = this;
2105 var dbInfo = {};
2106 if (options) {
2107 for (var i in options) {
2108 dbInfo[i] = options[i];
2109 }
2110 }
2111
2112 dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
2113
2114 if (!_isLocalStorageUsable()) {
2115 return Promise$1.reject();
2116 }
2117
2118 self._dbInfo = dbInfo;
2119 dbInfo.serializer = localforageSerializer;
2120
2121 return Promise$1.resolve();
2122}
2123
2124// Remove all keys from the datastore, effectively destroying all data in
2125// the app's key/value store!
2126function clear$2(callback) {
2127 var self = this;
2128 var promise = self.ready().then(function () {
2129 var keyPrefix = self._dbInfo.keyPrefix;
2130
2131 for (var i = localStorage.length - 1; i >= 0; i--) {
2132 var key = localStorage.key(i);
2133
2134 if (key.indexOf(keyPrefix) === 0) {
2135 localStorage.removeItem(key);
2136 }
2137 }
2138 });
2139
2140 executeCallback(promise, callback);
2141 return promise;
2142}
2143
2144// Retrieve an item from the store. Unlike the original async_storage
2145// library in Gaia, we don't modify return values at all. If a key's value
2146// is `undefined`, we pass that value to the callback function.
2147function getItem$2(key, callback) {
2148 var self = this;
2149
2150 key = normalizeKey(key);
2151
2152 var promise = self.ready().then(function () {
2153 var dbInfo = self._dbInfo;
2154 var result = localStorage.getItem(dbInfo.keyPrefix + key);
2155
2156 // If a result was found, parse it from the serialized
2157 // string into a JS object. If result isn't truthy, the key
2158 // is likely undefined and we'll pass it straight to the
2159 // callback.
2160 if (result) {
2161 result = dbInfo.serializer.deserialize(result);
2162 }
2163
2164 return result;
2165 });
2166
2167 executeCallback(promise, callback);
2168 return promise;
2169}
2170
2171// Iterate over all items in the store.
2172function iterate$2(iterator, callback) {
2173 var self = this;
2174
2175 var promise = self.ready().then(function () {
2176 var dbInfo = self._dbInfo;
2177 var keyPrefix = dbInfo.keyPrefix;
2178 var keyPrefixLength = keyPrefix.length;
2179 var length = localStorage.length;
2180
2181 // We use a dedicated iterator instead of the `i` variable below
2182 // so other keys we fetch in localStorage aren't counted in
2183 // the `iterationNumber` argument passed to the `iterate()`
2184 // callback.
2185 //
2186 // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
2187 var iterationNumber = 1;
2188
2189 for (var i = 0; i < length; i++) {
2190 var key = localStorage.key(i);
2191 if (key.indexOf(keyPrefix) !== 0) {
2192 continue;
2193 }
2194 var value = localStorage.getItem(key);
2195
2196 // If a result was found, parse it from the serialized
2197 // string into a JS object. If result isn't truthy, the
2198 // key is likely undefined and we'll pass it straight
2199 // to the iterator.
2200 if (value) {
2201 value = dbInfo.serializer.deserialize(value);
2202 }
2203
2204 value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
2205
2206 if (value !== void 0) {
2207 return value;
2208 }
2209 }
2210 });
2211
2212 executeCallback(promise, callback);
2213 return promise;
2214}
2215
2216// Same as localStorage's key() method, except takes a callback.
2217function key$2(n, callback) {
2218 var self = this;
2219 var promise = self.ready().then(function () {
2220 var dbInfo = self._dbInfo;
2221 var result;
2222 try {
2223 result = localStorage.key(n);
2224 } catch (error) {
2225 result = null;
2226 }
2227
2228 // Remove the prefix from the key, if a key is found.
2229 if (result) {
2230 result = result.substring(dbInfo.keyPrefix.length);
2231 }
2232
2233 return result;
2234 });
2235
2236 executeCallback(promise, callback);
2237 return promise;
2238}
2239
2240function keys$2(callback) {
2241 var self = this;
2242 var promise = self.ready().then(function () {
2243 var dbInfo = self._dbInfo;
2244 var length = localStorage.length;
2245 var keys = [];
2246
2247 for (var i = 0; i < length; i++) {
2248 var itemKey = localStorage.key(i);
2249 if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
2250 keys.push(itemKey.substring(dbInfo.keyPrefix.length));
2251 }
2252 }
2253
2254 return keys;
2255 });
2256
2257 executeCallback(promise, callback);
2258 return promise;
2259}
2260
2261// Supply the number of keys in the datastore to the callback function.
2262function length$2(callback) {
2263 var self = this;
2264 var promise = self.keys().then(function (keys) {
2265 return keys.length;
2266 });
2267
2268 executeCallback(promise, callback);
2269 return promise;
2270}
2271
2272// Remove an item from the store, nice and simple.
2273function removeItem$2(key, callback) {
2274 var self = this;
2275
2276 key = normalizeKey(key);
2277
2278 var promise = self.ready().then(function () {
2279 var dbInfo = self._dbInfo;
2280 localStorage.removeItem(dbInfo.keyPrefix + key);
2281 });
2282
2283 executeCallback(promise, callback);
2284 return promise;
2285}
2286
2287// Set a key's value and run an optional callback once the value is set.
2288// Unlike Gaia's implementation, the callback function is passed the value,
2289// in case you want to operate on that value only after you're sure it
2290// saved, or something like that.
2291function setItem$2(key, value, callback) {
2292 var self = this;
2293
2294 key = normalizeKey(key);
2295
2296 var promise = self.ready().then(function () {
2297 // Convert undefined values to null.
2298 // https://github.com/mozilla/localForage/pull/42
2299 if (value === undefined) {
2300 value = null;
2301 }
2302
2303 // Save the original value to pass to the callback.
2304 var originalValue = value;
2305
2306 return new Promise$1(function (resolve, reject) {
2307 var dbInfo = self._dbInfo;
2308 dbInfo.serializer.serialize(value, function (value, error) {
2309 if (error) {
2310 reject(error);
2311 } else {
2312 try {
2313 localStorage.setItem(dbInfo.keyPrefix + key, value);
2314 resolve(originalValue);
2315 } catch (e) {
2316 // localStorage capacity exceeded.
2317 // TODO: Make this a specific error/event.
2318 if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
2319 reject(e);
2320 }
2321 reject(e);
2322 }
2323 }
2324 });
2325 });
2326 });
2327
2328 executeCallback(promise, callback);
2329 return promise;
2330}
2331
2332function dropInstance$2(options, callback) {
2333 callback = getCallback.apply(this, arguments);
2334
2335 options = typeof options !== 'function' && options || {};
2336 if (!options.name) {
2337 var currentConfig = this.config();
2338 options.name = options.name || currentConfig.name;
2339 options.storeName = options.storeName || currentConfig.storeName;
2340 }
2341
2342 var self = this;
2343 var promise;
2344 if (!options.name) {
2345 promise = Promise$1.reject('Invalid arguments');
2346 } else {
2347 promise = new Promise$1(function (resolve) {
2348 if (!options.storeName) {
2349 resolve(options.name + '/');
2350 } else {
2351 resolve(_getKeyPrefix(options, self._defaultConfig));
2352 }
2353 }).then(function (keyPrefix) {
2354 for (var i = localStorage.length - 1; i >= 0; i--) {
2355 var key = localStorage.key(i);
2356
2357 if (key.indexOf(keyPrefix) === 0) {
2358 localStorage.removeItem(key);
2359 }
2360 }
2361 });
2362 }
2363
2364 executeCallback(promise, callback);
2365 return promise;
2366}
2367
2368var localStorageWrapper = {
2369 _driver: 'localStorageWrapper',
2370 _initStorage: _initStorage$2,
2371 _support: isLocalStorageValid(),
2372 iterate: iterate$2,
2373 getItem: getItem$2,
2374 setItem: setItem$2,
2375 removeItem: removeItem$2,
2376 clear: clear$2,
2377 length: length$2,
2378 key: key$2,
2379 keys: keys$2,
2380 dropInstance: dropInstance$2
2381};
2382
2383var isArray = Array.isArray || function (arg) {
2384 return Object.prototype.toString.call(arg) === '[object Array]';
2385};
2386
2387// Drivers are stored here when `defineDriver()` is called.
2388// They are shared across all instances of localForage.
2389var DefinedDrivers = {};
2390
2391var DriverSupport = {};
2392
2393var DefaultDrivers = {
2394 INDEXEDDB: asyncStorage,
2395 WEBSQL: webSQLStorage,
2396 LOCALSTORAGE: localStorageWrapper
2397};
2398
2399var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
2400
2401var OptionalDriverMethods = ['dropInstance'];
2402
2403var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
2404
2405var DefaultConfig = {
2406 description: '',
2407 driver: DefaultDriverOrder.slice(),
2408 name: 'localforage',
2409 // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
2410 // we can use without a prompt.
2411 size: 4980736,
2412 storeName: 'keyvaluepairs',
2413 version: 1.0
2414};
2415
2416function callWhenReady(localForageInstance, libraryMethod) {
2417 localForageInstance[libraryMethod] = function () {
2418 var _args = arguments;
2419 return localForageInstance.ready().then(function () {
2420 return localForageInstance[libraryMethod].apply(localForageInstance, _args);
2421 });
2422 };
2423}
2424
2425function extend() {
2426 for (var i = 1; i < arguments.length; i++) {
2427 var arg = arguments[i];
2428
2429 if (arg) {
2430 for (var _key in arg) {
2431 if (arg.hasOwnProperty(_key)) {
2432 if (isArray(arg[_key])) {
2433 arguments[0][_key] = arg[_key].slice();
2434 } else {
2435 arguments[0][_key] = arg[_key];
2436 }
2437 }
2438 }
2439 }
2440 }
2441
2442 return arguments[0];
2443}
2444
2445var LocalForage = function () {
2446 function LocalForage(options) {
2447 _classCallCheck(this, LocalForage);
2448
2449 for (var driverTypeKey in DefaultDrivers) {
2450 if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
2451 var driver = DefaultDrivers[driverTypeKey];
2452 var driverName = driver._driver;
2453 this[driverTypeKey] = driverName;
2454
2455 if (!DefinedDrivers[driverName]) {
2456 // we don't need to wait for the promise,
2457 // since the default drivers can be defined
2458 // in a blocking manner
2459 this.defineDriver(driver);
2460 }
2461 }
2462 }
2463
2464 this._defaultConfig = extend({}, DefaultConfig);
2465 this._config = extend({}, this._defaultConfig, options);
2466 this._driverSet = null;
2467 this._initDriver = null;
2468 this._ready = false;
2469 this._dbInfo = null;
2470
2471 this._wrapLibraryMethodsWithReady();
2472 this.setDriver(this._config.driver)["catch"](function () {});
2473 }
2474
2475 // Set any config values for localForage; can be called anytime before
2476 // the first API call (e.g. `getItem`, `setItem`).
2477 // We loop through options so we don't overwrite existing config
2478 // values.
2479
2480
2481 LocalForage.prototype.config = function config(options) {
2482 // If the options argument is an object, we use it to set values.
2483 // Otherwise, we return either a specified config value or all
2484 // config values.
2485 if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
2486 // If localforage is ready and fully initialized, we can't set
2487 // any new configuration values. Instead, we return an error.
2488 if (this._ready) {
2489 return new Error('Can\'t call config() after localforage ' + 'has been used.');
2490 }
2491
2492 for (var i in options) {
2493 if (i === 'storeName') {
2494 options[i] = options[i].replace(/\W/g, '_');
2495 }
2496
2497 if (i === 'version' && typeof options[i] !== 'number') {
2498 return new Error('Database version must be a number.');
2499 }
2500
2501 this._config[i] = options[i];
2502 }
2503
2504 // after all config options are set and
2505 // the driver option is used, try setting it
2506 if ('driver' in options && options.driver) {
2507 return this.setDriver(this._config.driver);
2508 }
2509
2510 return true;
2511 } else if (typeof options === 'string') {
2512 return this._config[options];
2513 } else {
2514 return this._config;
2515 }
2516 };
2517
2518 // Used to define a custom driver, shared across all instances of
2519 // localForage.
2520
2521
2522 LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
2523 var promise = new Promise$1(function (resolve, reject) {
2524 try {
2525 var driverName = driverObject._driver;
2526 var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
2527
2528 // A driver name should be defined and not overlap with the
2529 // library-defined, default drivers.
2530 if (!driverObject._driver) {
2531 reject(complianceError);
2532 return;
2533 }
2534
2535 var driverMethods = LibraryMethods.concat('_initStorage');
2536 for (var i = 0, len = driverMethods.length; i < len; i++) {
2537 var driverMethodName = driverMethods[i];
2538
2539 // when the property is there,
2540 // it should be a method even when optional
2541 var isRequired = OptionalDriverMethods.indexOf(driverMethodName) < 0;
2542 if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
2543 reject(complianceError);
2544 return;
2545 }
2546 }
2547
2548 var configureMissingMethods = function configureMissingMethods() {
2549 var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
2550 return function () {
2551 var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
2552 var promise = Promise$1.reject(error);
2553 executeCallback(promise, arguments[arguments.length - 1]);
2554 return promise;
2555 };
2556 };
2557
2558 for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
2559 var optionalDriverMethod = OptionalDriverMethods[_i];
2560 if (!driverObject[optionalDriverMethod]) {
2561 driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
2562 }
2563 }
2564 };
2565
2566 configureMissingMethods();
2567
2568 var setDriverSupport = function setDriverSupport(support) {
2569 if (DefinedDrivers[driverName]) {
2570 console.info('Redefining LocalForage driver: ' + driverName);
2571 }
2572 DefinedDrivers[driverName] = driverObject;
2573 DriverSupport[driverName] = support;
2574 // don't use a then, so that we can define
2575 // drivers that have simple _support methods
2576 // in a blocking manner
2577 resolve();
2578 };
2579
2580 if ('_support' in driverObject) {
2581 if (driverObject._support && typeof driverObject._support === 'function') {
2582 driverObject._support().then(setDriverSupport, reject);
2583 } else {
2584 setDriverSupport(!!driverObject._support);
2585 }
2586 } else {
2587 setDriverSupport(true);
2588 }
2589 } catch (e) {
2590 reject(e);
2591 }
2592 });
2593
2594 executeTwoCallbacks(promise, callback, errorCallback);
2595 return promise;
2596 };
2597
2598 LocalForage.prototype.driver = function driver() {
2599 return this._driver || null;
2600 };
2601
2602 LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
2603 var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
2604
2605 executeTwoCallbacks(getDriverPromise, callback, errorCallback);
2606 return getDriverPromise;
2607 };
2608
2609 LocalForage.prototype.getSerializer = function getSerializer(callback) {
2610 var serializerPromise = Promise$1.resolve(localforageSerializer);
2611 executeTwoCallbacks(serializerPromise, callback);
2612 return serializerPromise;
2613 };
2614
2615 LocalForage.prototype.ready = function ready(callback) {
2616 var self = this;
2617
2618 var promise = self._driverSet.then(function () {
2619 if (self._ready === null) {
2620 self._ready = self._initDriver();
2621 }
2622
2623 return self._ready;
2624 });
2625
2626 executeTwoCallbacks(promise, callback, callback);
2627 return promise;
2628 };
2629
2630 LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
2631 var self = this;
2632
2633 if (!isArray(drivers)) {
2634 drivers = [drivers];
2635 }
2636
2637 var supportedDrivers = this._getSupportedDrivers(drivers);
2638
2639 function setDriverToConfig() {
2640 self._config.driver = self.driver();
2641 }
2642
2643 function extendSelfWithDriver(driver) {
2644 self._extend(driver);
2645 setDriverToConfig();
2646
2647 self._ready = self._initStorage(self._config);
2648 return self._ready;
2649 }
2650
2651 function initDriver(supportedDrivers) {
2652 return function () {
2653 var currentDriverIndex = 0;
2654
2655 function driverPromiseLoop() {
2656 while (currentDriverIndex < supportedDrivers.length) {
2657 var driverName = supportedDrivers[currentDriverIndex];
2658 currentDriverIndex++;
2659
2660 self._dbInfo = null;
2661 self._ready = null;
2662
2663 return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
2664 }
2665
2666 setDriverToConfig();
2667 var error = new Error('No available storage method found.');
2668 self._driverSet = Promise$1.reject(error);
2669 return self._driverSet;
2670 }
2671
2672 return driverPromiseLoop();
2673 };
2674 }
2675
2676 // There might be a driver initialization in progress
2677 // so wait for it to finish in order to avoid a possible
2678 // race condition to set _dbInfo
2679 var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
2680 return Promise$1.resolve();
2681 }) : Promise$1.resolve();
2682
2683 this._driverSet = oldDriverSetDone.then(function () {
2684 var driverName = supportedDrivers[0];
2685 self._dbInfo = null;
2686 self._ready = null;
2687
2688 return self.getDriver(driverName).then(function (driver) {
2689 self._driver = driver._driver;
2690 setDriverToConfig();
2691 self._wrapLibraryMethodsWithReady();
2692 self._initDriver = initDriver(supportedDrivers);
2693 });
2694 })["catch"](function () {
2695 setDriverToConfig();
2696 var error = new Error('No available storage method found.');
2697 self._driverSet = Promise$1.reject(error);
2698 return self._driverSet;
2699 });
2700
2701 executeTwoCallbacks(this._driverSet, callback, errorCallback);
2702 return this._driverSet;
2703 };
2704
2705 LocalForage.prototype.supports = function supports(driverName) {
2706 return !!DriverSupport[driverName];
2707 };
2708
2709 LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
2710 extend(this, libraryMethodsAndProperties);
2711 };
2712
2713 LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
2714 var supportedDrivers = [];
2715 for (var i = 0, len = drivers.length; i < len; i++) {
2716 var driverName = drivers[i];
2717 if (this.supports(driverName)) {
2718 supportedDrivers.push(driverName);
2719 }
2720 }
2721 return supportedDrivers;
2722 };
2723
2724 LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
2725 // Add a stub for each driver API method that delays the call to the
2726 // corresponding driver method until localForage is ready. These stubs
2727 // will be replaced by the driver methods as soon as the driver is
2728 // loaded, so there is no performance impact.
2729 for (var i = 0, len = LibraryMethods.length; i < len; i++) {
2730 callWhenReady(this, LibraryMethods[i]);
2731 }
2732 };
2733
2734 LocalForage.prototype.createInstance = function createInstance(options) {
2735 return new LocalForage(options);
2736 };
2737
2738 return LocalForage;
2739}();
2740
2741// The actual localForage object that we expose as a module or via a
2742// global. It's extended by pulling in one of our other libraries.
2743
2744
2745var localforage_js = new LocalForage();
2746
2747module.exports = localforage_js;
2748
2749},{"3":3}]},{},[4])(4)
2750});
\No newline at end of file