diff --git a/README.md b/README.md index 5fcd42a..8930a3a 100755 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ You can use NestDB as an in-memory only datastore or as a persistent datastore. * `timestampData` (optional, defaults to `false`): timestamp the insertion and last update of all documents, with the fields `createdAt` and `updatedAt`. User-specified values override automatic generation, usually useful for testing. * `autoload` (optional, defaults to `false`): if used, the datastore will automatically be loaded from the datafile upon creation (you don't need to call `load`). Any command issued before load is finished is buffered and will be executed when load is done. * `onload` (optional): if you use autoloading, this is the handler called after the `load`. It takes one `error` argument. If you use autoloading without specifying this handler, and an error happens during load, an error will be thrown. +* `idGenerator` (optional): if set, this function will be used for generating IDs. It takes no arguments and should return a unique string. * `afterSerialization` (optional): hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing datastore to disk. This function takes a string as parameter (one line of an NestDB data file) and outputs the transformed string, **which must absolutely not contain a `\n` character** (or data will be lost). * `beforeDeserialization` (optional): inverse of `afterSerialization`. Make sure to include both and not just one or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NestDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NestDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below). * `corruptAlertThreshold` (optional): between 0 (0%) and 1 (100%), defaults to 0.1 (10%). NestDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care. diff --git a/browser-version/out/nestdb.js b/browser-version/out/nestdb.js index 9768a22..1d36e1a 100644 --- a/browser-version/out/nestdb.js +++ b/browser-version/out/nestdb.js @@ -315,7 +315,9 @@ var util = require('util') * @param {Boolean} options.inMemoryOnly Optional, defaults to false * @param {Boolean} options.autoload Optional, defaults to false * @param {Function} options.onload Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown - * @param {Function} options.afterSerialization/options.beforeDeserialization Optional, serialization hooks + * @param {Function} options.idGenerator Optional, if set, this function will be used for generating IDs. It takes no arguments and should return a unique string. + * @param {Function} options.afterSerialization Optional, serialization hook. Must be symmetrical to `options.beforeDeserialization`. + * @param {Function} options.beforeDeserialization Optional, deserialization hook. Must be symmetrical to options.afterSerialization`. * @param {Number} options.corruptAlertThreshold Optional, threshold after which an alert is thrown if too much data is corrupt * @param {Function} options.compareStrings Optional, string comparison function that overrides default for sorting * @param {Object} options.storage Optional, custom storage engine for the database files. Must implement all methods exported by the standard "storage" module included in NestDB @@ -370,6 +372,9 @@ function Datastore(options) { this.inMemoryOnly = options.inMemoryOnly || false; this.autoload = options.autoload || false; this.timestampData = options.timestampData || false; + if (typeof options.idGenerator === 'function') { + this._idGenerator = options.idGenerator; + } // Determine whether in memory or persistent if (!filename || typeof filename !== 'string' || filename.length === 0) { @@ -750,15 +755,27 @@ Datastore.prototype._insert = function (newDoc, cb) { }; +/** + * Default implementation for generating a unique _id + * @protected + */ +Datastore.prototype._idGenerator = function () { + return customUtils.uid(16); +}; + + /** * Create a new _id that's not already in use */ Datastore.prototype.createNewId = function () { - var tentativeId = customUtils.uid(16); + var tentativeId; + // Try as many times as needed to get an unused _id. As explained in customUtils, the probability of this ever happening is extremely small, so this is O(1) - if (this.indexes._id.getMatching(tentativeId).length > 0) { - tentativeId = this.createNewId(); + do { + tentativeId = this._idGenerator(); } + while (this.indexes._id.getMatching(tentativeId).length > 0); + return tentativeId; }; diff --git a/browser-version/out/nestdb.min.js b/browser-version/out/nestdb.min.js index d853e66..1d87d2d 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,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.createNewId=function(){var t=s.uid(16);return this.indexes._id.getMatching(t).length>0&&(t=this.createNewId()),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 x(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(x.apply(i,[t,u,n,r-1]));a(e)}})})}).catch(a)});return o(a,n),a}function _(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=_||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=x||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)),_(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(x(e))return t.stylize(Date.prototype.toString.call(e),"date");if(_(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)),x(e)&&(g=" "+Date.prototype.toUTCString.call(e)),_(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 x(t){return k(t)&&"[object Date]"===O(t)}function _(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];ns)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];n 0) { - tentativeId = this.createNewId(); + do { + tentativeId = this._idGenerator(); } + while (this.indexes._id.getMatching(tentativeId).length > 0); + return tentativeId; }; diff --git a/test/datastore.test.js b/test/datastore.test.js index 3e64d85..9f5ce2d 100755 --- a/test/datastore.test.js +++ b/test/datastore.test.js @@ -145,6 +145,28 @@ describe('Datastore', function () { }); }); + it('Custom ID Generator', function (done) { + var lastId + , db = new Datastore({ idGenerator: function() { lastId = '' + Date.now(); return lastId; } }) + ; + + db.insert({ foo: 'bar' }, function (err1, doc1) { + assert.isNull(err1); + doc1._id.should.equal(lastId); + doc1._id.should.match(/^\d+$/); + + // No delay is needed here since, if the ID already exists, it will just keep generating a new one until it differs + db.insert({ foo: 'baz' }, function (err2, doc2) { + assert.isNull(err2); + doc2._id.should.equal(lastId); + doc2._id.should.match(/^\d+$/); + doc2._id.should.not.equal(doc1._id); + parseInt(doc2._id, 10).should.be.greaterThan(parseInt(doc1._id, 10)); + done(); + }); + }); + }); + describe('Autoloading', function () { it('Can autoload a database and query it right away', function (done) {