diff --git a/browser-version/out/nestdb.js b/browser-version/out/nestdb.js index 1d36e1a..5a418be 100644 --- a/browser-version/out/nestdb.js +++ b/browser-version/out/nestdb.js @@ -1,4 +1,4 @@ -(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.NestDB = 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 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) { + return Promise$1.resolve().then(function () { + if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + // increase the db version, to create the new ObjectStore + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + }).then(function () { + return _tryReconnect(dbInfo).then(function () { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + + callback(err); + } +} + +function createDbContext() { + return { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null, + // Database readiness (promise). + dbReady: null, + // Deferred operations on the database. + deferredOperations: [] + }; +} + // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { @@ -5888,26 +6001,12 @@ function _initStorage(options) { } } - // Initialize a singleton container for all running localForages. - if (!dbContexts) { - dbContexts = {}; - } - // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { - dbContext = { - // Running localForages sharing a database. - forages: [], - // Shared database. - db: null, - // Database readiness (promise). - dbReady: null, - // Deferred operations on the database. - deferredOperations: [] - }; + dbContext = createDbContext(); // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } @@ -5972,32 +6071,37 @@ function _initStorage(options) { function getItem(key, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { - var dbInfo = self._dbInfo; - var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); - var req = store.get(key); - - req.onsuccess = function () { - var value = req.result; - if (value === undefined) { - value = null; - } - if (_isEncodedBlob(value)) { - value = _decodeBlob(value); + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); } - resolve(value); - }; - req.onerror = function () { - reject(req.error); - }; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function () { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6011,35 +6115,46 @@ function iterate(iterator, callback) { var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { - var dbInfo = self._dbInfo; - var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } - var req = store.openCursor(); - var iterationNumber = 1; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; - req.onsuccess = function () { - var cursor = req.result; + req.onsuccess = function () { + var cursor = req.result; - if (cursor) { - var value = cursor.value; - if (_isEncodedBlob(value)) { - value = _decodeBlob(value); - } - var result = iterator(value, cursor.key, iterationNumber++); + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + + // when the iterator callback retuns any + // (non-`undefined`) value, then we stop + // the iteration immediately + if (result !== void 0) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; - if (result !== void 0) { - resolve(result); - } else { - cursor["continue"](); - } - } else { - resolve(); + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); } - }; - - req.onerror = function () { - reject(req.error); - }; + }); })["catch"](reject); }); @@ -6051,11 +6166,7 @@ function iterate(iterator, callback) { function setItem(key, value, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { var dbInfo; @@ -6071,35 +6182,45 @@ function setItem(key, value, callback) { } return value; }).then(function (value) { - var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); - var store = transaction.objectStore(dbInfo.storeName); - var req = store.put(value, key); - - // The reason we don't _save_ null is because IE 10 does - // not support saving the `null` type in IndexedDB. How - // ironic, given the bug below! - // See: https://github.com/mozilla/localForage/issues/161 - if (value === null) { - value = undefined; - } - - transaction.oncomplete = function () { - // Cast to undefined so the value passed to - // callback/promise is the same as what one would get out - // of `getItem()` later. This leads to some weirdness - // (setItem('foo', undefined) will return `null`), but - // it's not my fault localStorage is our baseline and that - // it's weird. - if (value === undefined) { - value = null; + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); } - resolve(value); - }; - transaction.onabort = transaction.onerror = function () { - var err = req.error ? req.error : req.transaction.error; - reject(err); - }; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + var req = store.put(value, key); + + transaction.oncomplete = function () { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6110,38 +6231,41 @@ function setItem(key, value, callback) { function removeItem(key, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { - var dbInfo = self._dbInfo; - var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); - var store = transaction.objectStore(dbInfo.storeName); - - // We use a Grunt task to make this safe for IE and some - // versions of Android (including those used by Cordova). - // Normally IE won't like `.delete()` and will insist on - // using `['delete']()`, but we have a build step that - // fixes this for us now. - var req = store["delete"](key); - transaction.oncomplete = function () { - resolve(); - }; - - transaction.onerror = function () { - reject(req.error); - }; + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } - // The request will be also be aborted if we've exceeded our storage - // space. - transaction.onabort = function () { - var err = req.error ? req.error : req.transaction.error; - reject(err); - }; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store["delete"](key); + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onerror = function () { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6154,19 +6278,27 @@ function clear(callback) { var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { - var dbInfo = self._dbInfo; - var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); - var store = transaction.objectStore(dbInfo.storeName); - var req = store.clear(); - - transaction.oncomplete = function () { - resolve(); - }; + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } - transaction.onabort = transaction.onerror = function () { - var err = req.error ? req.error : req.transaction.error; - reject(err); - }; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6179,17 +6311,26 @@ function length(callback) { var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { - var dbInfo = self._dbInfo; - var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); - var req = store.count(); - - req.onsuccess = function () { - resolve(req.result); - }; + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } - req.onerror = function () { - reject(req.error); - }; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function () { + resolve(req.result); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6208,40 +6349,49 @@ function key(n, callback) { } self.ready().then(function () { - var dbInfo = self._dbInfo; - var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } - var advanced = false; - var req = store.openCursor(); - req.onsuccess = function () { - var cursor = req.result; - if (!cursor) { - // this means there weren't enough keys - resolve(null); + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var advanced = false; + var req = store.openCursor(); - return; - } + req.onsuccess = function () { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); - if (n === 0) { - // We have the first key, return it if that's what they - // wanted. - resolve(cursor.key); - } else { - if (!advanced) { - // Otherwise, ask the cursor to skip ahead n - // records. - advanced = true; - cursor.advance(n); - } else { - // When we get here, we've got the nth key. - resolve(cursor.key); - } - } - }; + return; + } - req.onerror = function () { - reject(req.error); - }; + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6254,27 +6404,35 @@ function keys(callback) { var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { - var dbInfo = self._dbInfo; - var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } - var req = store.openCursor(); - var keys = []; + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.openCursor(); + var keys = []; - req.onsuccess = function () { - var cursor = req.result; + req.onsuccess = function () { + var cursor = req.result; - if (!cursor) { - resolve(keys); - return; - } + if (!cursor) { + resolve(keys); + return; + } - keys.push(cursor.key); - cursor["continue"](); - }; + keys.push(cursor.key); + cursor["continue"](); + }; - req.onerror = function () { - reject(req.error); - }; + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); })["catch"](reject); }); @@ -6282,9 +6440,141 @@ function keys(callback) { return promise; } +function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + + var currentConfig = this.config(); + options = typeof options !== 'function' && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db; + + var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + return db; + }); + + if (!options.storeName) { + promise = dbPromise.then(function (db) { + _deferReadiness(options); + + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + + db.close(); + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + } + + var dropDBPromise = new Promise$1(function (resolve, reject) { + var req = idb.deleteDatabase(options.name); + + req.onerror = req.onblocked = function (err) { + var db = req.result; + if (db) { + db.close(); + } + reject(err); + }; + + req.onsuccess = function () { + var db = req.result; + if (db) { + db.close(); + } + resolve(db); + }; + }); + + return dropDBPromise.then(function (db) { + dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + var _forage = forages[i]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function (err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); + throw err; + }); + }); + } else { + promise = dbPromise.then(function (db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + + var newVersion = db.version + 1; + + _deferReadiness(options); + + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + + db.close(); + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + + var dropObjectPromise = new Promise$1(function (resolve, reject) { + var req = idb.open(options.name, newVersion); + + req.onerror = function (err) { + var db = req.result; + db.close(); + reject(err); + }; + + req.onupgradeneeded = function () { + var db = req.result; + db.deleteObjectStore(options.storeName); + }; + + req.onsuccess = function () { + var db = req.result; + db.close(); + resolve(db); + }; + }); + + return dropObjectPromise.then(function (db) { + dbContext.db = db; + for (var j = 0; j < forages.length; j++) { + var _forage2 = forages[j]; + _forage2._dbInfo.db = db; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function (err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); + throw err; + }); + }); + } + } + + executeCallback(promise, callback); + return promise; +} + var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, + _support: isIndexedDBValid(), iterate: iterate, getItem: getItem, setItem: setItem, @@ -6292,9 +6582,14 @@ var asyncStorage = { clear: clear, length: length, key: key, - keys: keys + keys: keys, + dropInstance: dropInstance }; +function isWebSQLValid() { + return typeof openDatabase === 'function'; +} + // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. @@ -6529,6 +6824,11 @@ var localforageSerializer = { * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ + +function createDbTable(t, dbInfo, callback, errorCallback) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback); +} + // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage$1(options) { @@ -6554,33 +6854,49 @@ function _initStorage$1(options) { // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { - t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { + createDbTable(t, dbInfo, function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); - }); + }, reject); }); dbInfo.serializer = localforageSerializer; return dbInfoPromise; } +function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { + t.executeSql(sqlStatement, args, callback, function (t, error) { + if (error.code === error.SYNTAX_ERR) { + t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) { + if (!results.rows.length) { + // if the table is missing (was deleted) + // re-create it table and retry + createDbTable(t, dbInfo, function () { + t.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t, error); + } + }, errorCallback); + } else { + errorCallback(t, error); + } + }, errorCallback); +} + function getItem$1(key, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { - t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { + tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to @@ -6591,7 +6907,6 @@ function getItem$1(key, callback) { resolve(result); }, function (t, error) { - reject(error); }); }); @@ -6610,7 +6925,7 @@ function iterate$1(iterator, callback) { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { - t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { + tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; @@ -6649,11 +6964,7 @@ function iterate$1(iterator, callback) { function _setItem(key, value, callback, retriesLeft) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { @@ -6673,7 +6984,7 @@ function _setItem(key, value, callback, retriesLeft) { reject(error); } else { dbInfo.db.transaction(function (t) { - t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { + tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); @@ -6712,20 +7023,15 @@ function setItem$1(key, value, callback) { function removeItem$1(key, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { - t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { + tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { - reject(error); }); }); @@ -6745,7 +7051,7 @@ function clear$1(callback) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { - t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { + tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); @@ -6768,12 +7074,10 @@ function length$1(callback) { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. - t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { + tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; - resolve(result); }, function (t, error) { - reject(error); }); }); @@ -6798,7 +7102,7 @@ function key$1(n, callback) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { - t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { + tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { @@ -6819,7 +7123,7 @@ function keys$1(callback) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { - t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { + tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { @@ -6828,7 +7132,6 @@ function keys$1(callback) { resolve(keys); }, function (t, error) { - reject(error); }); }); @@ -6839,9 +7142,102 @@ function keys$1(callback) { return promise; } +// https://www.w3.org/TR/webdatabase/#databases +// > There is no way to enumerate or delete the databases available for an origin from this API. +function getAllStoreNames(db) { + return new Promise$1(function (resolve, reject) { + db.transaction(function (t) { + t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) { + var storeNames = []; + + for (var i = 0; i < results.rows.length; i++) { + storeNames.push(results.rows.item(i).name); + } + + resolve({ + db: db, + storeNames: storeNames + }); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + reject(sqlError); + }); + }); +} + +function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + + var currentConfig = this.config(); + options = typeof options !== 'function' && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + promise = new Promise$1(function (resolve) { + var db; + if (options.name === currentConfig.name) { + // use the db reference of the current instance + db = self._dbInfo.db; + } else { + db = openDatabase(options.name, '', '', 0); + } + + if (!options.storeName) { + // drop all database tables + resolve(getAllStoreNames(db)); + } else { + resolve({ + db: db, + storeNames: [options.storeName] + }); + } + }).then(function (operationInfo) { + return new Promise$1(function (resolve, reject) { + operationInfo.db.transaction(function (t) { + function dropTable(storeName) { + return new Promise$1(function (resolve, reject) { + t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + } + + var operations = []; + for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) { + operations.push(dropTable(operationInfo.storeNames[i])); + } + + Promise$1.all(operations).then(function () { + resolve(); + })["catch"](function (e) { + reject(e); + }); + }, function (sqlError) { + reject(sqlError); + }); + }); + }); + } + + executeCallback(promise, callback); + return promise; +} + var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage$1, + _support: isWebSQLValid(), iterate: iterate$1, getItem: getItem$1, setItem: setItem$1, @@ -6849,9 +7245,51 @@ var webSQLStorage = { clear: clear$1, length: length$1, key: key$1, - keys: keys$1 + keys: keys$1, + dropInstance: dropInstance$1 }; +function isLocalStorageValid() { + try { + return typeof localStorage !== 'undefined' && 'setItem' in localStorage && + // in IE8 typeof localStorage.setItem === 'object' + !!localStorage.setItem; + } catch (e) { + return false; + } +} + +function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + '/'; + + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + '/'; + } + return keyPrefix; +} + +// Check if localStorage throws when saving an item +function checkIfLocalStorageThrows() { + var localStorageTestKey = '_localforage_support_test'; + + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + + return false; + } catch (e) { + return true; + } +} + +// Check if localStorage is usable and allows to save an item +// This method checks if localStorage is usable in Safari Private Browsing +// mode, or in any other case where the available quota for localStorage +// is 0 and there wasn't any saved items yet. +function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; +} + // Config the localStorage backend, using options set in the config. function _initStorage$2(options) { var self = this; @@ -6862,10 +7300,10 @@ function _initStorage$2(options) { } } - dbInfo.keyPrefix = dbInfo.name + '/'; + dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig); - if (dbInfo.storeName !== self._defaultConfig.storeName) { - dbInfo.keyPrefix += dbInfo.storeName + '/'; + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); } self._dbInfo = dbInfo; @@ -6900,11 +7338,7 @@ function clear$2(callback) { function getItem$2(key, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = self.ready().then(function () { var dbInfo = self._dbInfo; @@ -7002,8 +7436,9 @@ function keys$2(callback) { var keys = []; for (var i = 0; i < length; i++) { - if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { - keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); + var itemKey = localStorage.key(i); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys.push(itemKey.substring(dbInfo.keyPrefix.length)); } } @@ -7029,11 +7464,7 @@ function length$2(callback) { function removeItem$2(key, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = self.ready().then(function () { var dbInfo = self._dbInfo; @@ -7051,11 +7482,7 @@ function removeItem$2(key, callback) { function setItem$2(key, value, callback) { var self = this; - // Cast the key to a string, as that's all we can set as a key. - if (typeof key !== 'string') { - console.warn(key + ' used as a key, but it is not a string.'); - key = String(key); - } + key = normalizeKey(key); var promise = self.ready().then(function () { // Convert undefined values to null. @@ -7093,10 +7520,46 @@ function setItem$2(key, value, callback) { return promise; } +function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + + options = typeof options !== 'function' && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + promise = new Promise$1(function (resolve) { + if (!options.storeName) { + resolve(options.name + '/'); + } else { + resolve(_getKeyPrefix(options, self._defaultConfig)); + } + }).then(function (keyPrefix) { + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + } + + executeCallback(promise, callback); + return promise; +} + var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage$2, - // Default API, from Gaia/localStorage. + _support: isLocalStorageValid(), iterate: iterate$2, getItem: getItem$2, setItem: setItem$2, @@ -7104,22 +7567,48 @@ var localStorageWrapper = { clear: clear$2, length: length$2, key: key$2, - keys: keys$2 + keys: keys$2, + dropInstance: dropInstance$2 +}; + +var sameValue = function sameValue(x, y) { + return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); }; -// Custom drivers are stored here when `defineDriver()` is called. +var includes = function includes(array, searchElement) { + var len = array.length; + var i = 0; + while (i < len) { + if (sameValue(array[i], searchElement)) { + return true; + } + i++; + } + + return false; +}; + +var isArray = Array.isArray || function (arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; +}; + +// Drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. -var CustomDrivers = {}; +var DefinedDrivers = {}; + +var DriverSupport = {}; -var DriverType = { - INDEXEDDB: 'asyncStorage', - LOCALSTORAGE: 'localStorageWrapper', - WEBSQL: 'webSQLStorage' +var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper }; -var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; +var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; -var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; +var OptionalDriverMethods = ['dropInstance']; + +var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods); var DefaultConfig = { description: '', @@ -7132,22 +7621,6 @@ var DefaultConfig = { version: 1.0 }; -var driverSupport = {}; -// Check to see if IndexedDB is available and if it is the latest -// implementation; it's our preferred backend library. We use "_spec_test" -// as the name of the database because it's not the one we'll operate on, -// but it's useful to make sure its using the right spec. -// See: https://github.com/mozilla/localForage/issues/128 -driverSupport[DriverType.INDEXEDDB] = isIndexedDBValid(); - -driverSupport[DriverType.WEBSQL] = isWebSQLValid(); - -driverSupport[DriverType.LOCALSTORAGE] = isLocalStorageValid(); - -var isArray = Array.isArray || function (arg) { - return Object.prototype.toString.call(arg) === '[object Array]'; -}; - function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; @@ -7162,12 +7635,12 @@ function extend() { var arg = arguments[i]; if (arg) { - for (var key in arg) { - if (arg.hasOwnProperty(key)) { - if (isArray(arg[key])) { - arguments[0][key] = arg[key].slice(); + for (var _key in arg) { + if (arg.hasOwnProperty(_key)) { + if (isArray(arg[_key])) { + arguments[0][_key] = arg[_key].slice(); } else { - arguments[0][key] = arg[key]; + arguments[0][_key] = arg[_key]; } } } @@ -7177,23 +7650,24 @@ function extend() { return arguments[0]; } -function isLibraryDriver(driverName) { - for (var driver in DriverType) { - if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { - return true; - } - } - - return false; -} - var LocalForage = function () { function LocalForage(options) { _classCallCheck(this, LocalForage); - this.INDEXEDDB = DriverType.INDEXEDDB; - this.LOCALSTORAGE = DriverType.LOCALSTORAGE; - this.WEBSQL = DriverType.WEBSQL; + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + + if (!DefinedDrivers[driverName]) { + // we don't need to wait for the promise, + // since the default drivers can be defined + // in a blocking manner + this.defineDriver(driver); + } + } + } this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); @@ -7258,7 +7732,6 @@ var LocalForage = function () { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); - var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. @@ -7266,34 +7739,61 @@ var LocalForage = function () { reject(complianceError); return; } - if (isLibraryDriver(driverObject._driver)) { - reject(namingError); - return; - } - var customDriverMethods = LibraryMethods.concat('_initStorage'); - for (var i = 0; i < customDriverMethods.length; i++) { - var customDriverMethod = customDriverMethods[i]; - if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { + var driverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0, len = driverMethods.length; i < len; i++) { + var driverMethodName = driverMethods[i]; + + // when the property is there, + // it should be a method even when optional + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') { reject(complianceError); return; } } - var supportPromise = Promise$1.resolve(true); + var configureMissingMethods = function configureMissingMethods() { + var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { + return function () { + var error = new Error('Method ' + methodName + ' is not implemented by the current driver'); + var promise = Promise$1.reject(error); + executeCallback(promise, arguments[arguments.length - 1]); + return promise; + }; + }; + + for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + + configureMissingMethods(); + + var setDriverSupport = function setDriverSupport(support) { + if (DefinedDrivers[driverName]) { + console.info('Redefining LocalForage driver: ' + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + // don't use a then, so that we can define + // drivers that have simple _support methods + // in a blocking manner + resolve(); + }; + if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { - supportPromise = driverObject._support(); + driverObject._support().then(setDriverSupport, reject); } else { - supportPromise = Promise$1.resolve(!!driverObject._support); + setDriverSupport(!!driverObject._support); } + } else { + setDriverSupport(true); } - - supportPromise.then(function (supportResult) { - driverSupport[driverName] = supportResult; - CustomDrivers[driverName] = driverObject; - resolve(); - }, reject); } catch (e) { reject(e); } @@ -7308,23 +7808,8 @@ var LocalForage = function () { }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { - var self = this; - var getDriverPromise = Promise$1.resolve().then(function () { - if (isLibraryDriver(driverName)) { - switch (driverName) { - case self.INDEXEDDB: - return asyncStorage; - case self.LOCALSTORAGE: - return localStorageWrapper; - case self.WEBSQL: - return webSQLStorage; - } - } else if (CustomDrivers[driverName]) { - return CustomDrivers[driverName]; - } else { - throw new Error('Driver not found.'); - } - }); + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.')); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); return getDriverPromise; }; @@ -7426,7 +7911,7 @@ var LocalForage = function () { }; LocalForage.prototype.supports = function supports(driverName) { - return !!driverSupport[driverName]; + return !!DriverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { @@ -7449,7 +7934,7 @@ var LocalForage = function () { // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. - for (var i = 0; i < LibraryMethods.length; i++) { + for (var i = 0, len = LibraryMethods.length; i < len; i++) { callWhenReady(this, LibraryMethods[i]); } }; @@ -7471,6 +7956,7 @@ module.exports = localforage_js; },{"3":3}]},{},[4])(4) }); + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],15:[function(require,module,exports){ // Underscore.js 1.4.4 @@ -9005,6 +9491,31 @@ function isUndefined(arg) { } },{}],17:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],18:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -9190,39 +9701,93 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],18:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } +},{}],19:[function(require,module,exports){ +(function (setImmediate,clearImmediate){ +var nextTick = require('process/browser.js').nextTick; +var apply = Function.prototype.apply; +var slice = Array.prototype.slice; +var immediateIds = {}; +var nextImmediateId = 0; + +// DOM APIs, for completeness + +exports.setTimeout = function() { + return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); +}; +exports.setInterval = function() { + return new Timeout(apply.call(setInterval, window, arguments), clearInterval); +}; +exports.clearTimeout = +exports.clearInterval = function(timeout) { timeout.close(); }; + +function Timeout(id, clearFn) { + this._id = id; + this._clearFn = clearFn; } +Timeout.prototype.unref = Timeout.prototype.ref = function() {}; +Timeout.prototype.close = function() { + this._clearFn.call(window, this._id); +}; -},{}],19:[function(require,module,exports){ +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; + +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; + +exports._unrefActive = exports.active = function(item) { + clearTimeout(item._idleTimeoutId); + + var msecs = item._idleTimeout; + if (msecs >= 0) { + item._idleTimeoutId = setTimeout(function onTimeout() { + if (item._onTimeout) + item._onTimeout(); + }, msecs); + } +}; + +// That's not how node.js implements it but the exposed api is the same. +exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { + var id = nextImmediateId++; + var args = arguments.length < 2 ? false : slice.call(arguments, 1); + + immediateIds[id] = true; + + nextTick(function onNextTick() { + if (immediateIds[id]) { + // fn.call() is faster so we optimize for the common use-case + // @see http://jsperf.com/call-apply-segu + if (args) { + fn.apply(null, args); + } else { + fn.call(null); + } + // Prevent ids from leaking + exports.clearImmediate(id); + } + }); + + return id; +}; + +exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { + delete immediateIds[id]; +}; +}).call(this,require("timers").setImmediate,require("timers").clearImmediate) +},{"process/browser.js":18,"timers":19}],20:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],20:[function(require,module,exports){ +},{}],21:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -9812,5 +10377,5 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":19,"_process":17,"inherits":18}]},{},[3])(3) -}); \ No newline at end of file +},{"./support/isBuffer":20,"_process":18,"inherits":17}]},{},[3])(3) +}); diff --git a/browser-version/out/nestdb.min.js b/browser-version/out/nestdb.min.js index 1d87d2d..3a7ea7c 100644 --- a/browser-version/out/nestdb.min.js +++ b/browser-version/out/nestdb.min.js @@ -1 +1 @@ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).NestDB=t()}}(function(){return function t(e,n,r){function i(a,u){if(!n[a]){if(!e[a]){var s="function"==typeof require&&require;if(!u&&s)return s(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=n[a]={exports:{}};e[a][0].call(f.exports,function(t){var n=e[a][1][t];return i(n||t)},f,f.exports,t,e,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;as)s+=1;else if(a.push(l[n]),u+=1,c._limit&&c._limit<=u)break}catch(t){return e(t)}if(c._sort){r=Object.keys(c._sort);var h=[];for(n=0;n>>((3&r)<<3)&255;return n}function i(t){var e,n,r,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=t.length%3,a="";for(r=0,n=t.length-o;r>18&63]+i[t>>12&63]+i[t>>6&63]+i[63&t]}(e=(t[r]<<16)+(t[r+1]<<8)+t[r+2]);switch(o){case 1:e=t[t.length-1],a+=i[e>>2],a+=i[e<<4&63],a+="==";break;case 2:e=(t[t.length-2]<<8)+t[t.length-1],a+=i[e>>10],a+=i[e>>4&63],a+=i[e<<2&63],a+="="}return a}e.exports.uid=function(t){return i(r(Math.ceil(Math.max(8,2*t)))).replace(/[+\/]/g,"").slice(0,t)}},{}],3:[function(t,e,n){function r(t){if(!(this instanceof r))return new r(t);o.call(this);var e=(t=t||{}).filename;this.inMemoryOnly=t.inMemoryOnly||!1,this.autoload=t.autoload||!1,this.timestampData=t.timestampData||!1,"function"==typeof t.idGenerator&&(this._idGenerator=t.idGenerator),e&&"string"==typeof e&&0!==e.length?this.filename=e:(this.filename=null,this.inMemoryOnly=!0),this.compareStrings=t.compareStrings,this.persistence=new h({db:this,afterSerialization:t.afterSerialization,beforeDeserialization:t.beforeDeserialization,corruptAlertThreshold:t.corruptAlertThreshold,storage:t.storage}),this.executor=new f,this.inMemoryOnly&&(this.executor.ready=!0),this.indexes={},this.indexes._id=new l({fieldName:"_id",unique:!0}),this.ttlIndexes={},this.autoload&&this.load(t.onload)}var i=t("util"),o=t("events"),a=t("async"),u=t("underscore"),s=t("./customUtils"),c=t("./model"),f=t("./executor"),l=t("./indexes"),h=t("./persistence"),p=t("./cursor");i.inherits(r,o),o.call(r),Object.keys(o.prototype).forEach(function(t){"function"==typeof o.prototype[t]&&(r[t]=o.prototype[t].bind(r))}),r.prototype.load=function(t){var e=this,n=t||function(t){if(t)throw t};this.executor.push({this:this.persistence,fn:this.persistence.loadDatabase,arguments:[function(t){a.setImmediate(function(){t||(e.constructor.listeners("created").length>0&&e.constructor.emit("created",e),e.listeners("loaded").length>0&&e.emit("loaded")),n(t)})}]},!0)},r.prototype.loadDatabase=r.prototype.load,r.prototype.getAllData=function(){return this.indexes._id.getAll()},r.prototype.resetIndexes=function(t){var e=this;Object.keys(this.indexes).forEach(function(n){e.indexes[n].reset(t)})},r.prototype.ensureIndex=function(t,e){var n,r=e||function(){};if(!(t=t||{}).fieldName)return n=new Error("Cannot create an index without a fieldName"),n.missingFieldName=!0,r(n);if(this.indexes[t.fieldName])return r(null);this.indexes[t.fieldName]=new l(t),void 0!==t.expireAfterSeconds&&(this.ttlIndexes[t.fieldName]=t.expireAfterSeconds);try{this.indexes[t.fieldName].insert(this.getAllData())}catch(e){return delete this.indexes[t.fieldName],r(e)}this.persistence.persistNewState([{$$indexCreated:t}],function(t){return r(t?t:null)})},r.prototype.removeIndex=function(t,e){var n=e||function(){};delete this.indexes[t],this.persistence.persistNewState([{$$indexRemoved:t}],function(t){return n(t?t:null)})},r.prototype.addToIndexes=function(t){var e,n,r,i=Object.keys(this.indexes);for(e=0;e0?e(null,o.indexes[r[0]].getMatching(t[r[0]])):(r=[],Object.keys(t).forEach(function(e){t[e]&&t[e].hasOwnProperty("$in")&&r.push(e)}),(r=u.intersection(r,i)).length>0?e(null,o.indexes[r[0]].getMatching(t[r[0]].$in)):(r=[],Object.keys(t).forEach(function(e){t[e]&&(t[e].hasOwnProperty("$lt")||t[e].hasOwnProperty("$lte")||t[e].hasOwnProperty("$gt")||t[e].hasOwnProperty("$gte"))&&r.push(e)}),(r=u.intersection(r,i)).length>0?e(null,o.indexes[r[0]].getBetweenBounds(t[r[0]])):e(null,o.getAllData())))},function(t){if(e)return n(null,t);var r=[],i=[],s=Object.keys(o.ttlIndexes);t.forEach(function(t){var e=!0;s.forEach(function(n){void 0!==t[n]&&u.isDate(t[n])&&Date.now()>t[n].getTime()+1e3*o.ttlIndexes[n]&&(e=!1)}),e?i.push(t):r.push(t._id)}),a.eachSeries(r,function(t,e){o._remove({_id:t},{},function(t){return t?n(t):e()})},function(t){return n(null,i)})}])},r.prototype._insert=function(t,e){var n,r=this,i=e||function(){},o=function(t,e){var n=this,o=arguments;a.setImmediate(function(){if(!t){var a=Array.isArray(e)?e:[e];r.listeners("inserted").length>0&&a.forEach(function(t){r.emit("inserted",t)})}i.apply(n,o)})};try{n=this.prepareDocumentForInsertion(t),this._insertInCache(n)}catch(t){return o(t)}this.persistence.persistNewState(Array.isArray(n)?n:[n],function(t){return t?o(t):o(null,c.deepCopy(n))})},r.prototype._idGenerator=function(){return s.uid(16)},r.prototype.createNewId=function(){var t;do{t=this._idGenerator()}while(this.indexes._id.getMatching(t).length>0);return t},r.prototype.prepareDocumentForInsertion=function(t){var e,n=this;if(Array.isArray(t))e=[],t.forEach(function(t){e.push(n.prepareDocumentForInsertion(t))});else{void 0===(e=c.deepCopy(t))._id&&(e._id=this.createNewId());var r=new Date;this.timestampData&&void 0===e.createdAt&&(e.createdAt=r),this.timestampData&&void 0===e.updatedAt&&(e.updatedAt=r),c.checkObject(e)}return e},r.prototype._insertInCache=function(t){Array.isArray(t)?this._insertMultipleDocsInCache(t):this.addToIndexes(t)},r.prototype._insertMultipleDocsInCache=function(t){var e,n,r;for(e=0;e0&&l.listeners("updated").length>0&&p.forEach(function(t){l.emit("updated",t.newDoc,t.oldDoc)}),i.apply(e,n)})};l.getCandidates(t,function(i,a){if(i)return d(i);try{for(f=0;f0&&u.listeners("removed").length>0&&l.forEach(function(t){u.emit("removed",t)}),r.apply(e,n)})},this.getCandidates(t,!0,function(e,n){if(e)return i(e);try{n.forEach(function(e){c.match(e,t)&&(o||0===s)&&(s+=1,f.push({$$deleted:!0,_id:e._id}),l.push(e),u.removeFromIndexes(e))})}catch(e){return i(e)}u.persistence.persistNewState(f,function(t){return t?i(t):i(null,s)})})},r.prototype.remove=function(){this.executor.push({this:this,fn:this._remove,arguments:arguments})},r.prototype._destroy=function(t){var e=this,n=t||function(){};e._remove({},{multi:!0},function(t){if(t)return n(t);e.persistence.destroyDatabase(n)})},r.prototype.destroy=function(t){var e=this,n=t||function(){};this.executor.push({this:this,fn:this._destroy,arguments:[function(t){a.setImmediate(function(){t||(e.listeners("destroyed").length>0&&e.emit("destroyed"),e.constructor.listeners("destroyed").length>0&&e.constructor.emit("destroyed",e)),n(t)})}]})},r.plugin=function(t){if("function"==typeof t)t(r);else{if("object"!=typeof t||!t||0===Object.keys(t).length)throw new Error('Invalid plugin: got "'+t+'", expected an object or a function');Object.keys(t).forEach(function(e){r.prototype[e]=t[e]})}return r},e.exports=r},{"./cursor":1,"./customUtils":2,"./executor":4,"./indexes":5,"./model":6,"./persistence":7,async:9,events:16,underscore:15,util:20}],4:[function(t,e,n){function r(){this.buffer=[],this.ready=!1,this.queue=i.queue(function(t,e){for(var n=[],r=0;re?1:0}function s(t,e){var n,r;for(n=0;n0){for(i=0;i=3||2===Object.keys(n).length&&void 0===n.$slice)throw new Error("Can only use $slice in conjunction with $each when $push to array");if(!Array.isArray(n.$each))throw new Error("$each requires an array value");if(n.$each.forEach(function(n){t[e].push(n)}),void 0===n.$slice||"number"!=typeof n.$slice)return;if(0===n.$slice)t[e]=[];else{var r,i,o=t[e].length;n.$slice<0?(r=Math.max(0,o+n.$slice),i=o):n.$slice>0&&(r=0,i=Math.min(o,n.$slice)),t[e]=t[e].slice(r,i)}}else t[e].push(n)},m.$addToSet=function(t,e,n){var r=!0;if(t.hasOwnProperty(e)||(t[e]=[]),!Array.isArray(t[e]))throw new Error("Can't $addToSet an element on non-array values");if(null!==n&&"object"==typeof n&&n.$each){if(Object.keys(n).length>1)throw new Error("Can't use another field in conjunction with $each");if(!Array.isArray(n.$each))throw new Error("$each requires an array value");n.$each.forEach(function(n){m.$addToSet(t,e,n)})}else t[e].forEach(function(t){0===c(t,n)&&(r=!1)}),r&&t[e].push(n)},m.$pop=function(t,e,n){if(!Array.isArray(t[e]))throw new Error("Can't $pop an element from non-array values");if("number"!=typeof n)throw new Error(n+" isn't an integer, can't use it with $pop");0!==n&&(t[e]=n>0?t[e].slice(0,t[e].length-1):t[e].slice(1))},m.$pull=function(t,e,n){var r,i;if(!Array.isArray(t[e]))throw new Error("Can't $pull an element from non-array values");for(i=(r=t[e]).length-1;i>=0;i-=1)d(r[i],n)&&r.splice(i,1)},m.$inc=function(t,e,n){if("number"!=typeof n)throw new Error(n+" must be a number");if("number"!=typeof t[e]){if(v.has(t,e))throw new Error("Don't use the $inc modifier on non-number fields");t[e]=n}else t[e]+=n},m.$max=function(t,e,n){void 0===t[e]?t[e]=n:n>t[e]&&(t[e]=n)},m.$min=function(t,e,n){void 0===t[e]?t[e]=n:ne},b.$gte=function(t,e){return p(t,e)&&t>=e},b.$ne=function(t,e){return void 0===t||!h(t,e)},b.$in=function(t,e){var n;if(!Array.isArray(e))throw new Error("$in operator called with a non-array");for(n=0;n0&&u/n.length>this.corruptAlertThreshold)throw new Error("More than "+Math.floor(100*this.corruptAlertThreshold)+"% of the data file is corrupt, the wrong beforeDeserialization hook may be used. Cautiously refusing to start NestDB to prevent dataloss");return Object.keys(r).forEach(function(t){i.push(r[t])}),{data:i,indexes:o}},r.prototype.loadDatabase=function(t){var e=t||function(){},n=this;if(n.db.resetIndexes(),n.inMemoryOnly)return e(null);i.waterfall([function(t){n.storage.init(n.filename,function(e){if(e)return t(e);n.storage.read(n.filename,function(e,r){if(e)return t(e);try{var i=n.treatRawData(r)}catch(e){return t(e)}Object.keys(i.indexes).forEach(function(t){n.db.indexes[t]=new s(i.indexes[t])});try{n.db.resetIndexes(i.data)}catch(e){return n.db.resetIndexes(),t(e)}n.db.persistence.persistCachedDatabase(t)})})}],function(t){return t?e(t):(n.db.executor.processBuffer(),e(null))})},r.prototype.destroyDatabase=function(t){var e=t||function(){},n=this;if(n.db.resetIndexes(),n.inMemoryOnly)return e(null);n.storage.remove(n.filename,e)},e.exports=r},{"./customUtils":2,"./indexes":5,"./model":6,"./storage":8,async:9}],8:[function(t,e,n){var r=t("localforage"),i={};r.config({name:"NestDB",storeName:"nestdbdata"}),i.write=function(t,e,n){r.setItem(t,e,n)},i.append=function(t,e,n){r.getItem(t,function(i,o){if(i)return n(i);o=o||"",o+=e,r.setItem(t,o,n)})},i.read=function(t,e){r.getItem(t,function(t,n){if(t)return e(t);e(null,n||"")})},i.remove=function(t,e){r.removeItem(t,e)},i.init=function(t,e){return e(null)},e.exports.init=i.init,e.exports.read=i.read,e.exports.write=i.write,e.exports.append=i.append,e.exports.remove=i.remove},{localforage:14}],9:[function(t,e,n){(function(t,n){!function(){function r(){}function i(t){return t}function o(t){return!!t}function a(t){return!t}function u(t){return function(){if(null===t)throw new Error("Callback was already called.");t.apply(this,arguments),t=null}}function s(t){return function(){null!==t&&(t.apply(this,arguments),t=null)}}function c(t){return z(t)||"number"==typeof t.length&&t.length>=0&&t.length%1==0}function f(t,e){for(var n=-1,r=t.length;++n3?t(r,i,s,u):(a=o,o=i,t(r,s,u))}}function S(t,e){return e}function j(t,e,n){n=n||r;var i=c(e)?[]:{};t(e,function(t,e,n){t(g(function(t,r){r.length<=1&&(r=r[0]),i[e]=r,n(t)}))},function(t){n(t,i)})}function I(t,e,n,r){var i=[];t(e,function(t,e,r){n(t,function(t,e){i=i.concat(e||[]),r(t)})},function(t){r(t,i)})}function D(t,e,n){function i(t,e,n,i){if(null!=i&&"function"!=typeof i)throw new Error("task callback must be a function");if(t.started=!0,z(e)||(e=[e]),0===e.length&&t.idle())return M.setImmediate(function(){t.drain()});f(e,function(e){var o={data:e,callback:i||r};n?t.tasks.unshift(o):t.tasks.push(o),t.tasks.length===t.concurrency&&t.saturated()}),M.setImmediate(t.process)}function o(t,e){return function(){a-=1;var n=!1,r=arguments;f(e,function(t){f(s,function(e,r){e!==t||n||(s.splice(r,1),n=!0)}),t.callback.apply(t,r)}),t.tasks.length+a===0&&t.drain(),t.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var a=0,s=[],c={tasks:[],concurrency:e,payload:n,saturated:r,empty:r,drain:r,started:!1,paused:!1,push:function(t,e){i(c,t,!1,e)},kill:function(){c.drain=r,c.tasks=[]},unshift:function(t,e){i(c,t,!0,e)},process:function(){for(;!c.paused&&ar?1:0}M.map(t,function(t,n){e(t,function(e,r){e?n(e):n(null,{value:t,criteria:r})})},function(t,e){if(t)return n(t);n(null,l(e.sort(r),function(t){return t.value}))})},M.auto=function(t,e,n){function i(t){m.unshift(t)}function o(t){var e=y(m,t);e>=0&&m.splice(e,1)}function a(){c--,f(m.slice(0),function(t){t()})}"function"==typeof arguments[1]&&(n=e,e=null),n=s(n||r);var u=F(t),c=u.length;if(!c)return n(null);e||(e=c);var l={},h=0,v=!1,m=[];i(function(){c||n(null,l)}),f(u,function(r){function u(){return h=0)throw new Error("Has cyclic dependencies")}u()?(h++,f[f.length-1](m,l)):i(s)}})},M.retry=function(t,e,n){function r(t,e){for(;u.times;){var n=!(u.times-=1);a.push(function(t,n){return function(r){t(function(t,e){r(!t||n,{err:t,result:e})},e)}}(u.task,n)),!n&&u.interval>0&&a.push(function(t){return function(e){setTimeout(function(){e(null)},t)}}(u.interval))}M.series(a,function(e,n){n=n[n.length-1],(t||u.callback)(n.err,n.result)})}var i=5,o=0,a=[],u={times:i,interval:o},s=arguments.length;if(s<1||s>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return s<=2&&"function"==typeof t&&(n=e,e=t),"function"!=typeof t&&function(t,e){if("number"==typeof e)t.times=parseInt(e,10)||i;else{if("object"!=typeof e)throw new Error("Unsupported argument type for 'times': "+typeof e);t.times=parseInt(e.times,10)||i,t.interval=parseInt(e.interval,10)||o}}(u,t),u.callback=n,u.task=e,u.callback?r():r},M.waterfall=function(t,e){function n(t){return g(function(r,i){if(r)e.apply(null,[r].concat(i));else{var o=t.next();o?i.push(n(o)):i.push(e),C(t).apply(null,i)}})}if(e=s(e||r),!z(t)){var i=new Error("First argument to waterfall must be an array of functions");return e(i)}if(!t.length)return e();n(M.iterator(t))()},M.parallel=function(t,e){j(M.eachOf,t,e)},M.parallelLimit=function(t,e,n){j(b(e),t,n)},M.series=function(t,e){j(M.eachOfSeries,t,e)},M.iterator=function(t){function e(n){function r(){return t.length&&t[n].apply(null,arguments),r.next()}return r.next=function(){return n>>1);n(e,t[o])>=0?r=o:i=o-1}return r}function o(t,e,o,a){if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");if(t.started=!0,z(e)||(e=[e]),0===e.length)return M.setImmediate(function(){t.drain()});f(e,function(e){var u={data:e,priority:o,callback:"function"==typeof a?a:r};t.tasks.splice(i(t.tasks,u,n)+1,0,u),t.tasks.length===t.concurrency&&t.saturated(),M.setImmediate(t.process)})}var a=M.queue(t,e);return a.push=function(t,e,n){o(a,t,e,n)},delete a.unshift,a},M.cargo=function(t,e){return D(t,1,e)},M.log=$("log"),M.dir=$("dir"),M.memoize=function(t,e){var n={},r={},o=Object.prototype.hasOwnProperty;e=e||i;var a=g(function(i){var a=i.pop(),u=e.apply(null,i);o.call(n,u)?M.setImmediate(function(){a.apply(null,n[u])}):o.call(r,u)?r[u].push(a):(r[u]=[a],t.apply(null,i.concat([g(function(t){n[u]=t;var e=r[u];delete r[u];for(var i=0,o=e.length;i1)throw new Error("Tree is unbalanced at node "+this.key);this.left&&this.left.checkBalanceFactors(),this.right&&this.right.checkBalanceFactors()},i.prototype.checkIsAVLT=function(){i.super_.prototype.checkIsBST.call(this),this.checkHeightCorrect(),this.checkBalanceFactors()},r.prototype.checkIsAVLT=function(){this.tree.checkIsAVLT()},i.prototype.rightRotation=function(){var t,e,n,r,i=this,o=this.left;return o?(t=o.right,i.parent?(o.parent=i.parent,i.parent.left===i?i.parent.left=o:i.parent.right=o):o.parent=null,o.right=i,i.parent=o,i.left=t,t&&(t.parent=i),e=o.left?o.left.height:0,n=t?t.height:0,r=i.right?i.right.height:0,i.height=Math.max(n,r)+1,o.height=Math.max(e,i.height)+1,o):this},i.prototype.leftRotation=function(){var t,e,n,r,i=this,o=this.right;return o?(t=o.left,i.parent?(o.parent=i.parent,i.parent.left===i?i.parent.left=o:i.parent.right=o):o.parent=null,o.left=i,i.parent=o,i.right=t,t&&(t.parent=i),e=i.left?i.left.height:0,n=t?t.height:0,r=o.right?o.right.height:0,i.height=Math.max(e,n)+1,o.height=Math.max(r,i.height)+1,o):this},i.prototype.rightTooSmall=function(){return this.balanceFactor()<=1?this:(this.left.balanceFactor()<0&&this.left.leftRotation(),this.rightRotation())},i.prototype.leftTooSmall=function(){return this.balanceFactor()>=-1?this:(this.right.balanceFactor()>0&&this.right.rightRotation(),this.leftRotation())},i.prototype.rebalanceAlongPath=function(t){var e,n,r=this;if(!this.hasOwnProperty("key"))return delete this.height,this;for(n=t.length-1;n>=0;n-=1)t[n].height=1+Math.max(t[n].left?t[n].left.height:0,t[n].right?t[n].right.height:0),t[n].balanceFactor()>1&&(e=t[n].rightTooSmall(),0===n&&(r=e)),t[n].balanceFactor()<-1&&(e=t[n].leftTooSmall(),0===n&&(r=e));return r},i.prototype.insert=function(t,e){var n=[],r=this;if(!this.hasOwnProperty("key"))return this.key=t,this.data.push(e),this.height=1,this;for(;;){if(0===r.compareKeys(r.key,t)){if(r.unique){var i=new Error("Can't insert key "+t+", it violates the unique constraint");throw i.key=t,i.errorType="uniqueViolated",i}return r.data.push(e),this}if(n.push(r),r.compareKeys(t,r.key)<0){if(!r.left){n.push(r.createLeftChild({key:t,value:e}));break}r=r.left}else{if(!r.right){n.push(r.createRightChild({key:t,value:e}));break}r=r.right}}return this.rebalanceAlongPath(n)},r.prototype.insert=function(t,e){var n=this.tree.insert(t,e);n&&(this.tree=n)},i.prototype.delete=function(t,e){var n,r=[],i=this,o=[];if(!this.hasOwnProperty("key"))return this;for(;;){if(0===i.compareKeys(t,i.key))break;if(o.push(i),i.compareKeys(t,i.key)<0){if(!i.left)return this;i=i.left}else{if(!i.right)return this;i=i.right}}if(i.data.length>1&&void 0!==e)return i.data.forEach(function(t){i.checkValueEquality(t,e)||r.push(t)}),i.data=r,this;if(!i.left&&!i.right)return i===this?(delete i.key,i.data=[],delete i.height,this):(i.parent.left===i?i.parent.left=null:i.parent.right=null,this.rebalanceAlongPath(o));if(!i.left||!i.right)return n=i.left?i.left:i.right,i===this?(n.parent=null,n):(i.parent.left===i?(i.parent.left=n,n.parent=i.parent):(i.parent.right=n,n.parent=i.parent),this.rebalanceAlongPath(o));if(o.push(i),!(n=i.left).right)return i.key=n.key,i.data=n.data,i.left=n.left,n.left&&(n.left.parent=i),this.rebalanceAlongPath(o);for(;;){if(!n.right)break;o.push(n),n=n.right}return i.key=n.key,i.data=n.data,n.parent.right=n.left,n.left&&(n.left.parent=n.parent),this.rebalanceAlongPath(o)},r.prototype.delete=function(t,e){var n=this.tree.delete(t,e);n&&(this.tree=n)},["getNumberOfKeys","search","betweenBounds","prettyPrint","executeOnEveryNode"].forEach(function(t){r.prototype[t]=function(){return this.tree[t].apply(this.tree,arguments)}}),e.exports=r},{"./bst":12,"./customUtils":13,underscore:15,util:20}],12:[function(t,e,n){function r(t){t=t||{},this.left=null,this.right=null,this.parent=void 0!==t.parent?t.parent:null,t.hasOwnProperty("key")&&(this.key=t.key),this.data=t.hasOwnProperty("value")?[t.value]:[],this.unique=t.unique||!1,this.compareKeys=t.compareKeys||o.defaultCompareKeysFunction,this.checkValueEquality=t.checkValueEquality||o.defaultCheckValueEquality}function i(t,e){var n;for(n=0;n=0)throw new Error("Tree with root "+t.key+" is not a binary search tree")}),this.left.checkNodeOrdering()),this.right&&(this.right.checkAllNodesFullfillCondition(function(e){if(t.compareKeys(e,t.key)<=0)throw new Error("Tree with root "+t.key+" is not a binary search tree")}),this.right.checkNodeOrdering()))},r.prototype.checkInternalPointers=function(){if(this.left){if(this.left.parent!==this)throw new Error("Parent pointer broken for key "+this.key);this.left.checkInternalPointers()}if(this.right){if(this.right.parent!==this)throw new Error("Parent pointer broken for key "+this.key);this.right.checkInternalPointers()}},r.prototype.checkIsBST=function(){if(this.checkNodeOrdering(),this.checkInternalPointers(),this.parent)throw new Error("The root shouldn't have a parent")},r.prototype.getNumberOfKeys=function(){var t;return this.hasOwnProperty("key")?(t=1,this.left&&(t+=this.left.getNumberOfKeys()),this.right&&(t+=this.right.getNumberOfKeys()),t):0},r.prototype.createSimilar=function(t){return t=t||{},t.unique=this.unique,t.compareKeys=this.compareKeys,t.checkValueEquality=this.checkValueEquality,new this.constructor(t)},r.prototype.createLeftChild=function(t){var e=this.createSimilar(t);return e.parent=this,this.left=e,e},r.prototype.createRightChild=function(t){var e=this.createSimilar(t);return e.parent=this,this.right=e,e},r.prototype.insert=function(t,e){if(!this.hasOwnProperty("key"))return this.key=t,void this.data.push(e);if(0!==this.compareKeys(this.key,t))this.compareKeys(t,this.key)<0?this.left?this.left.insert(t,e):this.createLeftChild({key:t,value:e}):this.right?this.right.insert(t,e):this.createRightChild({key:t,value:e});else{if(this.unique){var n=new Error("Can't insert key "+t+", it violates the unique constraint");throw n.key=t,n.errorType="uniqueViolated",n}this.data.push(e)}},r.prototype.search=function(t){return this.hasOwnProperty("key")?0===this.compareKeys(this.key,t)?this.data:this.compareKeys(t,this.key)<0?this.left?this.left.search(t):[]:this.right?this.right.search(t):[]:[]},r.prototype.getLowerBoundMatcher=function(t){var e=this;return t.hasOwnProperty("$gt")||t.hasOwnProperty("$gte")?t.hasOwnProperty("$gt")&&t.hasOwnProperty("$gte")?0===e.compareKeys(t.$gte,t.$gt)?function(n){return e.compareKeys(n,t.$gt)>0}:e.compareKeys(t.$gte,t.$gt)>0?function(n){return e.compareKeys(n,t.$gte)>=0}:function(n){return e.compareKeys(n,t.$gt)>0}:t.hasOwnProperty("$gt")?function(n){return e.compareKeys(n,t.$gt)>0}:function(n){return e.compareKeys(n,t.$gte)>=0}:function(){return!0}},r.prototype.getUpperBoundMatcher=function(t){var e=this;return t.hasOwnProperty("$lt")||t.hasOwnProperty("$lte")?t.hasOwnProperty("$lt")&&t.hasOwnProperty("$lte")?0===e.compareKeys(t.$lte,t.$lt)?function(n){return e.compareKeys(n,t.$lt)<0}:e.compareKeys(t.$lte,t.$lt)<0?function(n){return e.compareKeys(n,t.$lte)<=0}:function(n){return e.compareKeys(n,t.$lt)<0}:t.hasOwnProperty("$lt")?function(n){return e.compareKeys(n,t.$lt)<0}:function(n){return e.compareKeys(n,t.$lte)<=0}:function(){return!0}},r.prototype.betweenBounds=function(t,e,n){var r=[];return this.hasOwnProperty("key")?(e=e||this.getLowerBoundMatcher(t),n=n||this.getUpperBoundMatcher(t),e(this.key)&&this.left&&i(r,this.left.betweenBounds(t,e,n)),e(this.key)&&n(this.key)&&i(r,this.data),n(this.key)&&this.right&&i(r,this.right.betweenBounds(t,e,n)),r):[]},r.prototype.deleteIfLeaf=function(){return!this.left&&!this.right&&(this.parent?(this.parent.left===this?this.parent.left=null:this.parent.right=null,!0):(delete this.key,this.data=[],!0))},r.prototype.deleteIfOnlyOneChild=function(){var t;return this.left&&!this.right&&(t=this.left),!this.left&&this.right&&(t=this.right),!!t&&(this.parent?(this.parent.left===this?(this.parent.left=t,t.parent=this.parent):(this.parent.right=t,t.parent=this.parent),!0):(this.key=t.key,this.data=t.data,this.left=null,t.left&&(this.left=t.left,t.left.parent=this),this.right=null,t.right&&(this.right=t.right,t.right.parent=this),!0))},r.prototype.delete=function(t,e){var n,r=[],i=this;if(this.hasOwnProperty("key"))if(this.compareKeys(t,this.key)<0)this.left&&this.left.delete(t,e);else if(this.compareKeys(t,this.key)>0)this.right&&this.right.delete(t,e);else if(0!==!this.compareKeys(t,this.key))return this.data.length>1&&void 0!==e?(this.data.forEach(function(t){i.checkValueEquality(t,e)||r.push(t)}),void(i.data=r)):void(this.deleteIfLeaf()||this.deleteIfOnlyOneChild()||(Math.random()>=.5?(n=this.left.getMaxKeyDescendant(),this.key=n.key,this.data=n.data,this===n.parent?(this.left=n.left,n.left&&(n.left.parent=n.parent)):(n.parent.right=n.left,n.left&&(n.left.parent=n.parent))):(n=this.right.getMinKeyDescendant(),this.key=n.key,this.data=n.data,this===n.parent?(this.right=n.right,n.right&&(n.right.parent=n.parent)):(n.parent.left=n.right,n.right&&(n.right.parent=n.parent)))))},r.prototype.executeOnEveryNode=function(t){this.left&&this.left.executeOnEveryNode(t),t(this),this.right&&this.right.executeOnEveryNode(t)},r.prototype.prettyPrint=function(t,e){e=e||"",console.log(e+"* "+this.key),t&&console.log(e+"* "+this.data),(this.left||this.right)&&(this.left?this.left.prettyPrint(t,e+" "):console.log(e+" *"),this.right?this.right.prettyPrint(t,e+" "):console.log(e+" *"))},e.exports=r},{"./customUtils":13}],13:[function(t,e,n){function r(t){var e,n;return 0===t?[]:1===t?[0]:(e=r(t-1),n=Math.floor(Math.random()*t),e.splice(n,0,t-1),e)}e.exports.getRandomArray=r,e.exports.defaultCompareKeysFunction=function(t,e){if(te)return 1;if(t===e)return 0;var n=new Error("Couldn't compare elements");throw n.a=t,n.b=e,n},e.exports.defaultCheckValueEquality=function(t,e){return t===e}},{}],14:[function(t,e,n){(function(r){!function(t){if("object"==typeof n&&void 0!==e)e.exports=t();else{("undefined"!=typeof window?window:void 0!==r?r:"undefined"!=typeof self?self:this).localforage=t()}}(function(){return function e(n,r,i){function o(u,s){if(!r[u]){if(!n[u]){var c="function"==typeof t&&t;if(!s&&c)return c(u,!0);if(a)return a(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var l=r[u]={exports:{}};n[u][0].call(l.exports,function(t){var e=n[u][1][t];return o(e||t)},l,l.exports,e,n,r,i)}return r[u].exports}for(var a="function"==typeof t&&t,u=0;u=43)}}).catch(function(){return!1})}function c(t){return"boolean"==typeof j?D.resolve(j):s(t).then(function(t){return j=t})}function f(t){var e=I[t.name],n={};n.promise=new D(function(t){n.resolve=t}),e.deferredOperations.push(n),e.dbReady?e.dbReady=e.dbReady.then(function(){return n.promise}):e.dbReady=n.promise}function l(t){var e=I[t.name].deferredOperations.pop();e&&e.resolve()}function h(t,e){return new D(function(n,r){if(t.db){if(!e)return n(t.db);f(t),t.db.close()}var i=[t.name];e&&i.push(t.version);var o=S.open.apply(S,i);e&&(o.onupgradeneeded=function(e){var n=o.result;try{n.createObjectStore(t.storeName),e.oldVersion<=1&&n.createObjectStore($)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+t.name+'" has been upgraded from version '+e.oldVersion+" to version "+e.newVersion+', but the storage "'+t.storeName+'" already exists.')}}),o.onerror=function(t){t.preventDefault(),r(o.error)},o.onsuccess=function(){n(o.result),l(t)}})}function p(t){return h(t,!1)}function d(t){return h(t,!0)}function y(t,e){if(!t.db)return!0;var n=!t.db.objectStoreNames.contains(t.storeName),r=t.versiont.db.version;if(r&&(t.version!==e&&console.warn('The database "'+t.name+"\" can't be downgraded from version "+t.db.version+" to version "+t.version+"."),t.version=t.db.version),i||n){if(n){var o=t.db.version+1;o>t.version&&(t.version=o)}return!0}return!1}function v(t){return new D(function(e,n){var r=new FileReader;r.onerror=n,r.onloadend=function(n){var r=btoa(n.target.result||"");e({__local_forage_encoded_blob:!0,data:r,type:t.type})},r.readAsBinaryString(t)})}function g(t){return i([u(atob(t.data))],{type:t.type})}function m(t){return t&&t.__local_forage_encoded_blob}function b(t){var e=this,n=e._initReady().then(function(){var t=I[e._dbInfo.name];if(t&&t.dbReady)return t.dbReady});return a(n,t,t),n}function w(t){var e,n,r,i,o,a=.75*t.length,u=t.length,s=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);var c=new ArrayBuffer(a),f=new Uint8Array(c);for(e=0;e>4,f[s++]=(15&r)<<4|i>>2,f[s++]=(3&i)<<6|63&o;return c}function k(t){var e,n=new Uint8Array(t),r="";for(e=0;e>2],r+=C[(3&n[e])<<4|n[e+1]>>4],r+=C[(15&n[e+1])<<2|n[e+2]>>6],r+=C[63&n[e+2]];return n.length%3==2?r=r.substring(0,r.length-1)+"=":n.length%3==1&&(r=r.substring(0,r.length-2)+"=="),r}function _(t,e,n,r){var i=this;"string"!=typeof t&&(console.warn(t+" used as a key, but it is not a string."),t=String(t));var a=new D(function(o,a){i.ready().then(function(){void 0===e&&(e=null);var u=e,s=i._dbInfo;s.serializer.serialize(e,function(e,c){c?a(c):s.db.transaction(function(n){n.executeSql("INSERT OR REPLACE INTO "+s.storeName+" (key, value) VALUES (?, ?)",[t,e],function(){o(u)},function(t,e){a(e)})},function(e){if(e.code===e.QUOTA_ERR){if(r>0)return void o(_.apply(i,[t,u,n,r-1]));a(e)}})})}).catch(a)});return o(a,n),a}function x(t,e){t[e]=function(){var n=arguments;return t.ready().then(function(){return t[e].apply(t,n)})}}function E(){for(var t=1;t=0;n--){var r=localStorage.key(n);0===r.indexOf(t)&&localStorage.removeItem(r)}});return o(n,t),n},length:function(t){var e=this.keys().then(function(t){return t.length});return o(e,t),e},key:function(t,e){var n=this,r=n.ready().then(function(){var e,r=n._dbInfo;try{e=localStorage.key(t)}catch(t){e=null}return e&&(e=e.substring(r.keyPrefix.length)),e});return o(r,e),r},keys:function(t){var e=this,n=e.ready().then(function(){for(var t=e._dbInfo,n=localStorage.length,r=[],i=0;i2;if(null==t&&(t=[]),y&&t.reduce===y)return r&&(e=O.bind(e,r)),i?t.reduce(e,n):t.reduce(e);if(A(t,function(t,o,a){i?n=e.call(r,n,t,o,a):(n=t,i=!0)}),!i)throw new TypeError(S);return n},O.reduceRight=O.foldr=function(t,e,n,r){var i=arguments.length>2;if(null==t&&(t=[]),v&&t.reduceRight===v)return r&&(e=O.bind(e,r)),i?t.reduceRight(e,n):t.reduceRight(e);var o=t.length;if(o!==+o){var a=O.keys(t);o=a.length}if(A(t,function(u,s,c){s=a?a[--o]:--o,i?n=e.call(r,n,t[s],s,c):(n=t[s],i=!0)}),!i)throw new TypeError(S);return n},O.find=O.detect=function(t,e,n){var r;return j(t,function(t,i,o){if(e.call(n,t,i,o))return r=t,!0}),r},O.filter=O.select=function(t,e,n){var r=[];return null==t?r:g&&t.filter===g?t.filter(e,n):(A(t,function(t,i,o){e.call(n,t,i,o)&&(r[r.length]=t)}),r)},O.reject=function(t,e,n){return O.filter(t,function(t,r,i){return!e.call(n,t,r,i)},n)},O.every=O.all=function(t,e,n){e||(e=O.identity);var r=!0;return null==t?r:m&&t.every===m?t.every(e,n):(A(t,function(t,o,a){if(!(r=r&&e.call(n,t,o,a)))return i}),!!r)};var j=O.some=O.any=function(t,e,n){e||(e=O.identity);var r=!1;return null==t?r:b&&t.some===b?t.some(e,n):(A(t,function(t,o,a){if(r||(r=e.call(n,t,o,a)))return i}),!!r)};O.contains=O.include=function(t,e){return null!=t&&(w&&t.indexOf===w?-1!=t.indexOf(e):j(t,function(t){return t===e}))},O.invoke=function(t,e){var n=c.call(arguments,2),r=O.isFunction(e);return O.map(t,function(t){return(r?e:t[e]).apply(t,n)})},O.pluck=function(t,e){return O.map(t,function(t){return t[e]})},O.where=function(t,e,n){return O.isEmpty(e)?n?null:[]:O[n?"find":"filter"](t,function(t){for(var n in e)if(e[n]!==t[n])return!1;return!0})},O.findWhere=function(t,e){return O.where(t,e,!0)},O.max=function(t,e,n){if(!e&&O.isArray(t)&&t[0]===+t[0]&&t.length<65535)return Math.max.apply(Math,t);if(!e&&O.isEmpty(t))return-1/0;var r={computed:-1/0,value:-1/0};return A(t,function(t,i,o){var a=e?e.call(n,t,i,o):t;a>=r.computed&&(r={value:t,computed:a})}),r.value},O.min=function(t,e,n){if(!e&&O.isArray(t)&&t[0]===+t[0]&&t.length<65535)return Math.min.apply(Math,t);if(!e&&O.isEmpty(t))return 1/0;var r={computed:1/0,value:1/0};return A(t,function(t,i,o){var a=e?e.call(n,t,i,o):t;ar||void 0===n)return 1;if(n>>1;n.call(r,t[u])=0})})},O.difference=function(t){var e=f.apply(o,c.call(arguments,1));return O.filter(t,function(t){return!O.contains(e,t)})},O.zip=function(){for(var t=c.call(arguments),e=O.max(O.pluck(t,"length")),n=new Array(e),r=0;r=0;n--)e=[t[n].apply(this,e)];return e[0]}},O.after=function(t,e){return t<=0?e():function(){if(--t<1)return e.apply(this,arguments)}},O.keys=x||function(t){if(t!==Object(t))throw new TypeError("Invalid object");var e=[];for(var n in t)O.has(t,n)&&(e[e.length]=n);return e},O.values=function(t){var e=[];for(var n in t)O.has(t,n)&&e.push(t[n]);return e},O.pairs=function(t){var e=[];for(var n in t)O.has(t,n)&&e.push([n,t[n]]);return e},O.invert=function(t){var e={};for(var n in t)O.has(t,n)&&(e[t[n]]=n);return e},O.functions=O.methods=function(t){var e=[];for(var n in t)O.isFunction(t[n])&&e.push(n);return e.sort()},O.extend=function(t){return A(c.call(arguments,1),function(e){if(e)for(var n in e)t[n]=e[n]}),t},O.pick=function(t){var e={},n=f.apply(o,c.call(arguments,1));return A(n,function(n){n in t&&(e[n]=t[n])}),e},O.omit=function(t){var e={},n=f.apply(o,c.call(arguments,1));for(var r in t)O.contains(n,r)||(e[r]=t[r]);return e},O.defaults=function(t){return A(c.call(arguments,1),function(e){if(e)for(var n in e)null==t[n]&&(t[n]=e[n])}),t},O.clone=function(t){return O.isObject(t)?O.isArray(t)?t.slice():O.extend({},t):t},O.tap=function(t,e){return e(t),t};var N=function(t,e,n,r){if(t===e)return 0!==t||1/t==1/e;if(null==t||null==e)return t===e;t instanceof O&&(t=t._wrapped),e instanceof O&&(e=e._wrapped);var i=l.call(t);if(i!=l.call(e))return!1;switch(i){case"[object String]":return t==String(e);case"[object Number]":return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case"[object Date]":case"[object Boolean]":return+t==+e;case"[object RegExp]":return t.source==e.source&&t.global==e.global&&t.multiline==e.multiline&&t.ignoreCase==e.ignoreCase}if("object"!=typeof t||"object"!=typeof e)return!1;for(var o=n.length;o--;)if(n[o]==t)return r[o]==e;n.push(t),r.push(e);var a=0,u=!0;if("[object Array]"==i){if(a=t.length,u=a==e.length)for(;a--&&(u=N(t[a],e[a],n,r)););}else{var s=t.constructor,c=e.constructor;if(s!==c&&!(O.isFunction(s)&&s instanceof s&&O.isFunction(c)&&c instanceof c))return!1;for(var f in t)if(O.has(t,f)&&(a++,!(u=O.has(e,f)&&N(t[f],e[f],n,r))))break;if(u){for(f in e)if(O.has(e,f)&&!a--)break;u=!a}}return n.pop(),r.pop(),u};O.isEqual=function(t,e){return N(t,e,[],[])},O.isEmpty=function(t){if(null==t)return!0;if(O.isArray(t)||O.isString(t))return 0===t.length;for(var e in t)if(O.has(t,e))return!1;return!0},O.isElement=function(t){return!(!t||1!==t.nodeType)},O.isArray=_||function(t){return"[object Array]"==l.call(t)},O.isObject=function(t){return t===Object(t)},A(["Arguments","Function","String","Number","Date","RegExp"],function(t){O["is"+t]=function(e){return l.call(e)=="[object "+t+"]"}}),O.isArguments(arguments)||(O.isArguments=function(t){return!(!t||!O.has(t,"callee"))}),"function"!=typeof/./&&(O.isFunction=function(t){return"function"==typeof t}),O.isFinite=function(t){return isFinite(t)&&!isNaN(parseFloat(t))},O.isNaN=function(t){return O.isNumber(t)&&t!=+t},O.isBoolean=function(t){return!0===t||!1===t||"[object Boolean]"==l.call(t)},O.isNull=function(t){return null===t},O.isUndefined=function(t){return void 0===t},O.has=function(t,e){return h.call(t,e)},O.noConflict=function(){return t._=r,this},O.identity=function(t){return t},O.times=function(t,e,n){for(var r=Array(t),i=0;i":">",'"':""","'":"'","/":"/"}};T.unescape=O.invert(T.escape);var C={escape:new RegExp("["+O.keys(T.escape).join("")+"]","g"),unescape:new RegExp("("+O.keys(T.unescape).join("|")+")","g")};O.each(["escape","unescape"],function(t){O[t]=function(e){return null==e?"":(""+e).replace(C[t],function(e){return T[t][e]})}}),O.result=function(t,e){if(null==t)return null;var n=t[e];return O.isFunction(n)?n.call(t):n},O.mixin=function(t){A(O.functions(t),function(e){var n=O[e]=t[e];O.prototype[e]=function(){var t=[this._wrapped];return s.apply(t,arguments),z.call(this,n.apply(O,t))}})};var L=0;O.uniqueId=function(t){var e=++L+"";return t?t+e:e},O.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var M=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},R=/\\|'|\r|\n|\t|\u2028|\u2029/g;O.template=function(t,e,n){var r;n=O.defaults({},n,O.templateSettings);var i=new RegExp([(n.escape||M).source,(n.interpolate||M).source,(n.evaluate||M).source].join("|")+"|$","g"),o=0,a="__p+='";t.replace(i,function(e,n,r,i,u){return a+=t.slice(o,u).replace(R,function(t){return"\\"+B[t]}),n&&(a+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'"),r&&(a+="'+\n((__t=("+r+"))==null?'':__t)+\n'"),i&&(a+="';\n"+i+"\n__p+='"),o=u+e.length,e}),a+="';\n",n.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{r=new Function(n.variable||"obj","_",a)}catch(t){throw t.source=a,t}if(e)return r(e,O);var u=function(t){return r.call(this,t,O)};return u.source="function("+(n.variable||"obj")+"){\n"+a+"}",u},O.chain=function(t){return O(t).chain()};var z=function(t){return this._chain?O(t).chain():t};O.mixin(O),A(["pop","push","reverse","shift","sort","splice","unshift"],function(t){var e=o[t];O.prototype[t]=function(){var n=this._wrapped;return e.apply(n,arguments),"shift"!=t&&"splice"!=t||0!==n.length||delete n[0],z.call(this,n)}}),A(["concat","join","slice"],function(t){var e=o[t];O.prototype[t]=function(){return z.call(this,e.apply(this._wrapped,arguments))}}),O.extend(O.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this)},{}],16:[function(t,e,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function o(t){return"number"==typeof t}function a(t){return"object"==typeof t&&null!==t}function u(t){return void 0===t}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!o(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,n,r,o,s,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var f=new Error('Uncaught, unspecified "error" event. ('+e+")");throw f.context=e,f}if(n=this._events[t],u(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),r=(c=n.slice()).length,s=0;s0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var r=!1;return n.listener=e,this.on(t,n),this},r.prototype.removeListener=function(t,e){var n,r,o,u;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],o=n.length,r=-1,n===e||i(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(a(n)){for(u=o;u-- >0;)if(n[u]===e||n[u].listener&&n[u].listener===e){r=u;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],i(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){return this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},{}],17:[function(t,e,n){function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function o(t){if(l===setTimeout)return setTimeout(t,0);if((l===r||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}function a(t){if(h===clearTimeout)return clearTimeout(t);if((h===i||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(t);try{return h(t)}catch(e){try{return h.call(null,t)}catch(e){return h.call(this,t)}}}function u(){v&&d&&(v=!1,d.length?y=d.concat(y):g=-1,y.length&&s())}function s(){if(!v){var t=o(u);v=!0;for(var e=y.length;e;){for(d=y,y=[];++g1)for(var n=1;n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),y(e)?r.showHidden=e:e&&n._extend(r,e),b(r.showHidden)&&(r.showHidden=!1),b(r.depth)&&(r.depth=2),b(r.colors)&&(r.colors=!1),b(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),s(r,t,r.depth)}function o(t,e){var n=i.styles[e];return n?"["+i.colors[n][0]+"m"+t+"["+i.colors[n][1]+"m":t}function a(t,e){return t}function u(t){var e={};return t.forEach(function(t,n){e[t]=!0}),e}function s(t,e,r){if(t.customInspect&&e&&E(e.inspect)&&e.inspect!==n.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(r,t);return m(i)||(i=s(t,i,r)),i}var o=c(t,e);if(o)return o;var a=Object.keys(e),y=u(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(e)),x(e)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(e);if(0===a.length){if(E(e)){var v=e.name?": "+e.name:"";return t.stylize("[Function"+v+"]","special")}if(w(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(_(e))return t.stylize(Date.prototype.toString.call(e),"date");if(x(e))return f(e)}var g="",b=!1,k=["{","}"];if(d(e)&&(b=!0,k=["[","]"]),E(e)&&(g=" [Function"+(e.name?": "+e.name:"")+"]"),w(e)&&(g=" "+RegExp.prototype.toString.call(e)),_(e)&&(g=" "+Date.prototype.toUTCString.call(e)),x(e)&&(g=" "+f(e)),0===a.length&&(!b||0==e.length))return k[0]+g+k[1];if(r<0)return w(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);var O;return O=b?l(t,e,r,y,a):a.map(function(n){return h(t,e,r,y,n,b)}),t.seen.pop(),p(O,g,k)}function c(t,e){if(b(e))return t.stylize("undefined","undefined");if(m(e)){var n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return g(e)?t.stylize(""+e,"number"):y(e)?t.stylize(""+e,"boolean"):v(e)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function l(t,e,n,r,i){for(var o=[],a=0,u=e.length;a-1&&(u=o?u.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+u.split("\n").map(function(t){return" "+t}).join("\n")):u=t.stylize("[Circular]","special")),b(a)){if(o&&i.match(/^\d+$/))return u;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}function p(t,e,n){var r=0;return t.reduce(function(t,e){return r++,e.indexOf("\n")>=0&&r++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}function d(t){return Array.isArray(t)}function y(t){return"boolean"==typeof t}function v(t){return null===t}function g(t){return"number"==typeof t}function m(t){return"string"==typeof t}function b(t){return void 0===t}function w(t){return k(t)&&"[object RegExp]"===O(t)}function k(t){return"object"==typeof t&&null!==t}function _(t){return k(t)&&"[object Date]"===O(t)}function x(t){return k(t)&&("[object Error]"===O(t)||t instanceof Error)}function E(t){return"function"==typeof t}function O(t){return Object.prototype.toString.call(t)}function A(t){return t<10?"0"+t.toString(10):t.toString(10)}function S(){var t=new Date,e=[A(t.getHours()),A(t.getMinutes()),A(t.getSeconds())].join(":");return[t.getDate(),N[t.getMonth()],e].join(" ")}function j(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var I=/%[sdj%]/g;n.format=function(t){if(!m(t)){for(var e=[],n=0;n=o)return t;switch(t){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return t}}),u=r[n];nf)f+=1;else if(s.push(t[i]),c+=1,l._limit&&l._limit<=c)break}catch(e){return p(e)}if(l._sort){a=Object.keys(l._sort);var o=[];for(i=0;i>18&63]+o[i>>12&63]+o[i>>6&63]+o[63&i];switch(a){case 1:t=e[e.length-1],u+=o[t>>2],u+=o[t<<4&63],u+="==";break;case 2:t=(e[e.length-2]<<8)+e[e.length-1],u+=o[t>>10],u+=o[t>>4&63],u+=o[t<<2&63],u+="="}return u}(function(e){for(var t,n=new Array(e),r=0;r>>((3&r)<<3)&255;return n}(Math.ceil(Math.max(8,2*e)))).replace(/[+\/]/g,"").slice(0,e)}},{}],3:[function(e,t,n){var r=e("util"),i=e("events"),y=e("async"),v=e("underscore"),o=e("./customUtils"),g=e("./model"),a=e("./executor"),u=e("./indexes"),s=e("./persistence"),m=e("./cursor");function c(e){if(!(this instanceof c))return new c(e);i.call(this);var t=(e=e||{}).filename;this.inMemoryOnly=e.inMemoryOnly||!1,this.autoload=e.autoload||!1,this.timestampData=e.timestampData||!1,"function"==typeof e.idGenerator&&(this._idGenerator=e.idGenerator),t&&"string"==typeof t&&0!==t.length?this.filename=t:(this.filename=null,this.inMemoryOnly=!0),this.compareStrings=e.compareStrings,this.persistence=new s({db:this,afterSerialization:e.afterSerialization,beforeDeserialization:e.beforeDeserialization,corruptAlertThreshold:e.corruptAlertThreshold,storage:e.storage}),this.executor=new a,this.inMemoryOnly&&(this.executor.ready=!0),this.indexes={},this.indexes._id=new u({fieldName:"_id",unique:!0}),this.ttlIndexes={},this.autoload&&this.load(e.onload)}r.inherits(c,i),i.call(c),Object.keys(i.prototype).forEach(function(e){"function"==typeof i.prototype[e]&&(c[e]=i.prototype[e].bind(c))}),c.prototype.loadDatabase=c.prototype.load=function(e){var t=this,n=e||function(e){if(e)throw e};this.executor.push({this:this.persistence,fn:this.persistence.loadDatabase,arguments:[function(e){y.setImmediate(function(){e||(0t[e].getTime()+1e3*u.ttlIndexes[e]&&(n=!1)}),n?i.push(t):r.push(t._id)}),y.eachSeries(r,function(e,t){u._remove({_id:e},{},function(e){return e?a(e):t()})},function(e){return a(null,i)})}])},c.prototype._insert=function(e,t){var n,o=this,a=t||function(){},r=function(t,n){var r=this,i=arguments;y.setImmediate(function(){if(!t){var e=Array.isArray(n)?n:[n];0e[t]&&(e[t]=n)},o.$min=function(e,t,n){void 0===e[t]?e[t]=n:nthis.corruptAlertThreshold)throw new Error("More than "+Math.floor(100*this.corruptAlertThreshold)+"% of the data file is corrupt, the wrong beforeDeserialization hook may be used. Cautiously refusing to start NestDB to prevent dataloss");return Object.keys(r).forEach(function(e){i.push(r[e])}),{data:i,indexes:o}},u.prototype.loadDatabase=function(e){var t=e||function(){},i=this;if(i.db.resetIndexes(),i.inMemoryOnly)return t(null);r.waterfall([function(r){i.storage.init(i.filename,function(e){if(e)return r(e);i.storage.read(i.filename,function(e,t){if(e)return r(e);try{var n=i.treatRawData(t)}catch(e){return r(e)}Object.keys(n.indexes).forEach(function(e){i.db.indexes[e]=new a(n.indexes[e])});try{i.db.resetIndexes(n.data)}catch(e){return i.db.resetIndexes(),r(e)}i.db.persistence.persistCachedDatabase(r)})})}],function(e){return e?t(e):(i.db.executor.processBuffer(),t(null))})},u.prototype.destroyDatabase=function(e){var t=e||function(){};if(this.db.resetIndexes(),this.inMemoryOnly)return t(null);this.storage.remove(this.filename,t)},t.exports=u},{"./customUtils":2,"./indexes":5,"./model":6,"./storage":8,async:9}],8:[function(e,t,n){var o=e("localforage"),r={};o.config({name:"NestDB",storeName:"nestdbdata"}),r.write=function(e,t,n){o.setItem(e,t,n)},r.append=function(n,r,i){o.getItem(n,function(e,t){if(e)return i(e);t=t||"",t+=r,o.setItem(n,t,i)})},r.read=function(e,n){o.getItem(e,function(e,t){if(e)return n(e);n(null,t||"")})},r.remove=function(e,t){o.removeItem(e,t)},r.init=function(e,t){return t(null)},t.exports.init=r.init,t.exports.read=r.read,t.exports.write=r.write,t.exports.append=r.append,t.exports.remove=r.remove},{localforage:14}],9:[function(e,P,t){(function(F,B,z){!function(){var e,v={};function g(){}function s(e){return e}function t(e){return!!e}function n(e){return!e}var r="object"==typeof self&&self.self===self&&self||"object"==typeof B&&B.global===B&&B||this;function f(e){return function(){if(null===e)throw new Error("Callback was already called.");e.apply(this,arguments),e=null}}function m(e){return function(){null!==e&&(e.apply(this,arguments),e=null)}}null!=r&&(e=r.async),v.noConflict=function(){return r.async=e,v};var i=Object.prototype.toString,b=Array.isArray||function(e){return"[object Array]"===i.call(e)};function a(e){return b(e)||"number"==typeof e.length&&0<=e.length&&e.length%1==0}function w(e,t){for(var n=-1,r=e.length;++n>>1);0<=n(t,e[o])?r=o:i=o-1}return r}(n.tasks,t,o)+1,0,t),n.tasks.length===n.concurrency&&n.saturated(),v.setImmediate(n.process)})}(r,e,t,n)},delete r.unshift,r},v.cargo=function(e,t){return T(e,1,t)},v.log=C("log"),v.dir=C("dir"),v.memoize=function(n,r){var o={},a={},u=Object.prototype.hasOwnProperty;r=r||s;var e=x(function(e){var t=e.pop(),i=r.apply(null,e);u.call(o,i)?v.setImmediate(function(){t.apply(null,o[i])}):u.call(a,i)?a[i].push(t):(a[i]=[t],n.apply(null,e.concat([x(function(e){o[i]=e;var t=a[i];delete a[i];for(var n=0,r=t.length;ne.db.version;if(r&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),i||n){if(n){var o=e.db.version+1;o>e.version&&(e.version=o)}return!0}return!1}function O(e){return a([function(e){for(var t=e.length,n=new ArrayBuffer(t),r=new Uint8Array(n),i=0;i>4,f[s++]=(15&r)<<4|i>>2,f[s++]=(3&i)<<6|63&o;return c}function B(e){var t,n=new Uint8Array(e),r="";for(t=0;t>2],r+=D[(3&n[t])<<4|n[t+1]>>4],r+=D[(15&n[t+1])<<2|n[t+2]>>6],r+=D[63&n[t+2]];return n.length%3==2?r=r.substring(0,r.length-1)+"=":n.length%3==1&&(r=r.substring(0,r.length-2)+"=="),r}var z={serialize:function(t,n){var e="";if(t&&(e=L.call(t)),t&&("[object ArrayBuffer]"===e||t.buffer&&"[object ArrayBuffer]"===L.call(t.buffer))){var r,i=N;t instanceof ArrayBuffer?(r=t,i+=C):(r=t.buffer,"[object Int8Array]"===e?i+="si08":"[object Uint8Array]"===e?i+="ui08":"[object Uint8ClampedArray]"===e?i+="uic8":"[object Int16Array]"===e?i+="si16":"[object Uint16Array]"===e?i+="ur16":"[object Int32Array]"===e?i+="si32":"[object Uint32Array]"===e?i+="ui32":"[object Float32Array]"===e?i+="fl32":"[object Float64Array]"===e?i+="fl64":n(new Error("Failed to get type for BinaryArray"))),n(i+B(r))}else if("[object Blob]"===e){var o=new FileReader;o.onload=function(){var e="~~local_forage_type~"+t.type+"~"+B(this.result);n(N+M+e)},o.readAsArrayBuffer(t)}else try{n(JSON.stringify(t))}catch(e){console.error("Couldn't convert value into a JSON string: ",t),n(null,e)}},deserialize:function(e){if(e.substring(0,T)!==N)return JSON.parse(e);var t,n=e.substring(R),r=e.substring(T,R);if(r===M&&$.test(n)){var i=n.match($);t=i[1],n=n.substring(i[0].length)}var o=F(n);switch(r){case C:return o;case M:return a([o],{type:t});case"si08":return new Int8Array(o);case"ui08":return new Uint8Array(o);case"uic8":return new Uint8ClampedArray(o);case"si16":return new Int16Array(o);case"ur16":return new Uint16Array(o);case"si32":return new Int32Array(o);case"ui32":return new Uint32Array(o);case"fl32":return new Float32Array(o);case"fl64":return new Float64Array(o);default:throw new Error("Unkown type: "+r)}},stringToBuffer:F,bufferToString:B};function P(e,t,n,r){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,r)}function q(e,r,i,o,a,u){e.executeSql(i,o,a,function(e,n){n.code===n.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[r.storeName],function(e,t){t.rows.length?u(e,n):P(e,r,function(){e.executeSql(i,o,a,u)},u)},u):u(e,n)},u)}var K={_driver:"webSQLStorage",_initStorage:function(e){var r=this,i={db:null};if(e)for(var t in e)i[t]="string"!=typeof e[t]?e[t].toString():e[t];var n=new l(function(t,n){try{i.db=openDatabase(i.name,String(i.version),i.description,i.size)}catch(e){return n(e)}i.db.transaction(function(e){P(e,i,function(){r._dbInfo=i,t()},function(e,t){n(t)})},n)});return i.serializer=z,n},_support:"function"==typeof openDatabase,iterate:function(c,e){var t=this,n=new l(function(s,n){t.ready().then(function(){var u=t._dbInfo;u.db.transaction(function(e){q(e,u,"SELECT * FROM "+u.storeName,[],function(e,t){for(var n=t.rows,r=n.length,i=0;i '__WebKitDatabaseInfoTable__'",[],function(e,t){for(var n=[],r=0;r=a.computed&&(a={value:e,computed:r})}),a.value},x.min=function(e,i,o){if(!i&&x.isArray(e)&&e[0]===+e[0]&&e.length<65535)return Math.min.apply(Math,e);if(!i&&x.isEmpty(e))return 1/0;var a={computed:1/0,value:1/0};return E(e,function(e,t,n){var r=i?i.call(o,e,t,n):e;r>>1;n.call(r,e[u])":">",'"':""","'":"'","/":"/"}};$.unescape=x.invert($.escape);var N={escape:new RegExp("["+x.keys($.escape).join("")+"]","g"),unescape:new RegExp("("+x.keys($.unescape).join("|")+")","g")};x.each(["escape","unescape"],function(t){x[t]=function(e){return null==e?"":(""+e).replace(N[t],function(e){return $[t][e]})}}),x.result=function(e,t){if(null==e)return null;var n=e[t];return x.isFunction(n)?n.call(e):n},x.mixin=function(n){E(x.functions(n),function(e){var t=x[e]=n[e];x.prototype[e]=function(){var e=[this._wrapped];return o.apply(e,arguments),L.call(this,t.apply(x,e))}})};var T=0;x.uniqueId=function(e){var t=++T+"";return e?e+t:t},x.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var C=/(.)^/,M={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},R=/\\|'|\r|\n|\t|\u2028|\u2029/g;x.template=function(o,e,t){var n;t=x.defaults({},t,x.templateSettings);var r=new RegExp([(t.escape||C).source,(t.interpolate||C).source,(t.evaluate||C).source].join("|")+"|$","g"),a=0,u="__p+='";o.replace(r,function(e,t,n,r,i){return u+=o.slice(a,i).replace(R,function(e){return"\\"+M[e]}),t&&(u+="'+\n((__t=("+t+"))==null?'':_.escape(__t))+\n'"),n&&(u+="'+\n((__t=("+n+"))==null?'':__t)+\n'"),r&&(u+="';\n"+r+"\n__p+='"),a=i+e.length,e}),u+="';\n",t.variable||(u="with(obj||{}){\n"+u+"}\n"),u="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+u+"return __p;\n";try{n=new Function(t.variable||"obj","_",u)}catch(e){throw e.source=u,e}if(e)return n(e,x);var i=function(e){return n.call(this,e,x)};return i.source="function("+(t.variable||"obj")+"){\n"+u+"}",i},x.chain=function(e){return x(e).chain()};var L=function(e){return this._chain?x(e).chain():e};x.mixin(x),E(["pop","push","reverse","shift","sort","splice","unshift"],function(t){var n=i[t];x.prototype[t]=function(){var e=this._wrapped;return n.apply(e,arguments),"shift"!=t&&"splice"!=t||0!==e.length||delete e[0],L.call(this,e)}}),E(["concat","join","slice"],function(e){var t=i[e];x.prototype[e]=function(){return L.call(this,t.apply(this._wrapped,arguments))}}),x.extend(x.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this)},{}],16:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function s(e){return"function"==typeof e}function c(e){return"object"==typeof e&&null!==e}function f(e){return void 0===e}((t.exports=r).EventEmitter=r).prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,i,o,a;if(this._events||(this._events={}),"error"===e&&(!this._events.error||c(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}if(f(n=this._events[e]))return!1;if(s(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=Array.prototype.slice.call(arguments,1),n.apply(this,i)}else if(c(n))for(i=Array.prototype.slice.call(arguments,1),r=(a=n.slice()).length,o=0;on&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.once=function(e,t){if(!s(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var n,r,i,o;if(!s(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(i=(n=this._events[e]).length,r=-1,n===t||s(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(c(n)){for(o=i;0