(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 3 && arguments[3] !== undefined ? arguments[3] : {};
var collection;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (!(schema.constructor.name != 'RxSchema')) {
_context7.next = 2;
break;
}
throw new TypeError('given schema is no Schema-object');
case 2:
if (!(database.constructor.name != 'RxDatabase')) {
_context7.next = 4;
break;
}
throw new TypeError('given database is no Database-object');
case 4:
if (!(typeof name != 'string' || name.length == 0)) {
_context7.next = 6;
break;
}
throw new TypeError('given name is no string or empty');
case 6:
collection = new RxCollection(database, name, schema);
_context7.next = 9;
return collection.prepare();
case 9:
return _context7.abrupt('return', collection);
case 10:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
return function create(_x6, _x7, _x8, _x9) {
return _ref7.apply(this, arguments);
};
}();
var _PouchDB = require('./PouchDB');
var _PouchDB2 = _interopRequireDefault(_PouchDB);
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _RxDocument = require('./RxDocument');
var RxDocument = _interopRequireWildcard(_RxDocument);
var _RxQuery = require('./RxQuery');
var RxQuery = _interopRequireWildcard(_RxQuery);
var _RxChangeEvent = require('./RxChangeEvent');
var RxChangeEvent = _interopRequireWildcard(_RxChangeEvent);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var RxCollection = function () {
function RxCollection(database, name, schema) {
var _this = this;
var pouchSettings = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
(0, _classCallCheck3.default)(this, RxCollection);
this.$ = function () {
return _this.observable$;
};
this.$emit = function (changeEvent) {
return _this.database.$emit(changeEvent);
};
this.database = database;
this.name = name;
this.schema = schema;
this.synced = false;
var adapterObj = {
db: this.database.adapter
};
if (typeof this.database.adapter === 'string') {
adapterObj = {
adapter: this.database.adapter
};
}
this.pouch = new _PouchDB2.default(database.prefix + ':RxDB:' + name, adapterObj, pouchSettings);
this.observable$ = this.database.$().filter(function (event) {
return event.data.col == _this.name;
});
}
(0, _createClass3.default)(RxCollection, [{
key: 'prepare',
value: function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
var _this2 = this;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return Promise.all(this.schema.indexes.map(function (indexAr) {
return _this2.pouch.createIndex({
index: {
fields: indexAr
}
});
}));
case 2:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function prepare() {
return _ref.apply(this, arguments);
}
return prepare;
}()
/**
* returns observable
*/
}, {
key: 'insert',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(json) {
var _this3 = this;
var encPaths, swappedDoc, insertResult, newDocData, newDoc, emitEvent;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!json._id) {
_context2.next = 2;
break;
}
throw new Error('do not provide ._id, it will be generated');
case 2:
json = (0, _clone2.default)(json);
json._id = util.generate_id();
this.schema.validate(json);
// handle encrypted fields
encPaths = this.schema.getEncryptedPaths();
Object.keys(encPaths).map(function (path) {
var value = _objectPath2.default.get(json, path);
var encrypted = _this3.database._encrypt(value);
_objectPath2.default.set(json, path, encrypted);
});
// primary swap
swappedDoc = this.schema.swapPrimaryToId(json);
_context2.next = 10;
return this.pouch.put(swappedDoc);
case 10:
insertResult = _context2.sent;
newDocData = json;
newDocData._id = insertResult.id;
newDocData._rev = insertResult.rev;
newDoc = RxDocument.create(this, newDocData, {});
// event
emitEvent = RxChangeEvent.create('RxCollection.insert', this.database, this, newDoc, newDocData);
this.$emit(emitEvent);
return _context2.abrupt('return', newDoc);
case 18:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function insert(_x2) {
return _ref2.apply(this, arguments);
}
return insert;
}()
/**
* takes a mongoDB-query-object and returns the documents
* @param {object} queryObj
* @return {RxDocument[]} found documents
*/
}, {
key: 'find',
value: function find(queryObj) {
var _this4 = this;
if (typeof queryObj === 'string') throw new Error('if you want to search by _id, use .findOne(_id)');
var query = RxQuery.create(queryObj, this);
query.exec = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
var queryJSON, docs, ret;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
queryJSON = query.toJSON();
_context3.next = 3;
return _this4.pouch.find(queryJSON);
case 3:
docs = _context3.sent;
ret = RxDocument.createAr(_this4, docs.docs, queryJSON);
return _context3.abrupt('return', ret);
case 6:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this4);
}));
return query;
}
}, {
key: 'findOne',
value: function findOne(queryObj) {
var _this5 = this;
var query = void 0;
if (typeof queryObj === 'string') {
query = RxQuery.create({
_id: queryObj
}, this);
} else query = RxQuery.create(queryObj, this);
query.exec = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4() {
var queryJSON, docs, doc, ret;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
queryJSON = query.toJSON();
queryJSON.limit = 1;
_context4.next = 4;
return _this5.pouch.find(queryJSON);
case 4:
docs = _context4.sent;
if (!(docs.docs.length === 0)) {
_context4.next = 7;
break;
}
return _context4.abrupt('return', null);
case 7:
doc = docs.docs.shift();
ret = RxDocument.create(_this5, doc, queryJSON);
return _context4.abrupt('return', ret);
case 10:
case 'end':
return _context4.stop();
}
}
}, _callee4, _this5);
}));
query.limit = function (a1, a2) {
throw new Error('.limit() cannot be called on .findOne()');
};
return query;
}
/**
* get a query only
* @return {RxQuery} query which can be subscribed to
*/
}, {
key: 'query',
value: function query(queryObj) {
if (typeof queryObj === 'string') throw new Error('if you want to search by _id, use .findOne(_id)');
var query = RxQuery.create(queryObj, this);
return query;
}
/**
* export to json
* @param {boolean} decrypted if true, all encrypted values will be decrypted
*/
}, {
key: 'dump',
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee5() {
var _this6 = this;
var decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var json, docs;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
json = {
name: this.name,
schemaHash: this.schema.hash(),
encrypted: false,
passwordHash: null,
docs: []
};
if (this.database.password) {
json.passwordHash = util.hash(this.database.password);
if (decrypted) json.encrypted = false;else json.encrypted = true;
}
_context5.next = 4;
return this.find().exec();
case 4:
docs = _context5.sent;
docs.map(function (doc) {
var useData = doc.rawData;
if (_this6.database.password && decrypted) useData = Object.assign(doc.rawData, doc.data);
delete useData._rev;
json.docs.push(useData);
});
return _context5.abrupt('return', json);
case 7:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function dump(_x3) {
return _ref5.apply(this, arguments);
}
return dump;
}()
/**
* imports the json-data into the collection
* @param {Array} exportedJSON should be an array of raw-data
*/
}, {
key: 'importDump',
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee6(exportedJSON) {
var _this7 = this;
var decDocs, fns;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!(exportedJSON.schemaHash != this.schema.hash())) {
_context6.next = 2;
break;
}
throw new Error('the imported json relies on a different schema');
case 2:
if (!(exportedJSON.encrypted && exportedJSON.passwordHash != util.hash(this.database.password))) {
_context6.next = 4;
break;
}
throw new Error('json.passwordHash does not match the own');
case 4:
// decrypt docs
decDocs = [];
exportedJSON.docs.map(function (docData) {
docData = (0, _clone2.default)(docData);
if (exportedJSON.encrypted) {
var encPaths = _this7.schema.getEncryptedPaths();
Object.keys(encPaths).map(function (path) {
var encrypted = _objectPath2.default.get(docData, path);
if (!encrypted) return;
var decrypted = _this7.database._decrypt(encrypted);
_objectPath2.default.set(docData, path, decrypted);
});
}
decDocs.push(docData);
});
// check if docs match schema
decDocs.map(function (decDoc) {
_this7.schema.validate(decDoc);
});
// import
fns = [];
exportedJSON.docs.map(function (decDocs) {
fns.push(_this7.pouch.put(decDocs));
});
_context6.next = 11;
return Promise.all(fns);
case 11:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function importDump(_x5) {
return _ref6.apply(this, arguments);
}
return importDump;
}()
}, {
key: 'sync',
value: function sync(serverURL) {
var _this8 = this;
if (!this.synced) {
(function () {
/**
* this will grap the changes and publish them to the rx-stream
* this is to ensure that changes from 'synced' dbs will be published
*/
var sendChanges = {};
var pouch$ = util.Rx.Observable.fromEvent(_this8.pouch.changes({
since: 'now',
live: true,
include_docs: true
}), 'change').filter(function (c) {
return c.id.charAt(0) != '_';
}).map(function (c) {
return c.doc;
}).map(function (doc) {
doc._ext = true;
return doc;
}).filter(function (doc) {
return sendChanges[doc._rev] = 'YES';
}).delay(10).map(function (doc) {
var ret = null;
if (sendChanges[doc._rev] == 'YES') ret = doc;
delete sendChanges[doc._rev];
return ret;
}).filter(function (doc) {
return doc != null;
}).subscribe(function (doc) {
_this8.$emit(RxChangeEvent.fromPouchChange(doc, _this8));
});
var ob2 = _this8.$().map(function (cE) {
return cE.data.v;
}).map(function (doc) {
if (sendChanges[doc._rev]) sendChanges[doc._rev] = 'NO';
}).subscribe();
})();
}
this.synced = true;
return this.pouch.sync(serverURL, {
live: true,
retry: true
}).on('error', function (err) {
console.log('sync error:');
console.log(JSON.stringify(err));
throw new Error(err);
});
}
}]);
return RxCollection;
}();
},{"./PouchDB":2,"./RxChangeEvent":3,"./RxDocument":6,"./RxQuery":7,"./util":13,"babel-runtime/helpers/asyncToGenerator":24,"babel-runtime/helpers/classCallCheck":25,"babel-runtime/helpers/createClass":26,"babel-runtime/regenerator":28,"clone":34,"object-path":175}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RxSchema = exports.create = undefined;
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var create = exports.create = function () {
var _ref9 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee9(prefix, adapter, password, multiInstance) {
var db;
return _regenerator2.default.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (!(typeof prefix !== 'string')) {
_context9.next = 2;
break;
}
throw new TypeError('given prefix is no string ');
case 2:
if (!(typeof adapter == 'string')) {
_context9.next = 7;
break;
}
if (!(!_PouchDB2.default.adapters || !_PouchDB2.default.adapters[adapter])) {
_context9.next = 5;
break;
}
throw new Error('Adapter ' + adapter + ' not added.' + ' Use RxDB.PouchDB.plugin(require(\'pouchdb-adapter-' + adapter + '\'));');
case 5:
_context9.next = 10;
break;
case 7:
util.isLevelDown(adapter);
if (!(!_PouchDB2.default.adapters || !_PouchDB2.default.adapters.leveldb)) {
_context9.next = 10;
break;
}
throw new Error('To use leveldown-adapters, you have to add the leveldb-plugin.' + ' Use RxDB.PouchDB.plugin(require(\'pouchdb-adapter-leveldb\'));');
case 10:
if (!(password && typeof password !== 'string')) {
_context9.next = 12;
break;
}
throw new TypeError('password is no string');
case 12:
if (!(password && password.length < RxDatabase.settings.minPassLength)) {
_context9.next = 14;
break;
}
throw new Error('password must be at least ' + RxDatabase.settings.minPassLength + ' chars');
case 14:
db = new RxDatabase(prefix, adapter, password, multiInstance);
_context9.next = 17;
return db.prepare();
case 17:
return _context9.abrupt('return', db);
case 18:
case 'end':
return _context9.stop();
}
}
}, _callee9, this);
}));
return function create(_x11, _x12, _x13, _x14) {
return _ref9.apply(this, arguments);
};
}();
var _randomToken = require('random-token');
var _randomToken2 = _interopRequireDefault(_randomToken);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _RxCollection = require('./RxCollection');
var RxCollection = _interopRequireWildcard(_RxCollection);
var _RxSchema = require('./RxSchema');
var RxSchema = _interopRequireWildcard(_RxSchema);
var _Database = require('./Database.schemas');
var DatabaseSchemas = _interopRequireWildcard(_Database);
var _RxChangeEvent = require('./RxChangeEvent');
var RxChangeEvent = _interopRequireWildcard(_RxChangeEvent);
var _PouchDB = require('./PouchDB');
var _PouchDB2 = _interopRequireDefault(_PouchDB);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var RxDatabase = function () {
function RxDatabase(prefix, adapter, password, multiInstance) {
var _this = this;
(0, _classCallCheck3.default)(this, RxDatabase);
this.$ = function () {
return _this.observable$;
};
this._cleanSocket_running = false;
this.prefix = prefix;
this.adapter = adapter;
this.token = (0, _randomToken2.default)(10);
this.password = password;
// cache for collection-objects
this.collections = {};
// rx
this.pull$Count = 0;
this.subject = new util.Rx.Subject();
this.observable$ = this.subject.asObservable().filter(function (cEvent) {
return cEvent.constructor.name == 'RxChangeEvent';
});
/**
* if true, the multiInstance handlings will be done
*/
this.multiInstance = multiInstance || false;
this.isPulling = false;
this.lastPull = new Date().getTime();
this.recievedEvents = {};
this.autoPull$;
if (this.multiInstance) {
var pullTime = 200;
// BroadcastChannel
if (util.hasBroadcastChannel()) {
pullTime = 1000;
this.bc$ = new BroadcastChannel('RxDB:' + this.prefix);
this.bc$.onmessage = function (msg) {
if (msg.data != _this.token) _this.$pull();
};
}
// pull on intervall
this.autoPull$ = util.Rx.Observable.interval(pullTime) // TODO evaluate pullTime value or make it settable
.subscribe(function (x) {
return _this.$pull();
});
}
}
/**
* make the async things for this database
*/
(0, _createClass3.default)(RxDatabase, [{
key: 'prepare',
value: function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
var _this2 = this;
var pwHashDoc;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return Promise.all([RxCollection.create(this, '_admin', DatabaseSchemas.administration, {
auto_compaction: true
}).then(function (col) {
return _this2.administrationCollection = col;
}), RxCollection.create(this, '_collections', DatabaseSchemas.collections).then(function (col) {
return _this2.collectionsCollection = col;
}), RxCollection.create(this, '_socket', DatabaseSchemas.socket).then(function (col) {
return _this2.socketCollection = col;
})]);
case 2:
_context.next = 4;
return this.administrationCollection.findOne({
key: 'pwHash'
}).exec();
case 4:
pwHashDoc = _context.sent;
if (!(!pwHashDoc && this.password)) {
_context.next = 8;
break;
}
_context.next = 8;
return this.administrationCollection.insert({
key: 'pwHash',
value: util.hash(this.password)
});
case 8:
if (!(pwHashDoc && this.password && util.hash(this.password) != pwHashDoc.get('value'))) {
_context.next = 10;
break;
}
throw new Error('another instance on this adapter has a different password');
case 10:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function prepare() {
return _ref.apply(this, arguments);
}
return prepare;
}()
}, {
key: '$emit',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2(changeEvent) {
var _this3 = this;
var socketDoc, decideHash, decidedVal;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (changeEvent) {
_context2.next = 2;
break;
}
return _context2.abrupt('return');
case 2:
// throw in own chain
this.subject.next(changeEvent);
// write to socket
if (this.multiInstance && !changeEvent.isIntern() && changeEvent.data.it == this.token) {
socketDoc = changeEvent.toJSON();
delete socketDoc.db;
if (socketDoc.v) {
if (this.password) socketDoc.v = this._encrypt(socketDoc.v);else socketDoc.v = JSON.stringify(socketDoc.v);
}
this.socketCollection.insert(socketDoc).then(function () {
_this3.bc$ && _this3.bc$.postMessage(_this3.token);
});
/**
* check if the cleanup of _socket should be run
* this is decided with the hash to prevent that 2 instances
* cleanup at the same time (not prevent but make more unlikely)
*/
decideHash = util.fastUnsecureHash(this.token + changeEvent.hash());
decidedVal = decideHash % 10;
if (decidedVal == 0) this._cleanSocket();
}
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function $emit(_x) {
return _ref2.apply(this, arguments);
}
return $emit;
}()
/**
* @return {Observable} observable
*/
}, {
key: '_cleanSocket',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
var maxTime, socketDocs;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!this._cleanSocket_running) {
_context3.next = 2;
break;
}
return _context3.abrupt('return');
case 2:
this._cleanSocket_running = true;
maxTime = new Date().getTime() - 1200;
_context3.next = 6;
return this.socketCollection.find({
t: {
$lt: maxTime
}
}).exec();
case 6:
socketDocs = _context3.sent;
_context3.next = 9;
return Promise.all(socketDocs.map(function (doc) {
return doc.remove();
}));
case 9:
this._cleanSocket_running = false;
case 10:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function _cleanSocket() {
return _ref3.apply(this, arguments);
}
return _cleanSocket;
}()
/**
* triggers the grabbing of new events from other instances
* from the socket
*/
}, {
key: '$pull',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4() {
var _this4 = this;
var minTime;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.pull$Count++;
// console.log('.....');
if (!(!this.subject || !this.socketCollection)) {
_context4.next = 3;
break;
}
return _context4.abrupt('return');
case 3:
if (!this.isPulling) {
_context4.next = 6;
break;
}
/**
* if pull is called again while running,
* it can happen that the change wont be noticed until the next
* pull-cycle. This will ensure than in this case pull$ is called again
*/
this._repull = true;
return _context4.abrupt('return');
case 6:
this.isPulling = true;
minTime = this.lastPull - 50; // TODO evaluate this value (50)
_context4.next = 10;
return this.socketCollection.find({
it: {
$ne: this.token
},
t: {
$gt: minTime
}
}).exec()
// sort docs by timestamp
.then(function (docs) {
return docs.sort(function (a, b) {
if (a.data.t > b.data.t) return 1;
return -1;
});
}).then(function (eventDocs) {
eventDocs.map(function (doc) {
return RxChangeEvent.fromJSON(doc.data);
})
// make sure the same event is not emitted twice
.filter(function (cE) {
if (_this4.recievedEvents[cE.hash()]) return false;
return _this4.recievedEvents[cE.hash()] = new Date().getTime();
})
// prevent memory leak of this.recievedEvents
.filter(function (cE) {
return setTimeout(function () {
return delete _this4.recievedEvents[cE.hash()];
}, 20 * 1000);
})
// decrypt if data.v is encrypted
.map(function (cE) {
if (cE.data.v) {
if (_this4.password) cE.data.v = _this4._decrypt(cE.data.v);else cE.data.v = JSON.parse(cE.data.v);
}
return cE;
}).forEach(function (cE) {
return _this4.$emit(cE);
});
});
case 10:
this.lastPull = new Date().getTime();
this.isPulling = false;
if (this._repull) {
this._repull = false;
this.$pull();
}
return _context4.abrupt('return', true);
case 14:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function $pull() {
return _ref4.apply(this, arguments);
}
return $pull;
}()
}, {
key: '_encrypt',
value: function _encrypt(value) {
if (!this.password) throw new Error('no passord given');
return util.encrypt(JSON.stringify(value), this.password);
}
}, {
key: '_decrypt',
value: function _decrypt(encValue) {
if (!this.password) throw new Error('no passord given');
var decrypted = util.decrypt(encValue, this.password);
return JSON.parse(decrypted);
}
/**
* create or fetch a collection
* @return {Collection}
*/
}, {
key: 'collection',
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee5(name, schema) {
var pouchSettings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var schemaHash, collectionDoc, _collection, cEvent;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!(name.charAt(0) == '_')) {
_context5.next = 2;
break;
}
throw new Error('collection-names cannot start with underscore _');
case 2:
if (schema && schema.constructor.name != 'RxSchema') schema = RxSchema.create(schema);
if (this.collections[name]) {
_context5.next = 25;
break;
}
// check schemaHash
schemaHash = schema.hash();
_context5.next = 7;
return this.collectionsCollection.findOne({
name: name
}).exec();
case 7:
collectionDoc = _context5.sent;
if (!(collectionDoc && collectionDoc.get('schemaHash') != schemaHash)) {
_context5.next = 10;
break;
}
throw new Error('another instance created this collection with a different schema');
case 10:
_context5.next = 12;
return RxCollection.create(this, name, schema, pouchSettings);
case 12:
_collection = _context5.sent;
if (!(Object.keys(_collection.schema.getEncryptedPaths()).length > 0 && !this.password)) {
_context5.next = 15;
break;
}
throw new Error('schema encrypted but no password given');
case 15:
if (collectionDoc) {
_context5.next = 18;
break;
}
_context5.next = 18;
return this.collectionsCollection.insert({
name: name,
schemaHash: schemaHash
});
case 18:
cEvent = RxChangeEvent.create('RxDatabase.collection', this);
cEvent.data.v = _collection.name;
cEvent.data.col = '_collections';
this.$emit(cEvent);
this.collections[name] = _collection;
_context5.next = 27;
break;
case 25:
if (!(schema && schema.hash() != this.collections[name].schema.hash())) {
_context5.next = 27;
break;
}
throw new Error('collection ' + name + ' already has a different schema');
case 27:
return _context5.abrupt('return', this.collections[name]);
case 28:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function collection(_x2, _x3, _x4) {
return _ref5.apply(this, arguments);
}
return collection;
}()
}, {
key: 'destroy',
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee6() {
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
this.bc$.close();
case 1:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function destroy() {
return _ref6.apply(this, arguments);
}
return destroy;
}()
/**
* export to json
* @param {boolean} decrypted
* @param {?string[]} collections array with collectionNames or null if all
*/
}, {
key: 'dump',
value: function () {
var _ref7 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee7() {
var _this5 = this;
var decrypted = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var collections = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var json, useCollections;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
json = {
name: this.prefix,
instanceToken: this.token,
encrypted: false,
passwordHash: null,
collections: []
};
if (this.password) {
json.passwordHash = util.hash(this.password);
if (decrypted) json.encrypted = false;else json.encrypted = true;
}
useCollections = Object.keys(this.collections).filter(function (colName) {
return !collections || collections.includes(colName);
}).filter(function (colName) {
return colName.charAt(0) != '_';
}).map(function (colName) {
return _this5.collections[colName];
});
_context7.next = 5;
return Promise.all(useCollections.map(function (col) {
return col.dump(decrypted);
}));
case 5:
json.collections = _context7.sent;
return _context7.abrupt('return', json);
case 7:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
function dump(_x6, _x7) {
return _ref7.apply(this, arguments);
}
return dump;
}()
/**
* import json
* @param {Object} dump
*/
}, {
key: 'importDump',
value: function () {
var _ref8 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee8(dump) {
var _this6 = this;
return _regenerator2.default.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
return _context8.abrupt('return', Promise.all(dump.collections.filter(function (colDump) {
return _this6.collections[colDump.name];
}).map(function (colDump) {
return _this6.collections[colDump.name].importDump(colDump);
})));
case 1:
case 'end':
return _context8.stop();
}
}
}, _callee8, this);
}));
function importDump(_x10) {
return _ref8.apply(this, arguments);
}
return importDump;
}()
}]);
return RxDatabase;
}();
RxDatabase.settings = {
minPassLength: 8
};
exports.RxSchema = RxSchema;
},{"./Database.schemas":1,"./PouchDB":2,"./RxChangeEvent":3,"./RxCollection":4,"./RxSchema":8,"./util":13,"babel-runtime/helpers/asyncToGenerator":24,"babel-runtime/helpers/classCallCheck":25,"babel-runtime/helpers/createClass":26,"babel-runtime/regenerator":28,"random-token":236}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.create = create;
exports.createAr = createAr;
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _RxChangeEvent = require('./RxChangeEvent');
var RxChangeEvent = _interopRequireWildcard(_RxChangeEvent);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var RxDocument = function () {
function RxDocument(collection, jsonData, query) {
var _this = this;
(0, _classCallCheck3.default)(this, RxDocument);
this.$emit = function (changeEvent) {
return _this.collection.$emit(changeEvent);
};
this.collection = collection;
this.rawData = jsonData;
this.query = query;
this.data = (0, _clone2.default)(this.rawData);
delete this.data._rev;
delete this.data._id;
// handle encrypted data
var encPaths = this.collection.schema.getEncryptedPaths();
var currentPath = void 0;
Object.keys(encPaths).map(function (path) {
return currentPath = path;
}).map(function (path) {
return _objectPath2.default.get(_this.data, currentPath);
}).filter(function (enc) {
return !!enc;
}).map(function (encrypted) {
return _this.collection.database._decrypt(encrypted);
}).forEach(function (decrypted) {
return _objectPath2.default.set(_this.data, currentPath, decrypted);
});
this.deleted = false;
this.changed = false;
this.observable$ = this.collection.$().filter(function (event) {
return event.data.doc == _this.rawData._id || event.data.doc == '*';
});
}
/**
* returns observable
* @param {?string} path or all events
* @return {RxObservable} obs
*/
(0, _createClass3.default)(RxDocument, [{
key: '$',
value: function $() {
var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
if (path) {
// observe single path only
var schemaObj = this.collection.schema.getSchemaByObjectPath(path);
if (!schemaObj) throw new Error('cannot observe a non-existed field (' + path + ')');
return this.observable$.map(function (cEvent) {
return _objectPath2.default.get(cEvent.data.v, path);
}).distinctUntilChanged().startWith(this.get(path));
} else return this.observable$;
}
}, {
key: 'get',
/**
* get data by objectPath
* @param {string} objPath
* @return {object} value
*/
value: function get(objPath) {
if (typeof objPath !== 'string') throw new TypeError('RxDocument.get(): objPath must be a string');
if (objPath == this.collection.schema.primaryPath) return this.rawData._id;
return _objectPath2.default.get(this.data, objPath);
}
/**
* set data by objectPath
* @param {string} objPath
* @param {object} value
*/
}, {
key: 'set',
value: function set(objPath, value) {
if (typeof objPath !== 'string') throw new TypeError('RxDocument.set(): objPath must be a string');
if (objPath == '_id') throw new Error('_id cannot be modified');
if (objPath == this.collection.schema.primaryPath) throw new Error('primary-fields cannot be modified');
// check if equal
if (Object.is(this.get(objPath), value)) return;else this.changed = true;
// check if nested without root-object
var pathEls = objPath.split('.');
pathEls.pop();
var rootPath = pathEls.join('.');
if (typeof _objectPath2.default.get(this.data, rootPath) === 'undefined') {
throw new Error('cannot set childpath ' + objPath + ' when rootPath ' + rootPath + ' not selected');
}
// check schema of changed field
var schemaObj = this.collection.schema.getSchemaByObjectPath(objPath);
this.collection.schema.validate(value, schemaObj);
_objectPath2.default.set(this.data, objPath, value);
_objectPath2.default.set(this.rawData, objPath, value);
return this;
}
}, {
key: 'save',
value: function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
var _this2 = this;
var rootDoc, emitValue, encPaths, ret;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this.changed) {
_context.next = 2;
break;
}
return _context.abrupt('return');
case 2:
if (!this.deleted) {
_context.next = 4;
break;
}
throw new Error('RxDocument.save(): cant save deleted document');
case 4:
if (!this.query.fields) {
_context.next = 10;
break;
}
_context.next = 7;
return this.collection.findOne(this.rawData._id).exec();
case 7:
rootDoc = _context.sent;
this.rawData = Object.assign(rootDoc.rawData, this.rawData);
this.data = Object.assign(rootDoc.data, this.data);
case 10:
emitValue = (0, _clone2.default)(this.rawData);
// handle encrypted data
encPaths = this.collection.schema.getEncryptedPaths();
Object.keys(encPaths).map(function (path) {
var value = _objectPath2.default.get(_this2.rawData, path);
var encrypted = _this2.collection.database._encrypt(value);
_objectPath2.default.set(_this2.rawData, path, encrypted);
});
_context.next = 15;
return this.collection.pouch.put(this.rawData);
case 15:
ret = _context.sent;
if (ret.ok) {
_context.next = 18;
break;
}
throw new Error('RxDocument.save(): error ' + JSON.stringify(ret));
case 18:
this.rawData._rev = ret.rev;
// event
this.$emit(RxChangeEvent.create('RxDocument.save', this.collection.database, this.collection, this, emitValue));
this.changed = false;
case 21:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function save() {
return _ref.apply(this, arguments);
}
return save;
}()
}, {
key: 'remove',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2() {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!this.deleted) {
_context2.next = 2;
break;
}
throw new Error('RxDocument.remove(): Document is already deleted');
case 2:
this.deleted = true;
_context2.next = 5;
return this.collection.pouch.remove(this.rawData._id, this.rawData._rev);
case 5:
this.$emit(RxChangeEvent.create('RxDocument.remove', this.collection.database, this.collection, this, null));
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function remove() {
return _ref2.apply(this, arguments);
}
return remove;
}()
}, {
key: 'destroy',
value: function destroy() {}
}]);
return RxDocument;
}();
function create(collection, jsonData, query) {
if (jsonData._id.startsWith('_design')) return null;
var doc = new RxDocument(collection, jsonData, query);
return doc;
}
function createAr(collection, jsonDataAr, query) {
var ret = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = jsonDataAr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var jsonData = _step.value;
if (!jsonData._id.startsWith('_design')) ret.push(create(collection, jsonData, query));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return ret;
}
},{"./RxChangeEvent":3,"./util":13,"babel-runtime/helpers/asyncToGenerator":24,"babel-runtime/helpers/classCallCheck":25,"babel-runtime/helpers/createClass":26,"babel-runtime/regenerator":28,"clone":34,"object-path":175}],7:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.create = create;
var _mquery = require('./mquery/mquery');
var _mquery2 = _interopRequireDefault(_mquery);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
var _RxDocument = require('./RxDocument');
var RxDocument = _interopRequireWildcard(_RxDocument);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaultQuery = {
_id: {}
};
// TODO arent they already removed in mquery/mquery.js ?
/**
* this is the query-builder
* it basically uses mquery with a few overwrites
*/
var notUsedMqueryFunctions = ['exec', 'collection', 'result'];
var RxQuery = function () {
function RxQuery(queryObj, collection) {
var _this = this;
(0, _classCallCheck3.default)(this, RxQuery);
this.collection = collection;
this.subject$;
this.collectionSub$;
this.defaultQuery = false;
if (!queryObj || Object.keys(queryObj).length === 0 && !Array.isArray(queryObj)) {
queryObj = defaultQuery;
this.defaultQuery = true;
}
this.mquery = (0, _mquery2.default)(queryObj);
// merge mquery-prototype functions to this
var mquery_proto = Object.getPrototypeOf(this.mquery);
Object.keys(mquery_proto).map(function (attrName) {
if (!notUsedMqueryFunctions.includes(attrName) && typeof mquery_proto[attrName] === 'function') {
// only param1 is tunneled here on purpose so no callback-call can be done
_this[attrName] = function (param1) {
_this.mquery[attrName](param1);
return _this;
};
}
});
// overwrites
/**
* make sure it searches index because of pouchdb-find bug
* @link https://github.com/nolanlawson/pouchdb-find/issues/204
*/
this.sort = function (params) {
// workarround because sort wont work on unused keys
Object.keys(params).map(function (k) {
return _this.mquery.where(k).gt(null);
});
_this.mquery.sort(params);
return _this;
};
}
// observe the result of this query
(0, _createClass3.default)(RxQuery, [{
key: '$',
value: function $() {
var _this2 = this;
if (this.subject$) return this.subject$.asObservable();
this.subject$ = new util.Rx.BehaviorSubject(null);
this.refresh$(); // get init value
this.collectionSub$ = this.collection.$().filter(function (c) {
return _this2.subject$.observers.length > 0;
}) // TODO replace with subject$.hasObservers() https://github.com/Reactive-Extensions/RxJS/issues/1364
.filter(function (cEvent) {
return ['RxCollection.insert', 'RxDocument.save'].includes(cEvent.data.op);
}).subscribe(function (cEvent) {
return _this2.refresh$();
});
return this.subject$.asObservable();
}
/**
* regrap the result from the database
* and save it to this.result
*/
}, {
key: 'refresh$',
value: function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
var queryJSON, docs, ret;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!this.refresh$_running) {
_context.next = 2;
break;
}
return _context.abrupt('return');
case 2:
this.refresh$_running = true;
queryJSON = this.toJSON();
_context.next = 6;
return this.collection.pouch.find(queryJSON);
case 6:
docs = _context.sent;
ret = RxDocument.createAr(this.collection, docs.docs, queryJSON);
this.subject$.next(ret);
this.refresh$_running = false;
case 10:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function refresh$() {
return _ref.apply(this, arguments);
}
return refresh$;
}()
}, {
key: 'toJSON',
value: function toJSON() {
var _this3 = this;
var conds = this.mquery._conditions;
var json = {
selector: conds
};
var options = this.mquery._optionsForExec();
// select fields
if (this.mquery._fields) {
(function () {
var fields = _this3.mquery._fieldsForExec();
var useFields = Object.keys(fields).filter(function (fieldName) {
return fields[fieldName] == 1;
});
useFields.push('_id');
useFields.push('_rev');
useFields = useFields.filter(function (elem, pos, arr) {
return arr.indexOf(elem) == pos;
}); // unique
json.fields = useFields;
})();
}
// sort
if (options.sort) {
(function () {
var sortArray = [];
Object.keys(options.sort).map(function (fieldName) {
var dirInt = options.sort[fieldName];
var dir = 'asc';
if (dirInt == -1) dir = 'desc';
var pushMe = {};
if (fieldName == _this3.collection.schema.primaryPath) fieldName = '_id';
pushMe[fieldName] = dir;
sortArray.push(pushMe);
});
json.sort = sortArray;
})();
}
if (options.limit) {
if (typeof options.limit !== 'number') throw new TypeError('limit() must get a number');
json.limit = options.limit;
}
if (options.skip) {
if (typeof options.skip !== 'number') throw new TypeError('skip() must get a number');
json.skip = options.skip;
}
// add not-query to _id to prevend the grabbing of '_design..' docs
// this is not the best solution because it prevents the usage of a 'language'-field
if (!json.selector.language) json.selector.language = {};
json.selector.language.$ne = 'query';
// primary swap
if (this.collection.schema.primaryPath && json.selector[this.collection.schema.primaryPath]) {
var primPath = this.collection.schema.primaryPath;
// selector
json.selector._id = json.selector[primPath];
delete json.selector[primPath];
}
return json;
}
}]);
return RxQuery;
}();
function create() {
var queryObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultQuery;
var collection = arguments[1];
if (Array.isArray(queryObj)) // TODO should typecheck be done here ?
throw new TypeError('query cannot be an array');
return new RxQuery(queryObj, collection);
}
},{"./RxDocument":6,"./mquery/mquery":11,"./util":13,"babel-runtime/helpers/asyncToGenerator":24,"babel-runtime/helpers/classCallCheck":25,"babel-runtime/helpers/createClass":26,"babel-runtime/regenerator":28}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getEncryptedPaths = undefined;
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.hasCrypt = hasCrypt;
exports.getIndexes = getIndexes;
exports.getPrimary = getPrimary;
exports.validateFieldsDeep = validateFieldsDeep;
exports.checkSchema = checkSchema;
exports.create = create;
var _objectPath = require('object-path');
var _objectPath2 = _interopRequireDefault(_objectPath);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var RxSchema = function () {
function RxSchema(jsonID) {
var _this = this;
(0, _classCallCheck3.default)(this, RxSchema);
this.jsonID = (0, _clone2.default)(jsonID);
this.compoundIndexes = this.jsonID.compoundIndexes || [];
delete this.jsonID.compoundIndexes;
// make indexes required
this.indexes = getIndexes(this.jsonID);
this.jsonID.required = this.jsonID.required || [];
this.indexes.map(function (indexAr) {
indexAr.filter(function (index) {
return !_this.jsonID.required.includes(index);
}).forEach(function (index) {
return _this.jsonID.required.push(index);
});
});
// primary
this.primaryPath = getPrimary(this.jsonID);
if (this.primaryPath) this.jsonID.required.push(this.primaryPath);
// add _id
this.jsonID.properties._id = {
type: 'string',
minLength: 1
};
// add _rev
this.jsonID.properties._rev = {
type: 'string',
minLength: 1
};
// true if schema contains a crypt-field
this.crypt = hasCrypt(this.jsonID);
this.encryptedPaths;
this.jsonID.additionalProperties = false;
}
(0, _createClass3.default)(RxSchema, [{
key: 'getSchemaByObjectPath',
value: function getSchemaByObjectPath(path) {
path = path.replace(/\./g, '.properties.');
path = 'properties.' + path;
return _objectPath2.default.get(this.jsonID, path);
}
/**
* get all encrypted paths
*/
}, {
key: 'getEncryptedPaths',
value: function getEncryptedPaths() {
if (!this.encryptedPaths) this.encryptedPaths = _getEncryptedPaths(this.jsonID);
return this.encryptedPaths;
}
/**
* validate if the obj matches the schema
* @param {Object} obj
* @param {Object} schemaObj json-schema
*/
}, {
key: 'validate',
value: function validate(obj, schemaObj) {
schemaObj = schemaObj || this.jsonID;
util.jsonSchemaValidate(schemaObj, obj);
return true;
}
}, {
key: 'hash',
value: function hash() {
return util.hash(this.jsonID);
}
}, {
key: 'swapIdToPrimary',
value: function swapIdToPrimary(obj) {
if (!this.primaryPath) return obj;
obj[this.primaryPath] = obj._id;
delete obj._id;
return obj;
}
}, {
key: 'swapPrimaryToId',
value: function swapPrimaryToId(obj) {
if (!this.primaryPath) return obj;
obj._id = obj[this.primaryPath];
delete obj[this.primaryPath];
return obj;
}
}]);
return RxSchema;
}();
/**
* returns all encrypted paths of the schema
* @param {Object} jsonSchema [description]
* @return {Object} with paths as attr and schema as value
*/
function _getEncryptedPaths(jsonSchema) {
var ret = {};
function traverse(currentObj, currentPath) {
if ((typeof currentObj === 'undefined' ? 'undefined' : (0, _typeof3.default)(currentObj)) !== 'object') return;
if (currentObj.encrypted) {
ret[currentPath.substring(1)] = currentObj;
return;
}
for (var attributeName in currentObj) {
var nextPath = currentPath;
if (attributeName != 'properties') nextPath = nextPath + '.' + attributeName;
traverse(currentObj[attributeName], nextPath);
}
}
traverse(jsonSchema, '');
return ret;
}
/**
* returns true if schema contains an encrypted field
* @param {object} jsonSchema with schema
* @return {boolean} isEncrypted
*/
exports.getEncryptedPaths = _getEncryptedPaths;
function hasCrypt(jsonSchema) {
var paths = _getEncryptedPaths(jsonSchema);
if (Object.keys(paths).length > 0) return true;else return false;
}
function getIndexes(jsonID) {
return Object.keys(jsonID.properties).filter(function (key) {
return jsonID.properties[key].index;
}).map(function (key) {
return [key];
}).concat(jsonID.compoundIndexes || []).filter(function (elem, pos, arr) {
return arr.indexOf(elem) == pos;
}); // unique
}
function getPrimary(jsonID) {
return Object.keys(jsonID.properties).filter(function (key) {
return jsonID.properties[key].primary;
}).shift();
}
/**
* validate that all schema-related things are ok
* @param {object} jsonSchema
* @return {boolean} true always
*/
function validateFieldsDeep(jsonSchema) {
function checkField(fieldName, schemaObj, path) {
// all
if (['properties', 'language'].includes(fieldName)) throw new Error('fieldname is not allowed: ' + fieldName);
if (fieldName.includes('.')) throw new Error('field-names cannot contain dots .');
var isNested = path.split('.').length >= 2;
// nested only
if (isNested) {
if (schemaObj.primary) throw new Error('primary can only be defined at top-level');
if (schemaObj.index) throw new Error('index can only be defined at top-level');
}
// first level
if (!isNested) {
// check underscore fields
if (fieldName.charAt(0) == '_') throw new Error('first level-fields cannot start with underscore _');
}
}
function traverse(currentObj, currentPath) {
if ((typeof currentObj === 'undefined' ? 'undefined' : (0, _typeof3.default)(currentObj)) !== 'object') return;
for (var attributeName in currentObj) {
if (!currentObj.properties) {
checkField(attributeName, currentObj[attributeName], currentPath);
}
var nextPath = currentPath;
if (attributeName != 'properties') nextPath = nextPath + '.' + attributeName;
traverse(currentObj[attributeName], nextPath);
}
}
traverse(jsonSchema, '');
return true;
}
/**
* check if the given schemaJSON is useable for the database
*/
function checkSchema(jsonID) {
// check _id
if (jsonID.properties._id) throw new Error('schema defines ._id, this will be done automatically');
// check _rev
if (jsonID.properties._rev) throw new Error('schema defines ._rev, this will be done automatically');
validateFieldsDeep(jsonID);
var primaryPath = void 0;
Object.keys(jsonID.properties).forEach(function (key) {
var value = jsonID.properties[key];
// check primary
if (value.primary) {
if (primaryPath) throw new Error('primary can only be defined once');
primaryPath = key;
if (value.index) throw new Error('primary is always index, do not declare it as index');
if (value.unique) throw new Error('primary is always unique, do not declare it as unique');
if (value.encrypted) throw new Error('primary cannot be encrypted');
if (value.type !== 'string') throw new Error('primary must have type: string');
}
});
if (primaryPath && jsonID && jsonID.required && jsonID.required.includes(primaryPath)) throw new Error('primary is always required, do not declare it as required');
// check format of jsonID.compoundIndexes
if (jsonID.compoundIndexes) {
try {
util.jsonSchemaValidate({
type: 'array',
items: {
type: 'array',
items: {
type: 'string'
}
}
}, jsonID.compoundIndexes);
} catch (e) {
throw new Error('schema.compoundIndexes must be array');
}
}
// check that indexes are string
getIndexes(jsonID).reduce(function (a, b) {
return a.concat(b);
}, []).filter(function (elem, pos, arr) {
return arr.indexOf(elem) == pos;
}) // unique
.filter(function (indexKey) {
return jsonID.properties[indexKey].type != 'string' && jsonID.properties[indexKey].type != 'integer';
}).forEach(function (indexKey) {
throw new Error('given indexKey (' + indexKey + ') is not type:string but ' + jsonID.properties[indexKey].type);
});
}
function create(jsonID) {
checkSchema(jsonID);
return new RxSchema(jsonID);
}
},{"./util":13,"babel-runtime/helpers/classCallCheck":25,"babel-runtime/helpers/createClass":26,"babel-runtime/helpers/typeof":27,"clone":34,"object-path":175}],9:[function(require,module,exports){
'use strict';
var _index = require('./index.js');
var RxDB = _interopRequireWildcard(_index);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
RxDB.plugin(require('pouchdb-adapter-localstorage'));
RxDB.plugin(require('pouchdb-adapter-http'));
RxDB.plugin(require('pouchdb-replication'));
window.RxDB = RxDB;
},{"./index.js":10,"pouchdb-adapter-http":176,"pouchdb-adapter-localstorage":185,"pouchdb-replication":224}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PouchDB = exports.RxSchema = exports.create = undefined;
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
/**
* create a database
* @param {string} prefix as databaseName for the storage (this can be the foldername)
* @param {Object} storageEngine any leveldown instance
* @param {String} password if the database contains encrypted fields
* @param {boolean} multiInstance if true, multiInstance-handling will be done
* @return {Promise}
*/
var create = exports.create = function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(prefix, storageEngine, password, multiInstance) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', RxDatabase.create(prefix, storageEngine, password, multiInstance));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function create(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
}();
exports.plugin = plugin;
var _RxDatabase = require('./RxDatabase');
var RxDatabase = _interopRequireWildcard(_RxDatabase);
var _RxSchema = require('./RxSchema');
var RxSchema = _interopRequireWildcard(_RxSchema);
var _PouchDB = require('./PouchDB');
var _PouchDB2 = _interopRequireDefault(_PouchDB);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function plugin(mod) {
_PouchDB2.default.plugin(mod);
}
exports.RxSchema = RxSchema;
exports.PouchDB = _PouchDB2.default;
},{"./PouchDB":2,"./RxDatabase":5,"./RxSchema":8,"babel-runtime/helpers/asyncToGenerator":24,"babel-runtime/regenerator":28}],11:[function(require,module,exports){
/**
* this is copied from
* @link https://github.com/aheckmann/mquery/blob/master/lib/mquery.js
*/
'use strict';
/**
* Dependencies
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var slice = require('sliced');
var utils = require('./mquery_utils');
/**
* Query constructor used for building queries.
*
* ####Example:
*
* var query = new Query({ name: 'mquery' });
* query.setOptions({ collection: moduleCollection })
* query.where('age').gte(21).exec(callback);
*
* @param {Object} [criteria]
* @param {Object} [options]
* @api public
*/
function Query(criteria, options) {
if (!(this instanceof Query)) return new Query(criteria, options);
var proto = this.constructor.prototype;
this.op = proto.op || undefined;
this.options = {};
this.setOptions(proto.options);
this._conditions = proto._conditions ? utils.clone(proto._conditions, {
retainKeyOrder: this.options.retainKeyOrder
}) : {};
this._fields = proto._fields ? utils.clone(proto._fields, {
retainKeyOrder: this.options.retainKeyOrder
}) : undefined;
this._update = proto._update ? utils.clone(proto._update, {
retainKeyOrder: this.options.retainKeyOrder
}) : undefined;
this._path = proto._path || undefined;
this._distinct = proto._distinct || undefined;
this._traceFunction = proto._traceFunction || undefined;
if (options) {
this.setOptions(options);
}
if (criteria) {
if (criteria.find && criteria.remove && criteria.update) {
// quack quack!
this.collection(criteria);
} else {
this.find(criteria);
}
}
}
/**
* This is a parameter that the user can set which determines if mquery
* uses $within or $geoWithin for queries. It defaults to true which
* means $geoWithin will be used. If using MongoDB < 2.4 you should
* set this to false.
*
* @api public
* @property use$geoWithin
*/
var $withinCmd = '$geoWithin';
Object.defineProperty(Query, 'use$geoWithin', {
get: function get() {
return $withinCmd == '$geoWithin';
},
set: function set(v) {
if (true === v) {
// mongodb >= 2.4
$withinCmd = '$geoWithin';
} else {
$withinCmd = '$within';
}
}
});
/**
* Converts this query to a constructor function with all arguments and options retained.
*
* ####Example
*
* // Create a query that will read documents with a "video" category from
* // `aCollection` on the primary node in the replica-set unless it is down,
* // in which case we'll read from a secondary node.
* var query = mquery({ category: 'video' })
* query.setOptions({ collection: aCollection, read: 'primaryPreferred' });
*
* // create a constructor based off these settings
* var Video = query.toConstructor();
*
* // Video is now a subclass of mquery() and works the same way but with the
* // default query parameters and options set.
*
* // run a query with the previous settings but filter for movies with names
* // that start with "Life".
* Video().where({ name: /^Life/ }).exec(cb);
*
* @return {Query} new Query
* @api public
*/
Query.prototype.toConstructor = function toConstructor() {
function CustomQuery(criteria, options) {
if (!(this instanceof CustomQuery)) return new CustomQuery(criteria, options);
Query.call(this, criteria, options);
}
utils.inherits(CustomQuery, Query);
// set inherited defaults
var p = CustomQuery.prototype;
p.options = {};
p.setOptions(this.options);
p.op = this.op;
p._conditions = utils.clone(this._conditions, {
retainKeyOrder: this.options.retainKeyOrder
});
p._fields = utils.clone(this._fields, {
retainKeyOrder: this.options.retainKeyOrder
});
p._update = utils.clone(this._update, {
retainKeyOrder: this.options.retainKeyOrder
});
p._path = this._path;
p._distinct = this._distinct;
p._traceFunction = this._traceFunction;
return CustomQuery;
};
/**
* Sets query options.
*
* ####Options:
*
* - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) *
* - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) *
* - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) *
* - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) *
* - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) *
* - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) *
* - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) *
* - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) *
* - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) *
* - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) *
* - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) *
* - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command)
* - collection the collection to query against
*
* _* denotes a query helper method is also available_
*
* @param {Object} options
* @api public
*/
Query.prototype.setOptions = function (options) {
if (!(options && utils.isObject(options))) return this;
// set arbitrary options
var methods = utils.keys(options),
method;
for (var i = 0; i < methods.length; ++i) {
method = methods[i];
// use methods if exist (safer option manipulation)
if ('function' == typeof this[method]) {
var args = utils.isArray(options[method]) ? options[method] : [options[method]];
this[method].apply(this, args);
} else {
this.options[method] = options[method];
}
}
return this;
};
/**
* Specifies a `$where` condition
*
* Use `$where` when you need to select documents using a JavaScript expression.
*
* ####Example
*
* query.$where('this.comments.length > 10 || this.name.length > 5')
*
* query.$where(function () {
* return this.comments.length > 10 || this.name.length > 5;
* })
*
* @param {String|Function} js javascript string or function
* @return {Query} this
* @memberOf Query
* @method $where
* @api public
*/
Query.prototype.$where = function (js) {
this._conditions.$where = js;
return this;
};
/**
* Specifies a `path` for use with chaining.
*
* ####Example
*
* // instead of writing:
* User.find({age: {$gte: 21, $lte: 65}}, callback);
*
* // we can instead write:
* User.where('age').gte(21).lte(65);
*
* // passing query conditions is permitted
* User.find().where({ name: 'vonderful' })
*
* // chaining
* User
* .where('age').gte(21).lte(65)
* .where('name', /^vonderful/i)
* .where('friends').slice(10)
* .exec(callback)
*
* @param {String} [path]
* @param {Object} [val]
* @return {Query} this
* @api public
*/
Query.prototype.where = function () {
if (!arguments.length) return this;
if (!this.op) this.op = 'find';
var type = (0, _typeof3.default)(arguments[0]);
if ('string' == type) {
this._path = arguments[0];
if (2 === arguments.length) {
this._conditions[this._path] = arguments[1];
}
return this;
}
if ('object' == type && !Array.isArray(arguments[0])) {
return this.merge(arguments[0]);
}
throw new TypeError('path must be a string or object');
};
/**
* Specifies the complementary comparison value for paths specified with `where()`
*
* ####Example
*
* User.where('age').equals(49);
*
* // is the same as
*
* User.where('age', 49);
*
* @param {Object} val
* @return {Query} this
* @api public
*/
Query.prototype.equals = function equals(val) {
this._ensurePath('equals');
var path = this._path;
this._conditions[path] = val;
return this;
};
/**
* Specifies the complementary comparison value for paths specified with `where()`
* This is alias of `equals`
*
* ####Example
*
* User.where('age').eq(49);
*
* // is the same as
*
* User.shere('age').equals(49);
*
* // is the same as
*
* User.where('age', 49);
*
* @param {Object} val
* @return {Query} this
* @api public
*/
Query.prototype.eq = function eq(val) {
this._ensurePath('eq');
var path = this._path;
this._conditions[path] = val;
return this;
};
/**
* Specifies arguments for an `$or` condition.
*
* ####Example
*
* query.or([{ color: 'red' }, { status: 'emergency' }])
*
* @param {Array} array array of conditions
* @return {Query} this
* @api public
*/
Query.prototype.or = function or(array) {
var or = this._conditions.$or || (this._conditions.$or = []);
if (!utils.isArray(array)) array = [array];
or.push.apply(or, array);
return this;
};
/**
* Specifies arguments for a `$nor` condition.
*
* ####Example
*
* query.nor([{ color: 'green' }, { status: 'ok' }])
*
* @param {Array} array array of conditions
* @return {Query} this
* @api public
*/
Query.prototype.nor = function nor(array) {
var nor = this._conditions.$nor || (this._conditions.$nor = []);
if (!utils.isArray(array)) array = [array];
nor.push.apply(nor, array);
return this;
};
/**
* Specifies arguments for a `$and` condition.
*
* ####Example
*
* query.and([{ color: 'green' }, { status: 'ok' }])
*
* @see $and http://docs.mongodb.org/manual/reference/operator/and/
* @param {Array} array array of conditions
* @return {Query} this
* @api public
*/
Query.prototype.and = function and(array) {
var and = this._conditions.$and || (this._conditions.$and = []);
if (!Array.isArray(array)) array = [array];
and.push.apply(and, array);
return this;
};
/**
* Specifies a $gt query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* ####Example
*
* Thing.find().where('age').gt(21)
*
* // or
* Thing.find().gt('age', 21)
*
* @method gt
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $gte query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method gte
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $lt query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method lt
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $lte query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method lte
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $ne query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method ne
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies an $in query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method in
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies an $nin query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method nin
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies an $all query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method all
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $size query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method size
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $regex query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method regex
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/**
* Specifies a $maxDistance query condition.
*
* When called with one argument, the most recent path passed to `where()` is used.
*
* @method maxDistance
* @memberOf Query
* @param {String} [path]
* @param {Number} val
* @api public
*/
/*!
* gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance
*
* Thing.where('type').nin(array)
*/
'gt gte lt lte ne in nin all regex size maxDistance minDistance'.split(' ').forEach(function ($conditional) {
Query.prototype[$conditional] = function () {
var path, val;
if (1 === arguments.length) {
this._ensurePath($conditional);
val = arguments[0];
path = this._path;
} else {
val = arguments[1];
path = arguments[0];
}
var conds = this._conditions[path] === null || (0, _typeof3.default)(this._conditions[path]) === 'object' ? this._conditions[path] : this._conditions[path] = {};
conds['$' + $conditional] = val;
return this;
};
});
/**
* Specifies a `$mod` condition
*
* @param {String} [path]
* @param {Number} val
* @return {Query} this
* @api public
*/
Query.prototype.mod = function () {
var val, path;
if (1 === arguments.length) {
this._ensurePath('mod');
val = arguments[0];
path = this._path;
} else if (2 === arguments.length && !utils.isArray(arguments[1])) {
this._ensurePath('mod');
val = slice(arguments);
path = this._path;
} else if (3 === arguments.length) {
val = slice(arguments, 1);
path = arguments[0];
} else {
val = arguments[1];
path = arguments[0];
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds.$mod = val;
return this;
};
/**
* Specifies an `$exists` condition
*
* ####Example
*
* // { name: { $exists: true }}
* Thing.where('name').exists()
* Thing.where('name').exists(true)
* Thing.find().exists('name')
*
* // { name: { $exists: false }}
* Thing.where('name').exists(false);
* Thing.find().exists('name', false);
*
* @param {String} [path]
* @param {Number} val
* @return {Query} this
* @api public
*/
Query.prototype.exists = function () {
var path, val;
if (0 === arguments.length) {
this._ensurePath('exists');
path = this._path;
val = true;
} else if (1 === arguments.length) {
if ('boolean' === typeof arguments[0]) {
this._ensurePath('exists');
path = this._path;
val = arguments[0];
} else {
path = arguments[0];
val = true;
}
} else if (2 === arguments.length) {
path = arguments[0];
val = arguments[1];
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds.$exists = val;
return this;
};
/**
* Specifies an `$elemMatch` condition
*
* ####Example
*
* query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
*
* query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
*
* query.elemMatch('comment', function (elem) {
* elem.where('author').equals('autobot');
* elem.where('votes').gte(5);
* })
*
* query.where('comment').elemMatch(function (elem) {
* elem.where({ author: 'autobot' });
* elem.where('votes').gte(5);
* })
*
* @param {String|Object|Function} path
* @param {Object|Function} criteria
* @return {Query} this
* @api public
*/
Query.prototype.elemMatch = function () {
if (null == arguments[0]) throw new TypeError("Invalid argument");
var fn, path, criteria;
if ('function' === typeof arguments[0]) {
this._ensurePath('elemMatch');
path = this._path;
fn = arguments[0];
} else if (utils.isObject(arguments[0])) {
this._ensurePath('elemMatch');
path = this._path;
criteria = arguments[0];
} else if ('function' === typeof arguments[1]) {
path = arguments[0];
fn = arguments[1];
} else if (arguments[1] && utils.isObject(arguments[1])) {
path = arguments[0];
criteria = arguments[1];
} else {
throw new TypeError("Invalid argument");
}
if (fn) {
criteria = new Query();
fn(criteria);
criteria = criteria._conditions;
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds.$elemMatch = criteria;
return this;
};
// Spatial queries
/**
* Sugar for geo-spatial queries.
*
* ####Example
*
* query.within().box()
* query.within().circle()
* query.within().geometry()
*
* query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
* query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
* query.where('loc').within({ polygon: [[],[],[],[]] });
*
* query.where('loc').within([], [], []) // polygon
* query.where('loc').within([], []) // box
* query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
*
* #### n o t e:
*
* Must be used after `where()`.
*
* @memberOf Query
* @return {Query} this
* @api public
*/
Query.prototype.within = function within() {
// opinionated, must be used after where
this._ensurePath('within');
this._geoComparison = $withinCmd;
if (0 === arguments.length) {
return this;
}
if (2 === arguments.length) {
return this.box.apply(this, arguments);
} else if (2 < arguments.length) {
return this.polygon.apply(this, arguments);
}
var area = arguments[0];
if (!area) throw new TypeError('Invalid argument');
if (area.center) return this.circle(area);
if (area.box) return this.box.apply(this, area.box);
if (area.polygon) return this.polygon.apply(this, area.polygon);
if (area.type && area.coordinates) return this.geometry(area);
throw new TypeError('Invalid argument');
};
/**
* Specifies a $box condition
*
* ####Example
*
* var lowerLeft = [40.73083, -73.99756]
* var upperRight= [40.741404, -73.988135]
*
* query.where('loc').within().box(lowerLeft, upperRight)
* query.box('loc', lowerLeft, upperRight )
*
* @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
* @see Query#within #query_Query-within
* @param {String} path
* @param {Object} val
* @return {Query} this
* @api public
*/
Query.prototype.box = function () {
var path, box;
if (3 === arguments.length) {
// box('loc', [], [])
path = arguments[0];
box = [arguments[1], arguments[2]];
} else if (2 === arguments.length) {
// box([], [])
this._ensurePath('box');
path = this._path;
box = [arguments[0], arguments[1]];
} else {
throw new TypeError("Invalid argument");
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds[this._geoComparison || $withinCmd] = {
'$box': box
};
return this;
};
/**
* Specifies a $polygon condition
*
* ####Example
*
* query.where('loc').within().polygon([10,20], [13, 25], [7,15])
* query.polygon('loc', [10,20], [13, 25], [7,15])
*
* @param {String|Array} [path]
* @param {Array|Object} [val]
* @return {Query} this
* @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
* @api public
*/
Query.prototype.polygon = function () {
var val, path;
if ('string' == typeof arguments[0]) {
// polygon('loc', [],[],[])
path = arguments[0];
val = slice(arguments, 1);
} else {
// polygon([],[],[])
this._ensurePath('polygon');
path = this._path;
val = slice(arguments);
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds[this._geoComparison || $withinCmd] = {
'$polygon': val
};
return this;
};
/**
* Specifies a $center or $centerSphere condition.
*
* ####Example
*
* var area = { center: [50, 50], radius: 10, unique: true }
* query.where('loc').within().circle(area)
* query.center('loc', area);
*
* // for spherical calculations
* var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
* query.where('loc').within().circle(area)
* query.center('loc', area);
*
* @param {String} [path]
* @param {Object} area
* @return {Query} this
* @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
* @api public
*/
Query.prototype.circle = function () {
var path, val;
if (1 === arguments.length) {
this._ensurePath('circle');
path = this._path;
val = arguments[0];
} else if (2 === arguments.length) {
path = arguments[0];
val = arguments[1];
} else {
throw new TypeError("Invalid argument");
}
if (!('radius' in val && val.center)) throw new Error('center and radius are required');
var conds = this._conditions[path] || (this._conditions[path] = {});
var type = val.spherical ? '$centerSphere' : '$center';
var wKey = this._geoComparison || $withinCmd;
conds[wKey] = {};
conds[wKey][type] = [val.center, val.radius];
if ('unique' in val) conds[wKey].$uniqueDocs = !!val.unique;
return this;
};
/**
* Specifies a `$near` or `$nearSphere` condition
*
* These operators return documents sorted by distance.
*
* ####Example
*
* query.where('loc').near({ center: [10, 10] });
* query.where('loc').near({ center: [10, 10], maxDistance: 5 });
* query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
* query.near('loc', { center: [10, 10], maxDistance: 5 });
* query.near({ center: { type: 'Point', coordinates: [..] }})
* query.near().geometry({ type: 'Point', coordinates: [..] })
*
* @param {String} [path]
* @param {Object} val
* @return {Query} this
* @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
* @api public
*/
Query.prototype.near = function near() {
var path, val;
this._geoComparison = '$near';
if (0 === arguments.length) {
return this;
} else if (1 === arguments.length) {
this._ensurePath('near');
path = this._path;
val = arguments[0];
} else if (2 === arguments.length) {
path = arguments[0];
val = arguments[1];
} else {
throw new TypeError("Invalid argument");
}
if (!val.center) {
throw new Error('center is required');
}
var conds = this._conditions[path] || (this._conditions[path] = {});
var type = val.spherical ? '$nearSphere' : '$near';
// center could be a GeoJSON object or an Array
if (Array.isArray(val.center)) {
conds[type] = val.center;
var radius = 'maxDistance' in val ? val.maxDistance : null;
if (null != radius) {
conds.$maxDistance = radius;
}
if (null != val.minDistance) {
conds.$minDistance = val.minDistance;
}
} else {
// GeoJSON?
if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) {
throw new Error("Invalid GeoJSON specified for " + type);
}
conds[type] = {
$geometry: val.center
};
// MongoDB 2.6 insists on maxDistance being in $near / $nearSphere
if ('maxDistance' in val) {
conds[type]['$maxDistance'] = val.maxDistance;
}
if ('minDistance' in val) {
conds[type]['$minDistance'] = val.minDistance;
}
}
return this;
};
/**
* Declares an intersects query for `geometry()`.
*
* ####Example
*
* query.where('path').intersects().geometry({
* type: 'LineString'
* , coordinates: [[180.0, 11.0], [180, 9.0]]
* })
*
* query.where('path').intersects({
* type: 'LineString'
* , coordinates: [[180.0, 11.0], [180, 9.0]]
* })
*
* @param {Object} [arg]
* @return {Query} this
* @api public
*/
Query.prototype.intersects = function intersects() {
// opinionated, must be used after where
this._ensurePath('intersects');
this._geoComparison = '$geoIntersects';
if (0 === arguments.length) {
return this;
}
var area = arguments[0];
if (null != area && area.type && area.coordinates) return this.geometry(area);
throw new TypeError('Invalid argument');
};
/**
* Specifies a `$geometry` condition
*
* ####Example
*
* var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
* query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
*
* // or
* var polyB = [[ 0, 0 ], [ 1, 1 ]]
* query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
*
* // or
* var polyC = [ 0, 0 ]
* query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
*
* // or
* query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
*
* #### N O T E :
*
* `geometry()` **must** come after either `intersects()` or `within()`.
*
* The `object` argument must contain `type` and `coordinates` properties.
* - type {String}
* - coordinates {Array}
*
* The most recent path passed to `where()` is used.
*
* @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
* @return {Query} this
* @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
* @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
* @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
* @api public
*/
Query.prototype.geometry = function geometry() {
if (!('$within' == this._geoComparison || '$geoWithin' == this._geoComparison || '$near' == this._geoComparison || '$geoIntersects' == this._geoComparison)) {
throw new Error('geometry() must come after `within()`, `intersects()`, or `near()');
}
var val, path;
if (1 === arguments.length) {
this._ensurePath('geometry');
path = this._path;
val = arguments[0];
} else {
throw new TypeError("Invalid argument");
}
if (!(val.type && Array.isArray(val.coordinates))) {
throw new TypeError('Invalid argument');
}
var conds = this._conditions[path] || (this._conditions[path] = {});
conds[this._geoComparison] = {
$geometry: val
};
return this;
};
// end spatial
/**
* Specifies which document fields to include or exclude
*
* ####String syntax
*
* When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included.
*
* ####Example
*
* // include a and b, exclude c
* query.select('a b -c');
*
* // or you may use object notation, useful when
* // you have keys already prefixed with a "-"
* query.select({a: 1, b: 1, c: 0});
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @param {Object|String} arg
* @return {Query} this
* @see SchemaType
* @api public
*/
Query.prototype.select = function select() {
var arg = arguments[0];
if (!arg) return this;
if (arguments.length !== 1) {
throw new Error("Invalid select: select only takes 1 argument");
}
this._validate('select');
var fields = this._fields || (this._fields = {});
var type = typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg);
if (('string' == type || utils.isArgumentsObject(arg)) && 'number' == typeof arg.length) {
if ('string' == type) arg = arg.split(/\s+/);
for (var i = 0, len = arg.length; i < len; ++i) {
var field = arg[i];
if (!field) continue;
var include = '-' == field[0] ? 0 : 1;
if (include === 0) field = field.substring(1);
fields[field] = include;
}
return this;
}
if (utils.isObject(arg) && !Array.isArray(arg)) {
var keys = utils.keys(arg);
for (var i = 0; i < keys.length; ++i) {
fields[keys[i]] = arg[keys[i]];
}
return this;
}
throw new TypeError('Invalid select() argument. Must be string or object.');
};
/**
* Specifies a $slice condition for a `path`
*
* ####Example
*
* query.slice('comments', 5)
* query.slice('comments', -5)
* query.slice('comments', [10, 5])
* query.where('comments').slice(5)
* query.where('comments').slice([-10, 5])
*
* @param {String} [path]
* @param {Number} val number/range of elements to slice
* @return {Query} this
* @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
* @api public
*/
Query.prototype.slice = function () {
if (0 === arguments.length) return this;
this._validate('slice');
var path, val;
if (1 === arguments.length) {
var arg = arguments[0];
if ((typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg)) === 'object' && !Array.isArray(arg)) {
var keys = Object.keys(arg);
var numKeys = keys.length;
for (var i = 0; i < numKeys; ++i) {
this.slice(keys[i], arg[keys[i]]);
}
return this;
}
this._ensurePath('slice');
path = this._path;
val = arguments[0];
} else if (2 === arguments.length) {
if ('number' === typeof arguments[0]) {
this._ensurePath('slice');
path = this._path;
val = slice(arguments);
} else {
path = arguments[0];
val = arguments[1];
}
} else if (3 === arguments.length) {
path = arguments[0];
val = slice(arguments, 1);
}
var myFields = this._fields || (this._fields = {});
myFields[path] = {
'$slice': val
};
return this;
};
/**
* Sets the sort order
*
* If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.
*
* If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
*
* ####Example
*
* // these are equivalent
* query.sort({ field: 'asc', test: -1 });
* query.sort('field -test');
* query.sort([['field', 1], ['test', -1]]);
*
* ####Note
*
* - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15).
* - Cannot be used with `distinct()`
*
* @param {Object|String|Array} arg
* @return {Query} this
* @api public
*/
Query.prototype.sort = function (arg) {
if (!arg) return this;
var len;
this._validate('sort');
var type = typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg);
// .sort([['field', 1], ['test', -1]])
if (Array.isArray(arg)) {
len = arg.length;
for (var i = 0; i < arg.length; ++i) {
_pushArr(this.options, arg[i][0], arg[i][1]);
}
return this;
}
// .sort('field -test')
if (1 === arguments.length && 'string' == type) {
arg = arg.split(/\s+/);
len = arg.length;
for (var i = 0; i < len; ++i) {
var field = arg[i];
if (!field) continue;
var ascend = '-' == field[0] ? -1 : 1;
if (ascend === -1) field = field.substring(1);
push(this.options, field, ascend);
}
return this;
}
// .sort({ field: 1, test: -1 })
if (utils.isObject(arg)) {
var keys = utils.keys(arg);
for (var i = 0; i < keys.length; ++i) {
var field = keys[i];
push(this.options, field, arg[field]);
}
return this;
}
throw new TypeError('Invalid sort() argument. Must be a string, object, or array.');
};
/*!
* @ignore
*/
function push(opts, field, value) {
if (Array.isArray(opts.sort)) {
throw new TypeError("Can't mix sort syntaxes. Use either array or object:" + "\n- `.sort([['field', 1], ['test', -1]])`" + "\n- `.sort({ field: 1, test: -1 })`");
}
if (value && value.$meta) {
var s = opts.sort || (opts.sort = {});
s[field] = {
$meta: value.$meta
};
return;
}
var val = String(value || 1).toLowerCase();
if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {
if (utils.isArray(value)) value = '[' + value + ']';
throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }');
}
// store `sort` in a sane format
var s = opts.sort || (opts.sort = {});
var valueStr = value.toString().replace("asc", "1").replace("ascending", "1").replace("desc", "-1").replace("descending", "-1");
s[field] = parseInt(valueStr, 10);
}
function _pushArr(opts, field, value) {
opts.sort = opts.sort || [];
if (!Array.isArray(opts.sort)) {
throw new TypeError("Can't mix sort syntaxes. Use either array or object:" + "\n- `.sort([['field', 1], ['test', -1]])`" + "\n- `.sort({ field: 1, test: -1 })`");
}
var valueStr = value.toString().replace("asc", "1").replace("ascending", "1").replace("desc", "-1").replace("descending", "-1");
opts.sort.push([field, value]);
}
/**
* Specifies the limit option.
*
* ####Example
*
* query.limit(20)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method limit
* @memberOf Query
* @param {Number} val
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D
* @api public
*/
/**
* Specifies the skip option.
*
* ####Example
*
* query.skip(100).limit(20)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method skip
* @memberOf Query
* @param {Number} val
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D
* @api public
*/
/**
* Specifies the maxScan option.
*
* ####Example
*
* query.maxScan(100)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method maxScan
* @memberOf Query
* @param {Number} val
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan
* @api public
*/
/**
* Specifies the batchSize option.
*
* ####Example
*
* query.batchSize(100)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method batchSize
* @memberOf Query
* @param {Number} val
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D
* @api public
*/
/**
* Specifies the `comment` option.
*
* ####Example
*
* query.comment('login query')
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @method comment
* @memberOf Query
* @param {Number} val
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment
* @api public
*/
/*!
* limit, skip, maxScan, batchSize, comment
*
* Sets these associated options.
*
* query.comment('feed query');
*/
;
['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) {
Query.prototype[method] = function (v) {
this._validate(method);
this.options[method] = v;
return this;
};
});
/**
* Specifies the maxTimeMS option.
*
* ####Example
*
* query.maxTime(100)
*
* @method maxTime
* @memberOf Query
* @param {Number} val
* @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS
* @api public
*/
Query.prototype.maxTime = function (v) {
this._validate('maxTime');
this.options.maxTimeMS = v;
return this;
};
/**
* Specifies this query as a `snapshot` query.
*
* ####Example
*
* mquery().snapshot() // true
* mquery().snapshot(true)
* mquery().snapshot(false)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D
* @return {Query} this
* @api public
*/
Query.prototype.snapshot = function () {
this._validate('snapshot');
this.options.snapshot = arguments.length ? !!arguments[0] : true;
return this;
};
/**
* Sets query hints.
*
* ####Example
*
* query.hint({ indexA: 1, indexB: -1})
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @param {Object} val a hint object
* @return {Query} this
* @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint
* @api public
*/
Query.prototype.hint = function () {
if (0 === arguments.length) return this;
this._validate('hint');
var arg = arguments[0];
if (utils.isObject(arg)) {
var hint = this.options.hint || (this.options.hint = {});
// must keep object keys in order so don't use Object.keys()
for (var k in arg) {
hint[k] = arg[k];
}
return this;
}
throw new TypeError('Invalid hint. ' + arg);
};
/**
* Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences.
*
* ####Example:
*
* query.slaveOk() // true
* query.slaveOk(true)
* query.slaveOk(false)
*
* @deprecated use read() preferences instead if on mongodb >= 2.2
* @param {Boolean} v defaults to true
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
* @see read()
* @return {Query} this
* @api public
*/
Query.prototype.slaveOk = function (v) {
this.options.slaveOk = arguments.length ? !!v : true;
return this;
};
/**
* Sets the readPreference option for the query.
*
* ####Example:
*
* new Query().read('primary')
* new Query().read('p') // same as primary
*
* new Query().read('primaryPreferred')
* new Query().read('pp') // same as primaryPreferred
*
* new Query().read('secondary')
* new Query().read('s') // same as secondary
*
* new Query().read('secondaryPreferred')
* new Query().read('sp') // same as secondaryPreferred
*
* new Query().read('nearest')
* new Query().read('n') // same as nearest
*
* // you can also use mongodb.ReadPreference class to also specify tags
* new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]))
*
* ####Preferences:
*
* primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
* secondary Read from secondary if available, otherwise error.
* primaryPreferred Read from primary if available, otherwise a secondary.
* secondaryPreferred Read from a secondary if available, otherwise read from the primary.
* nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.
*
* Aliases
*
* p primary
* pp primaryPreferred
* s secondary
* sp secondaryPreferred
* n nearest
*
* Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
*
* @param {String|ReadPreference} pref one of the listed preference options or their aliases
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
* @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
* @return {Query} this
* @api public
*/
Query.prototype.read = function (pref) {
if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) {
console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.");
Query.prototype.read.deprecationWarningIssued = true;
}
this.options.readPreference = utils.readPref(pref);
return this;
};
/**
* Sets tailable option.
*
* ####Example
*
* query.tailable() <== true
* query.tailable(true)
* query.tailable(false)
*
* ####Note
*
* Cannot be used with `distinct()`
*
* @param {Boolean} v defaults to true
* @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors
* @api public
*/
Query.prototype.tailable = function () {
this._validate('tailable');
this.options.tailable = arguments.length ? !!arguments[0] : true;
return this;
};
/**
* Merges another Query or conditions object into this one.
*
* When a Query is passed, conditions, field selection and options are merged.
*
* @param {Query|Object} source
* @return {Query} this
*/
Query.prototype.merge = function (source) {
if (!source) return this;
if (!Query.canMerge(source)) throw new TypeError('Invalid argument. Expected instanceof mquery or plain object');
if (source instanceof Query) {
// if source has a feature, apply it to ourselves
if (source._conditions) {
utils.merge(this._conditions, source._conditions);
}
if (source._fields) {
this._fields || (this._fields = {});
utils.merge(this._fields, source._fields);
}
if (source.options) {
this.options || (this.options = {});
utils.merge(this.options, source.options);
}
if (source._update) {
this._update || (this._update = {});
utils.mergeClone(this._update, source._update);
}
if (source._distinct) {
this._distinct = source._distinct;
}
return this;
}
// plain object
utils.merge(this._conditions, source);
return this;
};
/**
* Finds documents.
*
* Passing a `callback` executes the query.
*
* ####Example
*
* query.find()
* query.find(callback)
* query.find({ name: 'Burning Lights' }, callback)
*
* @param {Object} [criteria] mongodb selector
* @param {Function} [callback]
* @return {Query} this
* @api public
*/
Query.prototype.find = function (criteria, callback) {
this.op = 'find';
if ('function' === typeof criteria) {
callback = criteria;
criteria = undefined;
} else if (Query.canMerge(criteria)) {
this.merge(criteria);
}
if (!callback) return this;
var self = this,
conds = this._conditions,
options = this._optionsForExec();
options.fields = this._fieldsForExec();
callback = this._wrapCallback('find', callback, {
conditions: conds,
options: options
});
return this;
};
/**
* Declares or executes a distinct() operation.
*
* Passing a `callback` executes the query.
*
* ####Example
*
* distinct(criteria, field, fn)
* distinct(criteria, field)
* distinct(field, fn)
* distinct(field)
* distinct(fn)
* distinct()
*
* @param {Object|Query} [criteria]
* @param {String} [field]
* @param {Function} [callback]
* @return {Query} this
* @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct
* @api public
*/
Query.prototype.distinct = function (criteria, field, callback) {
this.op = 'distinct';
this._validate();
if (!callback) {
switch (typeof field === 'undefined' ? 'undefined' : (0, _typeof3.default)(field)) {
case 'function':
callback = field;
if ('string' == typeof criteria) {
field = criteria;
criteria = undefined;
}
break;
case 'undefined':
case 'string':
break;
default:
throw new TypeError('Invalid `field` argument. Must be string or function');
break;
}
switch (typeof criteria === 'undefined' ? 'undefined' : (0, _typeof3.default)(criteria)) {
case 'function':
callback = criteria;
criteria = field = undefined;
break;
case 'string':
field = criteria;
criteria = undefined;
break;
}
}
if ('string' == typeof field) {
this._distinct = field;
}
if (Query.canMerge(criteria)) {
this.merge(criteria);
}
if (!callback) {
return this;
}
if (!this._distinct) {
throw new Error('No value for `distinct` has been declared');
}
var conds = this._conditions,
options = this._optionsForExec();
callback = this._wrapCallback('distinct', callback, {
conditions: conds,
options: options
});
this._collection.distinct(this._distinct, conds, options, utils.tick(callback));
return this;
};
/**
* Declare and/or execute this query as an update() operation.
*
* _All paths passed that are not $atomic operations will become $set ops._
*
* ####Example
*
* mquery({ _id: id }).update({ title: 'words' }, ...)
*
* becomes
*
* collection.update({ _id: id }, { $set: { title: 'words' }}, ...)
*
* ####Note
*
* Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.
*
* ####Note
*
* The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method.
*
* var q = mquery(collection).where({ _id: id });
* q.update({ $set: { name: 'bob' }}).update(); // not executed
*
* var q = mquery(collection).where({ _id: id });
* q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe
*
* // keys that are not $atomic ops become $set.
* // this executes the same command as the previous example.
* q.update({ name: 'bob' }).where({ _id: id }).exec();
*
* var q = mquery(collection).update(); // not executed
*
* // overwriting with empty docs
* var q.where({ _id: id }).setOptions({ overwrite: true })
* q.update({ }, callback); // executes
*
* // multi update with overwrite to empty doc
* var q = mquery(collection).where({ _id: id });
* q.setOptions({ multi: true, overwrite: true })
* q.update({ });
* q.update(callback); // executed
*
* // multi updates
* mquery()
* .collection(coll)
* .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
* // more multi updates
* mquery({ })
* .collection(coll)
* .setOptions({ multi: true })
* .update({ $set: { arr: [] }}, callback)
*
* // single update by default
* mquery({ email: 'address@example.com' })
* .collection(coll)
* .update({ $inc: { counter: 1 }}, callback)
*
* // summary
* update(criteria, doc, opts, cb) // executes
* update(criteria, doc, opts)
* update(criteria, doc, cb) // executes
* update(criteria, doc)
* update(doc, cb) // executes
* update(doc)
* update(cb) // executes
* update(true) // executes (unsafe write)
* update()
*
* @param {Object} [criteria]
* @param {Object} [doc] the update command
* @param {Object} [options]
* @param {Function} [callback]
* @return {Query} this
* @api public
*/
Query.prototype.update = function update(criteria, doc, options, callback) {
this.op = 'update';
var force;
switch (arguments.length) {
case 3:
if ('function' == typeof options) {
callback = options;
options = undefined;
}
break;
case 2:
if ('function' == typeof doc) {
callback = doc;
doc = criteria;
criteria = undefined;
}
break;
case 1:
switch (typeof criteria === 'undefined' ? 'undefined' : (0, _typeof3.default)(criteria)) {
case 'function':
callback = criteria;
criteria = options = doc = undefined;
break;
case 'boolean':
// execution with no callback (unsafe write)
force = criteria;
criteria = undefined;
break;
default:
doc = criteria;
criteria = options = undefined;
break;
}
}
if (Query.canMerge(criteria)) {
this.merge(criteria);
}
if (doc) {
this._mergeUpdate(doc);
}
if (utils.isObject(options)) {
// { overwrite: true }
this.setOptions(options);
}
// we are done if we don't have callback and they are
// not forcing an unsafe write.
if (!(force || callback)) return this;
if (!this._update || !this.options.overwrite && 0 === utils.keys(this._update).length) {
callback && utils.soon(callback.bind(null, null, 0));
return this;
}
options = this._optionsForExec();
if (!callback) options.safe = false;
var criteria = this._conditions;
doc = this._updateForExec();
callback = this._wrapCallback('update', callback, {
conditions: criteria,
doc: doc,
options: options
});
this._collection.update(criteria, doc, options, utils.tick(callback));
return this;
};
/**
* Declare and/or execute this query as a remove() operation.
*
* ####Example
*
* mquery(collection).remove({ artist: 'Anne Murray' }, callback)
*
* ####Note
*
* The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method.
*
* // not executed
* var query = mquery(collection).remove({ name: 'Anne Murray' })
*
* // executed
* mquery(collection).remove({ name: 'Anne Murray' }, callback)
* mquery(collection).remove({ name: 'Anne Murray' }).remove(callback)
*
* // executed without a callback (unsafe write)
* query.exec()
*
* // summary
* query.remove(conds, fn); // executes
* query.remove(conds)
* query.remove(fn) // executes
* query.remove()
*
* @param {Object|Query} [criteria] mongodb selector
* @param {Function} [callback]
* @return {Query} this
* @api public
*/
Query.prototype.remove = function (criteria, callback) {
this.op = 'remove';
var force;
if ('function' === typeof criteria) {
callback = criteria;
criteria = undefined;
} else if (Query.canMerge(criteria)) {
this.merge(criteria);
} else if (true === criteria) {
force = criteria;
criteria = undefined;
}
if (!(force || callback)) return this;
var options = this._optionsForExec();
if (!callback) options.safe = false;
var conds = this._conditions;
callback = this._wrapCallback('remove', callback, {
conditions: conds,
options: options
});
this._collection.remove(conds, options, utils.tick(callback));
return this;
};
/**
* Wrap callback to add tracing
*
* @param {Function} callback
* @param {Object} [queryInfo]
* @api private
*/
Query.prototype._wrapCallback = function (method, callback, queryInfo) {
var traceFunction = this._traceFunction || Query.traceFunction;
if (traceFunction) {
queryInfo.collectionName = this._collection.collectionName;
var traceCallback = traceFunction && traceFunction.call(null, method, queryInfo, this);
var startTime = new Date().getTime();
return function wrapperCallback(err, result) {
if (traceCallback) {
var millis = new Date().getTime() - startTime;
traceCallback.call(null, err, result, millis);
}
if (callback) {
callback.apply(null, arguments);
}
};
}
return callback;
};
/**
* Determines if field selection has been made.
*
* @return {Boolean}
* @api public
*/
Query.prototype.selected = function selected() {
return !!(this._fields && Object.keys(this._fields).length > 0);
};
/**
* Determines if inclusive field selection has been made.
*
* query.selectedInclusively() // false
* query.select('name')
* query.selectedInclusively() // true
* query.selectedExlusively() // false
*
* @returns {Boolean}
*/
Query.prototype.selectedInclusively = function selectedInclusively() {
if (!this._fields) return false;
var keys = Object.keys(this._fields);
if (0 === keys.length) return false;
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (0 === this._fields[key]) return false;
if (this._fields[key] && (0, _typeof3.default)(this._fields[key]) === 'object' && this._fields[key].$meta) {
return false;
}
}
return true;
};
/**
* Determines if exclusive field selection has been made.
*
* query.selectedExlusively() // false
* query.select('-name')
* query.selectedExlusively() // true
* query.selectedInclusively() // false
*
* @returns {Boolean}
*/
Query.prototype.selectedExclusively = function selectedExclusively() {
if (!this._fields) return false;
var keys = Object.keys(this._fields);
if (0 === keys.length) return false;
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (0 === this._fields[key]) return true;
}
return false;
};
/**
* Merges `doc` with the current update object.
*
* @param {Object} doc
*/
Query.prototype._mergeUpdate = function (doc) {
if (!this._update) this._update = {};
if (doc instanceof Query) {
if (doc._update) {
utils.mergeClone(this._update, doc._update);
}
} else {
utils.mergeClone(this._update, doc);
}
};
/**
* Returns default options.
*
* @return {Object}
* @api private
*/
Query.prototype._optionsForExec = function () {
var options = utils.clone(this.options, {
retainKeyOrder: true
});
return options;
};
/**
* Returns fields selection for this query.
*
* @return {Object}
* @api private
*/
Query.prototype._fieldsForExec = function () {
return utils.clone(this._fields, {
retainKeyOrder: true
});
};
/**
* Return an update document with corrected $set operations.
*
* @api private
*/
Query.prototype._updateForExec = function () {
var update = utils.clone(this._update, {
retainKeyOrder: true
}),
ops = utils.keys(update),
i = ops.length,
ret = {},
hasKeys,
val;
while (i--) {
var op = ops[i];
if (this.options.overwrite) {
ret[op] = update[op];
continue;
}
if ('$' !== op[0]) {
// fix up $set sugar
if (!ret.$set) {
if (update.$set) {
ret.$set = update.$set;
} else {
ret.$set = {};
}
}
ret.$set[op] = update[op];
ops.splice(i, 1);
if (!~ops.indexOf('$set')) ops.push('$set');
} else if ('$set' === op) {
if (!ret.$set) {
ret[op] = update[op];
}
} else {
ret[op] = update[op];
}
}
this._compiledUpdate = ret;
return ret;
};
/**
* Make sure _path is set.
*
* @parmam {String} method
*/
Query.prototype._ensurePath = function (method) {
if (!this._path) {
var msg = method + '() must be used after where() ' + 'when called with these arguments';
throw new Error(msg);
}
};
/*!
* Permissions
*/
Query._isPermitted = function (a, b) {
return false;
};
Query.prototype._validate = function (action) {};
/**
* Determines if `conds` can be merged using `mquery().merge()`
*
* @param {Object} conds
* @return {Boolean}
*/
Query.canMerge = function (conds) {
return conds instanceof Query || utils.isObject(conds);
};
/**
* Set a trace function that will get called whenever a
* query is executed.
*
* See `setTraceFunction()` for details.
*
* @param {Object} conds
* @return {Boolean}
*/
Query.setGlobalTraceFunction = function (traceFunction) {
Query.traceFunction = traceFunction;
};
/*!
* Exports.
*/
Query.utils = utils;
exports.default = Query;
},{"./mquery_utils":12,"babel-runtime/helpers/typeof":27,"sliced":311}],12:[function(require,module,exports){
(function (process,Buffer){
/**
* this is copied from
* @link https://github.com/aheckmann/mquery/blob/master/lib/utils.js
*/
'use strict';
/*!
* Module dependencies.
*/
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var RegExpClone = require('regexp-clone');
/**
* Clones objects
*
* @param {Object} obj the object to clone
* @param {Object} options
* @return {Object} the cloned object
* @api private
*/
var clone = exports.clone = function clone(obj, options) {
if (obj === undefined || obj === null) return obj;
if (Array.isArray(obj)) return exports.cloneArray(obj, options);
if (obj.constructor) {
if (/ObjectI[dD]$/.test(obj.constructor.name)) {
return 'function' == typeof obj.clone ? obj.clone() : new obj.constructor(obj.id);
}
if ('ReadPreference' === obj._type && obj.isValid && obj.toObject) {
return 'function' == typeof obj.clone ? obj.clone() : new obj.constructor(obj.mode, clone(obj.tags, options));
}
if ('Binary' == obj._bsontype && obj.buffer && obj.value) {
return 'function' == typeof obj.clone ? obj.clone() : new obj.constructor(obj.value(true), obj.sub_type);
}
if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) return new obj.constructor(+obj);
if ('RegExp' === obj.constructor.name) return RegExpClone(obj);
if ('Buffer' === obj.constructor.name) return exports.cloneBuffer(obj);
}
if (isObject(obj)) return exports.cloneObject(obj, options);
if (obj.valueOf) return obj.valueOf();
};
/*!
* ignore
*/
var cloneObject = exports.cloneObject = function cloneObject(obj, options) {
var retainKeyOrder = options && options.retainKeyOrder,
minimize = options && options.minimize,
ret = {},
hasKeys,
keys,
val,
k,
i;
if (retainKeyOrder) {
for (k in obj) {
val = clone(obj[k], options);
if (!minimize || 'undefined' !== typeof val) {
hasKeys || (hasKeys = true);
ret[k] = val;
}
}
} else {
// faster
keys = Object.keys(obj);
i = keys.length;
while (i--) {
k = keys[i];
val = clone(obj[k], options);
if (!minimize || 'undefined' !== typeof val) {
if (!hasKeys) hasKeys = true;
ret[k] = val;
}
}
}
return minimize ? hasKeys && ret : ret;
};
var cloneArray = exports.cloneArray = function cloneArray(arr, options) {
var ret = [];
for (var i = 0, l = arr.length; i < l; i++) {
ret.push(clone(arr[i], options));
}return ret;
};
/**
* process.nextTick helper.
*
* Wraps the given `callback` in a try/catch. If an error is
* caught it will be thrown on nextTick.
*
* node-mongodb-native had a habit of state corruption when
* an error was immediately thrown from within a collection
* method (find, update, etc) callback.
*
* @param {Function} [callback]
* @api private
*/
var tick = exports.tick = function tick(callback) {
if ('function' !== typeof callback) return;
return function () {
// callbacks should always be fired on the next
// turn of the event loop. A side benefit is
// errors thrown from executing the callback
// will not cause drivers state to be corrupted
// which has historically been a problem.
var args = arguments;
soon(function () {
callback.apply(this, args);
});
};
};
/**
* Merges `from` into `to` without overwriting existing properties.
*
* @param {Object} to
* @param {Object} from
* @api private
*/
var merge = exports.merge = function merge(to, from) {
var keys = Object.keys(from),
i = keys.length,
key;
while (i--) {
key = keys[i];
if ('undefined' === typeof to[key]) {
to[key] = from[key];
} else {
if (exports.isObject(from[key])) {
merge(to[key], from[key]);
} else {
to[key] = from[key];
}
}
}
};
/**
* Same as merge but clones the assigned values.
*
* @param {Object} to
* @param {Object} from
* @api private
*/
var mergeClone = exports.mergeClone = function mergeClone(to, from) {
var keys = Object.keys(from),
i = keys.length,
key;
while (i--) {
key = keys[i];
if ('undefined' === typeof to[key]) {
// make sure to retain key order here because of a bug handling the $each
// operator in mongodb 2.4.4
to[key] = clone(from[key], {
retainKeyOrder: 1
});
} else {
if (exports.isObject(from[key])) {
mergeClone(to[key], from[key]);
} else {
// make sure to retain key order here because of a bug handling the
// $each operator in mongodb 2.4.4
to[key] = clone(from[key], {
retainKeyOrder: 1
});
}
}
}
};
/**
* Read pref helper (mongo 2.2 drivers support this)
*
* Allows using aliases instead of full preference names:
*
* p primary
* pp primaryPreferred
* s secondary
* sp secondaryPreferred
* n nearest
*
* @param {String} pref
*/
exports.readPref = function readPref(pref) {
switch (pref) {
case 'p':
pref = 'primary';
break;
case 'pp':
pref = 'primaryPreferred';
break;
case 's':
pref = 'secondary';
break;
case 'sp':
pref = 'secondaryPreferred';
break;
case 'n':
pref = 'nearest';
break;
}
return pref;
};
/**
* Object.prototype.toString.call helper
*/
var _toString = Object.prototype.toString;
var toString = exports.toString = function (arg) {
return _toString.call(arg);
};
/**
* Determines if `arg` is an object.
*
* @param {Object|Array|String|Function|RegExp|any} arg
* @return {Boolean}
*/
var isObject = exports.isObject = function (arg) {
return '[object Object]' == exports.toString(arg);
};
/**
* Determines if `arg` is an array.
*
* @param {Object}
* @return {Boolean}
* @see nodejs utils
*/
var isArray = exports.isArray = function (arg) {
return Array.isArray(arg) || 'object' == (typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg)) && '[object Array]' == exports.toString(arg);
};
/**
* Object.keys helper
*/
exports.keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}return keys;
};
/**
* Basic Object.create polyfill.
* Only one argument is supported.
*
* Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
*/
exports.create = 'function' == typeof Object.create ? Object.create : create;
function create(proto) {
if (arguments.length > 1) {
throw new Error("Adding properties is not supported");
}
function F() {}
F.prototype = proto;
return new F();
}
/**
* inheritance
*/
exports.inherits = function (ctor, superCtor) {
ctor.prototype = exports.create(superCtor.prototype);
ctor.prototype.constructor = ctor;
};
/**
* nextTick helper
* compat with node 0.10 which behaves differently than previous versions
*/
var soon = exports.soon = 'function' == typeof setImmediate ? setImmediate : process.nextTick;
/**
* Clones the contents of a buffer.
*
* @param {Buffer} buff
* @return {Buffer}
*/
exports.cloneBuffer = function (buff) {
var dupe = new Buffer(buff.length);
buff.copy(dupe, 0, 0, buff.length);
return dupe;
};
/**
* Check if this object is an arguments object
*
* @param {Any} v
* @return {Boolean}
*/
exports.isArgumentsObject = function (v) {
return Object.prototype.toString.call(v) === '[object Arguments]';
};
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":230,"babel-runtime/helpers/typeof":27,"buffer":32,"regexp-clone":245}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.promiseWait = exports.assertThrowsAsync = exports.Rx = undefined;
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var assertThrowsAsync = exports.assertThrowsAsync = function () {
var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(test, error) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return test();
case 3:
_context.next = 9;
break;
case 5:
_context.prev = 5;
_context.t0 = _context['catch'](0);
if (!(!error || _context.t0 instanceof error)) {
_context.next = 9;
break;
}
return _context.abrupt('return', 'util.assertThrowsAsync(): everything is fine');
case 9:
throw new Error('util.assertThrowsAsync(): Missing rejection' + (error ? ' with ' + error.name : ''));
case 10:
case 'end':
return _context.stop();
}
}
}, _callee, this, [[0, 5]]);
}));
return function assertThrowsAsync(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
/**
* this is a very fast hashing but its unsecure
* @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
* @param {object} obj
* @return {number} a number as hash-result
*/
/**
* [promiseWait description]
* @param {Number} [ms=0]
* @return {Promise}
*/
var promiseWait = exports.promiseWait = function () {
var _ref2 = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt('return', new Promise(function (res) {
setTimeout(res, ms);
}));
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function promiseWait(_x3) {
return _ref2.apply(this, arguments);
};
}();
/**
* this returns a promise and the resolve-function
* which can be called to resolve before the timeout
* @param {Number} [ms=0] [description]
*/
exports.encrypt = encrypt;
exports.decrypt = decrypt;
exports.isLevelDown = isLevelDown;
exports.fastUnsecureHash = fastUnsecureHash;
exports.hash = hash;
exports.generate_id = generate_id;
exports.jsonSchemaValidate = jsonSchemaValidate;
exports.promiseWaitResolveable = promiseWaitResolveable;
exports.hasBroadcastChannel = hasBroadcastChannel;
var _jsSha = require('js-sha3');
var _randomToken = require('random-token');
var _randomToken2 = _interopRequireDefault(_randomToken);
var _jsonschema = require('jsonschema');
var _Observable = require('rxjs/Observable');
var _Subject = require('rxjs/Subject');
var _BehaviorSubject = require('rxjs/BehaviorSubject');
require('rxjs/add/observable/merge');
require('rxjs/add/observable/interval');
require('rxjs/add/observable/fromEvent');
require('rxjs/add/operator/timeout');
require('rxjs/add/operator/delay');
require('rxjs/add/operator/map');
require('rxjs/add/operator/filter');
require('rxjs/add/operator/first');
require('rxjs/add/operator/startWith');
require('rxjs/add/operator/toPromise');
require('rxjs/add/operator/distinctUntilChanged');
var _aes = require('crypto-js/aes');
var crypto_AES = _interopRequireWildcard(_aes);
var _encUtf = require('crypto-js/enc-utf8');
var crypto_enc = _interopRequireWildcard(_encUtf);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* this contains a mapping to basic dependencies
* which should be easy to change
*/
/**
* TODO maybe replace js-sha3 with spark-md5
* because pouchdb-find uses the same and build-size could be reduced by 20kb
*/
var Rx = exports.Rx = {
Observable: _Observable.Observable,
Subject: _Subject.Subject,
BehaviorSubject: _BehaviorSubject.BehaviorSubject
};
// crypto-js
// rxjs cherry-pick
function encrypt(value, password) {
var encrypted = crypto_AES.encrypt(value, password);
return encrypted.toString();
}
function decrypt(ciphertext, password) {
var decrypted = crypto_AES.decrypt(ciphertext, password);
return decrypted.toString(crypto_enc);
}
/**
* check if the given module is a leveldown-adapter
* throws if not
*/
function isLevelDown(adapter) {
if (!adapter || typeof adapter.super_ !== 'function' || typeof adapter.destroy !== 'function') throw new Error('given leveldown is no valid adapter');
}
function fastUnsecureHash(obj) {
if (typeof obj !== 'string') obj = JSON.stringify(obj);
var hash = 0,
i = void 0,
chr = void 0,
len = void 0;
if (obj.length === 0) return hash;
for (i = 0, len = obj.length; i < len; i++) {
chr = obj.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
if (hash < 0) hash = hash * -1;
return hash;
}
function hash(obj) {
var salt = 'dW8a]Qsà <<>0lW6{3Fqxp3IdößBh:Fot';
var msg = obj;
if (typeof obj !== 'string') msg = JSON.stringify(obj);
return (0, _jsSha.sha3_512)(msg);
}
/**
* generate a new _id as db-key
* @return {string}
*/
function generate_id() {
return (0, _randomToken2.default)(10) + ':' + new Date().getTime();
}
var VALIDATOR = void 0;
function jsonSchemaValidate(schema, obj) {
if (!VALIDATOR) VALIDATOR = new _jsonschema.Validator();
var valid = VALIDATOR.validate(obj, schema);
if (valid.errors.length > 0) {
throw new Error(JSON.stringify({
name: 'object does not match schema',
errors: valid.errors,
object: obj,
schema: schema
}));
}
}function promiseWaitResolveable() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var ret = {};
ret.promise = new Promise(function (res) {
ret.resolve = function () {
return res();
};
setTimeout(res, ms);
});
return ret;
}
/**
* Detect if client can use BroadcastChannel
* @link https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
* @return {Boolean}
*/
function hasBroadcastChannel() {
if ((typeof window === 'undefined' ? 'undefined' : (0, _typeof3.default)(window)) === 'object' && window.BroadcastChannel && typeof window.BroadcastChannel === 'function' && typeof window.BroadcastChannel.prototype.postMessage === 'function' && typeof window.BroadcastChannel.prototype.close === 'function') return true;
return false;
}
},{"babel-runtime/helpers/asyncToGenerator":24,"babel-runtime/helpers/typeof":27,"babel-runtime/regenerator":28,"crypto-js/aes":118,"crypto-js/enc-utf8":122,"js-sha3":147,"jsonschema":150,"random-token":236,"rxjs/BehaviorSubject":246,"rxjs/Observable":249,"rxjs/Subject":253,"rxjs/add/observable/fromEvent":257,"rxjs/add/observable/interval":258,"rxjs/add/observable/merge":259,"rxjs/add/operator/delay":260,"rxjs/add/operator/distinctUntilChanged":261,"rxjs/add/operator/filter":262,"rxjs/add/operator/first":263,"rxjs/add/operator/map":264,"rxjs/add/operator/startWith":265,"rxjs/add/operator/timeout":266,"rxjs/add/operator/toPromise":267}],14:[function(require,module,exports){
(function (process){
/* Copyright (c) 2013 Rod Vagg, MIT License */
function AbstractChainedBatch (db) {
this._db = db
this._operations = []
this._written = false
}
AbstractChainedBatch.prototype._checkWritten = function () {
if (this._written)
throw new Error('write() already called on this batch')
}
AbstractChainedBatch.prototype.put = function (key, value) {
this._checkWritten()
var err = this._db._checkKey(key, 'key', this._db._isBuffer)
if (err)
throw err
if (!this._db._isBuffer(key)) key = String(key)
if (!this._db._isBuffer(value)) value = String(value)
if (typeof this._put == 'function' )
this._put(key, value)
else
this._operations.push({ type: 'put', key: key, value: value })
return this
}
AbstractChainedBatch.prototype.del = function (key) {
this._checkWritten()
var err = this._db._checkKey(key, 'key', this._db._isBuffer)
if (err) throw err
if (!this._db._isBuffer(key)) key = String(key)
if (typeof this._del == 'function' )
this._del(key)
else
this._operations.push({ type: 'del', key: key })
return this
}
AbstractChainedBatch.prototype.clear = function () {
this._checkWritten()
this._operations = []
if (typeof this._clear == 'function' )
this._clear()
return this
}
AbstractChainedBatch.prototype.write = function (options, callback) {
this._checkWritten()
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('write() requires a callback argument')
if (typeof options != 'object')
options = {}
this._written = true
if (typeof this._write == 'function' )
return this._write(callback)
if (typeof this._db._batch == 'function')
return this._db._batch(this._operations, options, callback)
process.nextTick(callback)
}
module.exports = AbstractChainedBatch
}).call(this,require('_process'))
},{"_process":230}],15:[function(require,module,exports){
(function (process){
/* Copyright (c) 2013 Rod Vagg, MIT License */
function AbstractIterator (db) {
this.db = db
this._ended = false
this._nexting = false
}
AbstractIterator.prototype.next = function (callback) {
var self = this
if (typeof callback != 'function')
throw new Error('next() requires a callback argument')
if (self._ended)
return callback(new Error('cannot call next() after end()'))
if (self._nexting)
return callback(new Error('cannot call next() before previous next() has completed'))
self._nexting = true
if (typeof self._next == 'function') {
return self._next(function () {
self._nexting = false
callback.apply(null, arguments)
})
}
process.nextTick(function () {
self._nexting = false
callback()
})
}
AbstractIterator.prototype.end = function (callback) {
if (typeof callback != 'function')
throw new Error('end() requires a callback argument')
if (this._ended)
return callback(new Error('end() already called on iterator'))
this._ended = true
if (typeof this._end == 'function')
return this._end(callback)
process.nextTick(callback)
}
module.exports = AbstractIterator
}).call(this,require('_process'))
},{"_process":230}],16:[function(require,module,exports){
(function (Buffer,process){
/* Copyright (c) 2013 Rod Vagg, MIT License */
var xtend = require('xtend')
, AbstractIterator = require('./abstract-iterator')
, AbstractChainedBatch = require('./abstract-chained-batch')
function AbstractLevelDOWN (location) {
if (!arguments.length || location === undefined)
throw new Error('constructor requires at least a location argument')
if (typeof location != 'string')
throw new Error('constructor requires a location string argument')
this.location = location
this.status = 'new'
}
AbstractLevelDOWN.prototype.open = function (options, callback) {
var self = this
, oldStatus = this.status
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('open() requires a callback argument')
if (typeof options != 'object')
options = {}
options.createIfMissing = options.createIfMissing != false
options.errorIfExists = !!options.errorIfExists
if (typeof this._open == 'function') {
this.status = 'opening'
this._open(options, function (err) {
if (err) {
self.status = oldStatus
return callback(err)
}
self.status = 'open'
callback()
})
} else {
this.status = 'open'
process.nextTick(callback)
}
}
AbstractLevelDOWN.prototype.close = function (callback) {
var self = this
, oldStatus = this.status
if (typeof callback != 'function')
throw new Error('close() requires a callback argument')
if (typeof this._close == 'function') {
this.status = 'closing'
this._close(function (err) {
if (err) {
self.status = oldStatus
return callback(err)
}
self.status = 'closed'
callback()
})
} else {
this.status = 'closed'
process.nextTick(callback)
}
}
AbstractLevelDOWN.prototype.get = function (key, options, callback) {
var err
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('get() requires a callback argument')
if (err = this._checkKey(key, 'key', this._isBuffer))
return callback(err)
if (!this._isBuffer(key))
key = String(key)
if (typeof options != 'object')
options = {}
options.asBuffer = options.asBuffer != false
if (typeof this._get == 'function')
return this._get(key, options, callback)
process.nextTick(function () { callback(new Error('NotFound')) })
}
AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
var err
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('put() requires a callback argument')
if (err = this._checkKey(key, 'key', this._isBuffer))
return callback(err)
if (!this._isBuffer(key))
key = String(key)
// coerce value to string in node, don't touch it in browser
// (indexeddb can store any JS type)
if (value != null && !this._isBuffer(value) && !process.browser)
value = String(value)
if (typeof options != 'object')
options = {}
if (typeof this._put == 'function')
return this._put(key, value, options, callback)
process.nextTick(callback)
}
AbstractLevelDOWN.prototype.del = function (key, options, callback) {
var err
if (typeof options == 'function')
callback = options
if (typeof callback != 'function')
throw new Error('del() requires a callback argument')
if (err = this._checkKey(key, 'key', this._isBuffer))
return callback(err)
if (!this._isBuffer(key))
key = String(key)
if (typeof options != 'object')
options = {}
if (typeof this._del == 'function')
return this._del(key, options, callback)
process.nextTick(callback)
}
AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
if (!arguments.length)
return this._chainedBatch()
if (typeof options == 'function')
callback = options
if (typeof array == 'function')
callback = array
if (typeof callback != 'function')
throw new Error('batch(array) requires a callback argument')
if (!Array.isArray(array))
return callback(new Error('batch(array) requires an array argument'))
if (!options || typeof options != 'object')
options = {}
var i = 0
, l = array.length
, e
, err
for (; i < l; i++) {
e = array[i]
if (typeof e != 'object')
continue
if (err = this._checkKey(e.type, 'type', this._isBuffer))
return callback(err)
if (err = this._checkKey(e.key, 'key', this._isBuffer))
return callback(err)
}
if (typeof this._batch == 'function')
return this._batch(array, options, callback)
process.nextTick(callback)
}
//TODO: remove from here, not a necessary primitive
AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
if ( start == null
|| end == null
|| typeof start == 'function'
|| typeof end == 'function') {
throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
}
if (typeof callback != 'function')
throw new Error('approximateSize() requires a callback argument')
if (!this._isBuffer(start))
start = String(start)
if (!this._isBuffer(end))
end = String(end)
if (typeof this._approximateSize == 'function')
return this._approximateSize(start, end, callback)
process.nextTick(function () {
callback(null, 0)
})
}
AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
var self = this
options = xtend(options)
;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
delete options[o]
})
options.reverse = !!options.reverse
options.keys = options.keys != false
options.values = options.values != false
options.limit = 'limit' in options ? options.limit : -1
options.keyAsBuffer = options.keyAsBuffer != false
options.valueAsBuffer = options.valueAsBuffer != false
return options
}
AbstractLevelDOWN.prototype.iterator = function (options) {
if (typeof options != 'object')
options = {}
options = this._setupIteratorOptions(options)
if (typeof this._iterator == 'function')
return this._iterator(options)
return new AbstractIterator(this)
}
AbstractLevelDOWN.prototype._chainedBatch = function () {
return new AbstractChainedBatch(this)
}
AbstractLevelDOWN.prototype._isBuffer = function (obj) {
return Buffer.isBuffer(obj)
}
AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
if (obj === null || obj === undefined)
return new Error(type + ' cannot be `null` or `undefined`')
if (this._isBuffer(obj)) {
if (obj.length === 0)
return new Error(type + ' cannot be an empty Buffer')
} else if (String(obj) === '')
return new Error(type + ' cannot be an empty String')
}
module.exports = AbstractLevelDOWN
}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
},{"../is-buffer/index.js":145,"./abstract-chained-batch":14,"./abstract-iterator":15,"_process":230,"xtend":342}],17:[function(require,module,exports){
exports.AbstractLevelDOWN = require('./abstract-leveldown')
exports.AbstractIterator = require('./abstract-iterator')
exports.AbstractChainedBatch = require('./abstract-chained-batch')
exports.isLevelDOWN = require('./is-leveldown')
},{"./abstract-chained-batch":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module,exports){
var AbstractLevelDOWN = require('./abstract-leveldown')
function isLevelDOWN (db) {
if (!db || typeof db !== 'object')
return false
return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
// TODO remove approximateSize check when method is gone
return name[0] != '_' && name != 'approximateSize'
}).every(function (name) {
return typeof db[name] == 'function'
})
}
module.exports = isLevelDOWN
},{"./abstract-leveldown":16}],19:[function(require,module,exports){
'use strict';
module.exports = argsArray;
function argsArray(fun) {
return function () {
var len = arguments.length;
if (len) {
var args = [];
var i = -1;
while (++i < len) {
args[i] = arguments[i];
}
return fun.call(this, args);
} else {
return fun.call(this, []);
}
};
}
},{}],20:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":35}],21:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/promise"), __esModule: true };
},{"core-js/library/fn/promise":36}],22:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true };
},{"core-js/library/fn/symbol":37}],23:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true };
},{"core-js/library/fn/symbol/iterator":38}],24:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _promise = require("../core-js/promise");
var _promise2 = _interopRequireDefault(_promise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new _promise2.default(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return _promise2.default.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
}
return step("next");
});
};
};
},{"../core-js/promise":21}],25:[function(require,module,exports){
"use strict";
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
},{}],26:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _defineProperty = require("../core-js/object/define-property");
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
},{"../core-js/object/define-property":20}],27:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _iterator = require("../core-js/symbol/iterator");
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = require("../core-js/symbol");
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
},{"../core-js/symbol":22,"../core-js/symbol/iterator":23}],28:[function(require,module,exports){
module.exports = require("regenerator-runtime");
},{"regenerator-runtime":243}],29:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],30:[function(require,module,exports){
},{}],31:[function(require,module,exports){
(function (global){
'use strict';
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
if (typeof Buffer.alloc === 'function') {
return Buffer.alloc(size, fill, encoding);
}
if (typeof encoding === 'number') {
throw new TypeError('encoding must not be number');
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
var enc = encoding;
var _fill = fill;
if (_fill === undefined) {
enc = undefined;
_fill = 0;
}
var buf = new Buffer(size);
if (typeof _fill === 'string') {
var fillBuf = new Buffer(_fill, enc);
var flen = fillBuf.length;
var i = -1;
while (++i < size) {
buf[i] = fillBuf[i % flen];
}
} else {
buf.fill(_fill);
}
return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
if (typeof Buffer.allocUnsafe === 'function') {
return Buffer.allocUnsafe(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
return Buffer.from(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (typeof value === 'string') {
return new Buffer(value, encodingOrOffset);
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
var offset = encodingOrOffset;
if (arguments.length === 1) {
return new Buffer(value);
}
if (typeof offset === 'undefined') {
offset = 0;
}
var len = length;
if (typeof len === 'undefined') {
len = value.byteLength - offset;
}
if (offset >= value.byteLength) {
throw new RangeError('\'offset\' is out of bounds');
}
if (len > value.byteLength - offset) {
throw new RangeError('\'length\' is out of bounds');
}
return new Buffer(value.slice(offset, offset + len));
}
if (Buffer.isBuffer(value)) {
var out = new Buffer(value.length);
value.copy(out, 0, 0, value.length);
return out;
}
if (value) {
if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
return new Buffer(value);
}
if (value.type === 'Buffer' && Array.isArray(value.data)) {
return new Buffer(value.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
if (typeof Buffer.allocUnsafeSlow === 'function') {
return Buffer.allocUnsafeSlow(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size >= MAX_LEN) {
throw new RangeError('size is too large');
}
return new SlowBuffer(size);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"buffer":32}],32:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return ''
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"base64-js":29,"ieee754":141,"isarray":33}],33:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],34:[function(require,module,exports){
(function (Buffer){
var clone = (function() {
'use strict';
var nativeMap;
try {
nativeMap = Map;
} catch(_) {
// maybe a reference error because no `Map`. Give it a dummy value that no
// value will ever be an instanceof.
nativeMap = function() {};
}
var nativeSet;
try {
nativeSet = Set;
} catch(_) {
nativeSet = function() {};
}
var nativePromise;
try {
nativePromise = Promise;
} catch(_) {
nativePromise = function() {};
}
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
* @param `includeNonEnumerable` - set to true if the non-enumerable properties
* should be cloned as well. Non-enumerable properties on the prototype
* chain will be ignored. (optional - false by default)
*/
function clone(parent, circular, depth, prototype, includeNonEnumerable) {
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
includeNonEnumerable = circular.includeNonEnumerable;
circular = circular.circular;
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (parent instanceof nativeMap) {
child = new nativeMap();
} else if (parent instanceof nativeSet) {
child = new nativeSet();
} else if (parent instanceof nativePromise) {
child = new nativePromise(function (resolve, reject) {
parent.then(function(value) {
resolve(_clone(value, depth - 1));
}, function(err) {
reject(_clone(err, depth - 1));
});
});
} else if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
child = new Buffer(parent.length);
parent.copy(child);
return child;
} else if (parent instanceof Error) {
child = Object.create(parent);
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
if (parent instanceof nativeMap) {
var keyIterator = parent.keys();
while(true) {
var next = keyIterator.next();
if (next.done) {
break;
}
var keyChild = _clone(next.value, depth - 1);
var valueChild = _clone(parent.get(next.value), depth - 1);
child.set(keyChild, valueChild);
}
}
if (parent instanceof nativeSet) {
var iterator = parent.keys();
while(true) {
var next = iterator.next();
if (next.done) {
break;
}
var entryChild = _clone(next.value, depth - 1);
child.add(entryChild);
}
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(parent);
for (var i = 0; i < symbols.length; i++) {
// Don't need to worry about cloning a symbol because it is a primitive,
// like a number or string.
var symbol = symbols[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
continue;
}
child[symbol] = _clone(parent[symbol], depth - 1);
if (!descriptor.enumerable) {
Object.defineProperty(child, symbol, {
enumerable: false
});
}
}
}
if (includeNonEnumerable) {
var allPropertyNames = Object.getOwnPropertyNames(parent);
for (var i = 0; i < allPropertyNames.length; i++) {
var propertyName = allPropertyNames[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
if (descriptor && descriptor.enumerable) {
continue;
}
child[propertyName] = _clone(parent[propertyName], depth - 1);
Object.defineProperty(child, propertyName, {
enumerable: false
});
}
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
}
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
}
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
}
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
}).call(this,require("buffer").Buffer)
},{"buffer":32}],35:[function(require,module,exports){
require('../../modules/es6.object.define-property');
var $Object = require('../../modules/_core').Object;
module.exports = function defineProperty(it, key, desc){
return $Object.defineProperty(it, key, desc);
};
},{"../../modules/_core":46,"../../modules/es6.object.define-property":109}],36:[function(require,module,exports){
require('../modules/es6.object.to-string');
require('../modules/es6.string.iterator');
require('../modules/web.dom.iterable');
require('../modules/es6.promise');
module.exports = require('../modules/_core').Promise;
},{"../modules/_core":46,"../modules/es6.object.to-string":110,"../modules/es6.promise":111,"../modules/es6.string.iterator":112,"../modules/web.dom.iterable":116}],37:[function(require,module,exports){
require('../../modules/es6.symbol');
require('../../modules/es6.object.to-string');
require('../../modules/es7.symbol.async-iterator');
require('../../modules/es7.symbol.observable');
module.exports = require('../../modules/_core').Symbol;
},{"../../modules/_core":46,"../../modules/es6.object.to-string":110,"../../modules/es6.symbol":113,"../../modules/es7.symbol.async-iterator":114,"../../modules/es7.symbol.observable":115}],38:[function(require,module,exports){
require('../../modules/es6.string.iterator');
require('../../modules/web.dom.iterable');
module.exports = require('../../modules/_wks-ext').f('iterator');
},{"../../modules/_wks-ext":105,"../../modules/es6.string.iterator":112,"../../modules/web.dom.iterable":116}],39:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],40:[function(require,module,exports){
module.exports = function(){ /* empty */ };
},{}],41:[function(require,module,exports){
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],42:[function(require,module,exports){
var isObject = require('./_is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":65}],43:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./_to-iobject')
, toLength = require('./_to-length')
, toIndex = require('./_to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-index":97,"./_to-iobject":99,"./_to-length":100}],44:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof')
, TAG = require('./_wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./_cof":45,"./_wks":106}],45:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],46:[function(require,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],47:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./_a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./_a-function":39}],48:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],49:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./_fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_fails":54}],50:[function(require,module,exports){
var isObject = require('./_is-object')
, document = require('./_global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./_global":56,"./_is-object":65}],51:[function(require,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],52:[function(require,module,exports){
// all enumerable object keys, includes symbols
var getKeys = require('./_object-keys')
, gOPS = require('./_object-gops')
, pIE = require('./_object-pie');
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
},{"./_object-gops":82,"./_object-keys":85,"./_object-pie":86}],53:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, ctx = require('./_ctx')
, hide = require('./_hide')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":46,"./_ctx":47,"./_global":56,"./_hide":58}],54:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],55:[function(require,module,exports){
var ctx = require('./_ctx')
, call = require('./_iter-call')
, isArrayIter = require('./_is-array-iter')
, anObject = require('./_an-object')
, toLength = require('./_to-length')
, getIterFn = require('./core.get-iterator-method')
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
},{"./_an-object":42,"./_ctx":47,"./_is-array-iter":63,"./_iter-call":66,"./_to-length":100,"./core.get-iterator-method":107}],56:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],57:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],58:[function(require,module,exports){
var dP = require('./_object-dp')
, createDesc = require('./_property-desc');
module.exports = require('./_descriptors') ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./_descriptors":49,"./_object-dp":77,"./_property-desc":87}],59:[function(require,module,exports){
module.exports = require('./_global').document && document.documentElement;
},{"./_global":56}],60:[function(require,module,exports){
module.exports = !require('./_descriptors') && !require('./_fails')(function(){
return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_descriptors":49,"./_dom-create":50,"./_fails":54}],61:[function(require,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],62:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":45}],63:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./_iterators')
, ITERATOR = require('./_wks')('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./_iterators":71,"./_wks":106}],64:[function(require,module,exports){
// 7.2.2 IsArray(argument)
var cof = require('./_cof');
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"./_cof":45}],65:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],66:[function(require,module,exports){
// call something on iterator step with safe closing on error
var anObject = require('./_an-object');
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"./_an-object":42}],67:[function(require,module,exports){
'use strict';
var create = require('./_object-create')
, descriptor = require('./_property-desc')
, setToStringTag = require('./_set-to-string-tag')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./_hide":58,"./_object-create":76,"./_property-desc":87,"./_set-to-string-tag":91,"./_wks":106}],68:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, $export = require('./_export')
, redefine = require('./_redefine')
, hide = require('./_hide')
, has = require('./_has')
, Iterators = require('./_iterators')
, $iterCreate = require('./_iter-create')
, setToStringTag = require('./_set-to-string-tag')
, getPrototypeOf = require('./_object-gpo')
, ITERATOR = require('./_wks')('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./_export":53,"./_has":57,"./_hide":58,"./_iter-create":67,"./_iterators":71,"./_library":73,"./_object-gpo":83,"./_redefine":89,"./_set-to-string-tag":91,"./_wks":106}],69:[function(require,module,exports){
var ITERATOR = require('./_wks')('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
},{"./_wks":106}],70:[function(require,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],71:[function(require,module,exports){
module.exports = {};
},{}],72:[function(require,module,exports){
var getKeys = require('./_object-keys')
, toIObject = require('./_to-iobject');
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"./_object-keys":85,"./_to-iobject":99}],73:[function(require,module,exports){
module.exports = true;
},{}],74:[function(require,module,exports){
var META = require('./_uid')('meta')
, isObject = require('./_is-object')
, has = require('./_has')
, setDesc = require('./_object-dp').f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !require('./_fails')(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"./_fails":54,"./_has":57,"./_is-object":65,"./_object-dp":77,"./_uid":103}],75:[function(require,module,exports){
var global = require('./_global')
, macrotask = require('./_task').set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = require('./_cof')(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
},{"./_cof":45,"./_global":56,"./_task":96}],76:[function(require,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object')
, dPs = require('./_object-dps')
, enumBugKeys = require('./_enum-bug-keys')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = require('./_dom-create')('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
require('./_html').appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"./_an-object":42,"./_dom-create":50,"./_enum-bug-keys":51,"./_html":59,"./_object-dps":78,"./_shared-key":92}],77:[function(require,module,exports){
var anObject = require('./_an-object')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, toPrimitive = require('./_to-primitive')
, dP = Object.defineProperty;
exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"./_an-object":42,"./_descriptors":49,"./_ie8-dom-define":60,"./_to-primitive":102}],78:[function(require,module,exports){
var dP = require('./_object-dp')
, anObject = require('./_an-object')
, getKeys = require('./_object-keys');
module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":42,"./_descriptors":49,"./_object-dp":77,"./_object-keys":85}],79:[function(require,module,exports){
var pIE = require('./_object-pie')
, createDesc = require('./_property-desc')
, toIObject = require('./_to-iobject')
, toPrimitive = require('./_to-primitive')
, has = require('./_has')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"./_descriptors":49,"./_has":57,"./_ie8-dom-define":60,"./_object-pie":86,"./_property-desc":87,"./_to-iobject":99,"./_to-primitive":102}],80:[function(require,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./_to-iobject')
, gOPN = require('./_object-gopn').f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"./_object-gopn":81,"./_to-iobject":99}],81:[function(require,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = require('./_object-keys-internal')
, hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
},{"./_enum-bug-keys":51,"./_object-keys-internal":84}],82:[function(require,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],83:[function(require,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has')
, toObject = require('./_to-object')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"./_has":57,"./_shared-key":92,"./_to-object":101}],84:[function(require,module,exports){
var has = require('./_has')
, toIObject = require('./_to-iobject')
, arrayIndexOf = require('./_array-includes')(false)
, IE_PROTO = require('./_shared-key')('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":43,"./_has":57,"./_shared-key":92,"./_to-iobject":99}],85:[function(require,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal')
, enumBugKeys = require('./_enum-bug-keys');
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":51,"./_object-keys-internal":84}],86:[function(require,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],87:[function(require,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],88:[function(require,module,exports){
var hide = require('./_hide');
module.exports = function(target, src, safe){
for(var key in src){
if(safe && target[key])target[key] = src[key];
else hide(target, key, src[key]);
} return target;
};
},{"./_hide":58}],89:[function(require,module,exports){
module.exports = require('./_hide');
},{"./_hide":58}],90:[function(require,module,exports){
'use strict';
var global = require('./_global')
, core = require('./_core')
, dP = require('./_object-dp')
, DESCRIPTORS = require('./_descriptors')
, SPECIES = require('./_wks')('species');
module.exports = function(KEY){
var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"./_core":46,"./_descriptors":49,"./_global":56,"./_object-dp":77,"./_wks":106}],91:[function(require,module,exports){
var def = require('./_object-dp').f
, has = require('./_has')
, TAG = require('./_wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"./_has":57,"./_object-dp":77,"./_wks":106}],92:[function(require,module,exports){
var shared = require('./_shared')('keys')
, uid = require('./_uid');
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":93,"./_uid":103}],93:[function(require,module,exports){
var global = require('./_global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./_global":56}],94:[function(require,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = require('./_an-object')
, aFunction = require('./_a-function')
, SPECIES = require('./_wks')('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"./_a-function":39,"./_an-object":42,"./_wks":106}],95:[function(require,module,exports){
var toInteger = require('./_to-integer')
, defined = require('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./_defined":48,"./_to-integer":98}],96:[function(require,module,exports){
var ctx = require('./_ctx')
, invoke = require('./_invoke')
, html = require('./_html')
, cel = require('./_dom-create')
, global = require('./_global')
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(require('./_cof')(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"./_cof":45,"./_ctx":47,"./_dom-create":50,"./_global":56,"./_html":59,"./_invoke":61}],97:[function(require,module,exports){
var toInteger = require('./_to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":98}],98:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],99:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject')
, defined = require('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./_defined":48,"./_iobject":62}],100:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./_to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":98}],101:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./_defined":48}],102:[function(require,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":65}],103:[function(require,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],104:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, LIBRARY = require('./_library')
, wksExt = require('./_wks-ext')
, defineProperty = require('./_object-dp').f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
},{"./_core":46,"./_global":56,"./_library":73,"./_object-dp":77,"./_wks-ext":105}],105:[function(require,module,exports){
exports.f = require('./_wks');
},{"./_wks":106}],106:[function(require,module,exports){
var store = require('./_shared')('wks')
, uid = require('./_uid')
, Symbol = require('./_global').Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":56,"./_shared":93,"./_uid":103}],107:[function(require,module,exports){
var classof = require('./_classof')
, ITERATOR = require('./_wks')('iterator')
, Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":44,"./_core":46,"./_iterators":71,"./_wks":106}],108:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./_add-to-unscopables')
, step = require('./_iter-step')
, Iterators = require('./_iterators')
, toIObject = require('./_to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./_add-to-unscopables":40,"./_iter-define":68,"./_iter-step":70,"./_iterators":71,"./_to-iobject":99}],109:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperty: require('./_object-dp').f});
},{"./_descriptors":49,"./_export":53,"./_object-dp":77}],110:[function(require,module,exports){
arguments[4][30][0].apply(exports,arguments)
},{"dup":30}],111:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, global = require('./_global')
, ctx = require('./_ctx')
, classof = require('./_classof')
, $export = require('./_export')
, isObject = require('./_is-object')
, aFunction = require('./_a-function')
, anInstance = require('./_an-instance')
, forOf = require('./_for-of')
, speciesConstructor = require('./_species-constructor')
, task = require('./_task').set
, microtask = require('./_microtask')()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = require('./_redefine-all')($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
},{"./_a-function":39,"./_an-instance":41,"./_classof":44,"./_core":46,"./_ctx":47,"./_export":53,"./_for-of":55,"./_global":56,"./_is-object":65,"./_iter-detect":69,"./_library":73,"./_microtask":75,"./_redefine-all":88,"./_set-species":90,"./_set-to-string-tag":91,"./_species-constructor":94,"./_task":96,"./_wks":106}],112:[function(require,module,exports){
'use strict';
var $at = require('./_string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./_iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./_iter-define":68,"./_string-at":95}],113:[function(require,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = require('./_global')
, has = require('./_has')
, DESCRIPTORS = require('./_descriptors')
, $export = require('./_export')
, redefine = require('./_redefine')
, META = require('./_meta').KEY
, $fails = require('./_fails')
, shared = require('./_shared')
, setToStringTag = require('./_set-to-string-tag')
, uid = require('./_uid')
, wks = require('./_wks')
, wksExt = require('./_wks-ext')
, wksDefine = require('./_wks-define')
, keyOf = require('./_keyof')
, enumKeys = require('./_enum-keys')
, isArray = require('./_is-array')
, anObject = require('./_an-object')
, toIObject = require('./_to-iobject')
, toPrimitive = require('./_to-primitive')
, createDesc = require('./_property-desc')
, _create = require('./_object-create')
, gOPNExt = require('./_object-gopn-ext')
, $GOPD = require('./_object-gopd')
, $DP = require('./_object-dp')
, $keys = require('./_object-keys')
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;
require('./_object-pie').f = $propertyIsEnumerable;
require('./_object-gops').f = $getOwnPropertySymbols;
if(DESCRIPTORS && !require('./_library')){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"./_an-object":42,"./_descriptors":49,"./_enum-keys":52,"./_export":53,"./_fails":54,"./_global":56,"./_has":57,"./_hide":58,"./_is-array":64,"./_keyof":72,"./_library":73,"./_meta":74,"./_object-create":76,"./_object-dp":77,"./_object-gopd":79,"./_object-gopn":81,"./_object-gopn-ext":80,"./_object-gops":82,"./_object-keys":85,"./_object-pie":86,"./_property-desc":87,"./_redefine":89,"./_set-to-string-tag":91,"./_shared":93,"./_to-iobject":99,"./_to-primitive":102,"./_uid":103,"./_wks":106,"./_wks-define":104,"./_wks-ext":105}],114:[function(require,module,exports){
require('./_wks-define')('asyncIterator');
},{"./_wks-define":104}],115:[function(require,module,exports){
require('./_wks-define')('observable');
},{"./_wks-define":104}],116:[function(require,module,exports){
require('./es6.array.iterator');
var global = require('./_global')
, hide = require('./_hide')
, Iterators = require('./_iterators')
, TO_STRING_TAG = require('./_wks')('toStringTag');
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype;
if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
},{"./_global":56,"./_hide":58,"./_iterators":71,"./_wks":106,"./es6.array.iterator":108}],117:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":145}],118:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Skip reset of nRounds has been set before and key did not change
if (this._nRounds && this._keyPriorReset === this._key) {
return;
}
// Shortcuts
var key = this._keyPriorReset = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6;
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":119,"./core":120,"./enc-base64":121,"./evpkdf":123,"./md5":125}],119:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":120}],120:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/*
* Local polyfil of Object.create
*/
var create = Object.create || (function () {
function F() {};
return function (obj) {
var subtype;
F.prototype = obj;
subtype = new F();
F.prototype = null;
return subtype;
};
}())
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
var subtype = create(this);
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],121:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
var reverseMap = this._reverseMap;
if (!reverseMap) {
reverseMap = this._reverseMap = [];
for (var j = 0; j < map.length; j++) {
reverseMap[map.charCodeAt(j)] = j;
}
}
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex !== -1) {
base64StrLength = paddingIndex;
}
}
// Convert
return parseLoop(base64Str, base64StrLength, reverseMap);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
function parseLoop(base64Str, base64StrLength, reverseMap) {
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
}
}());
return CryptoJS.enc.Base64;
}));
},{"./core":120}],122:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS.enc.Utf8;
}));
},{"./core":120}],123:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":120,"./hmac":124,"./sha1":126}],124:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":120}],125:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":120}],126:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":120}],127:[function(require,module,exports){
var Buffer = require('buffer').Buffer
var CHARS = '.PYFGCRLAOEUIDHTNSQJKXBMWVZ_pyfgcrlaoeuidhtnsqjkxbmwvz1234567890'
.split('').sort().join('')
module.exports = function (chars, exports) {
chars = chars || CHARS
exports = exports || {}
if(chars.length !== 64) throw new Error('a base 64 encoding requires 64 chars')
var codeToIndex = new Buffer(128)
codeToIndex.fill()
for(var i = 0; i < 64; i++) {
var code = chars.charCodeAt(i)
codeToIndex[code] = i
}
exports.encode = function (data) {
var s = '', l = data.length, hang = 0
for(var i = 0; i < l; i++) {
var v = data[i]
switch (i % 3) {
case 0:
s += chars[v >> 2]
hang = (v & 3) << 4
break;
case 1:
s += chars[hang | v >> 4]
hang = (v & 0xf) << 2
break;
case 2:
s += chars[hang | v >> 6]
s += chars[v & 0x3f]
hang = 0
break;
}
}
if(l%3) s += chars[hang]
return s
}
exports.decode = function (str) {
var l = str.length, j = 0
var b = new Buffer(~~((l/4)*3)), hang = 0
for(var i = 0; i < l; i++) {
var v = codeToIndex[str.charCodeAt(i)]
switch (i % 4) {
case 0:
hang = v << 2;
break;
case 1:
b[j++] = hang | v >> 4
hang = (v << 4) & 0xff
break;
case 2:
b[j++] = hang | v >> 2
hang = (v << 6) & 0xff
break;
case 3:
b[j++] = hang | v
break;
}
}
return b
}
return exports
}
module.exports(CHARS, module.exports)
},{"buffer":32}],128:[function(require,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
},{"./debug":129}],129:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":174}],130:[function(require,module,exports){
var util = require('util')
, AbstractIterator = require('abstract-leveldown').AbstractIterator
function DeferredIterator (options) {
AbstractIterator.call(this, options)
this._options = options
this._iterator = null
this._operations = []
}
util.inherits(DeferredIterator, AbstractIterator)
DeferredIterator.prototype.setDb = function (db) {
var it = this._iterator = db.iterator(this._options)
this._operations.forEach(function (op) {
it[op.method].apply(it, op.args)
})
}
DeferredIterator.prototype._operation = function (method, args) {
if (this._iterator)
return this._iterator[method].apply(this._iterator, args)
this._operations.push({ method: method, args: args })
}
'next end'.split(' ').forEach(function (m) {
DeferredIterator.prototype['_' + m] = function () {
this._operation(m, arguments)
}
})
module.exports = DeferredIterator;
},{"abstract-leveldown":17,"util":340}],131:[function(require,module,exports){
(function (Buffer,process){
var util = require('util')
, AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
, DeferredIterator = require('./deferred-iterator')
function DeferredLevelDOWN (location) {
AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares?
this._db = undefined
this._operations = []
this._iterators = []
}
util.inherits(DeferredLevelDOWN, AbstractLevelDOWN)
// called by LevelUP when we have a real DB to take its place
DeferredLevelDOWN.prototype.setDb = function (db) {
this._db = db
this._operations.forEach(function (op) {
db[op.method].apply(db, op.args)
})
this._iterators.forEach(function (it) {
it.setDb(db)
})
}
DeferredLevelDOWN.prototype._open = function (options, callback) {
return process.nextTick(callback)
}
// queue a new deferred operation
DeferredLevelDOWN.prototype._operation = function (method, args) {
if (this._db)
return this._db[method].apply(this._db, args)
this._operations.push({ method: method, args: args })
}
// deferrables
'put get del batch approximateSize'.split(' ').forEach(function (m) {
DeferredLevelDOWN.prototype['_' + m] = function () {
this._operation(m, arguments)
}
})
DeferredLevelDOWN.prototype._isBuffer = function (obj) {
return Buffer.isBuffer(obj)
}
DeferredLevelDOWN.prototype._iterator = function (options) {
if (this._db)
return this._db.iterator.apply(this._db, arguments)
var it = new DeferredIterator(options)
this._iterators.push(it)
return it
}
module.exports = DeferredLevelDOWN
module.exports.DeferredIterator = DeferredIterator
}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
},{"../is-buffer/index.js":145,"./deferred-iterator":130,"_process":230,"abstract-leveldown":17,"util":340}],132:[function(require,module,exports){
/**
* Copyright (c) 2013 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
"use strict";
function Deque(capacity) {
this._capacity = getCapacity(capacity);
this._length = 0;
this._front = 0;
if (isArray(capacity)) {
var len = capacity.length;
for (var i = 0; i < len; ++i) {
this[i] = capacity[i];
}
this._length = len;
}
}
Deque.prototype.toArray = function Deque$toArray() {
var len = this._length;
var ret = new Array(len);
var front = this._front;
var capacity = this._capacity;
for (var j = 0; j < len; ++j) {
ret[j] = this[(front + j) & (capacity - 1)];
}
return ret;
};
Deque.prototype.push = function Deque$push(item) {
var argsLength = arguments.length;
var length = this._length;
if (argsLength > 1) {
var capacity = this._capacity;
if (length + argsLength > capacity) {
for (var i = 0; i < argsLength; ++i) {
this._checkCapacity(length + 1);
var j = (this._front + length) & (this._capacity - 1);
this[j] = arguments[i];
length++;
this._length = length;
}
return length;
}
else {
var j = this._front;
for (var i = 0; i < argsLength; ++i) {
this[(j + length) & (capacity - 1)] = arguments[i];
j++;
}
this._length = length + argsLength;
return length + argsLength;
}
}
if (argsLength === 0) return length;
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = item;
this._length = length + 1;
return length + 1;
};
Deque.prototype.pop = function Deque$pop() {
var length = this._length;
if (length === 0) {
return void 0;
}
var i = (this._front + length - 1) & (this._capacity - 1);
var ret = this[i];
this[i] = void 0;
this._length = length - 1;
return ret;
};
Deque.prototype.shift = function Deque$shift() {
var length = this._length;
if (length === 0) {
return void 0;
}
var front = this._front;
var ret = this[front];
this[front] = void 0;
this._front = (front + 1) & (this._capacity - 1);
this._length = length - 1;
return ret;
};
Deque.prototype.unshift = function Deque$unshift(item) {
var length = this._length;
var argsLength = arguments.length;
if (argsLength > 1) {
var capacity = this._capacity;
if (length + argsLength > capacity) {
for (var i = argsLength - 1; i >= 0; i--) {
this._checkCapacity(length + 1);
var capacity = this._capacity;
var j = (((( this._front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[j] = arguments[i];
length++;
this._length = length;
this._front = j;
}
return length;
}
else {
var front = this._front;
for (var i = argsLength - 1; i >= 0; i--) {
var j = (((( front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[j] = arguments[i];
front = j;
}
this._front = front;
this._length = length + argsLength;
return length + argsLength;
}
}
if (argsLength === 0) return length;
this._checkCapacity(length + 1);
var capacity = this._capacity;
var i = (((( this._front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[i] = item;
this._length = length + 1;
this._front = i;
return length + 1;
};
Deque.prototype.peekBack = function Deque$peekBack() {
var length = this._length;
if (length === 0) {
return void 0;
}
var index = (this._front + length - 1) & (this._capacity - 1);
return this[index];
};
Deque.prototype.peekFront = function Deque$peekFront() {
if (this._length === 0) {
return void 0;
}
return this[this._front];
};
Deque.prototype.get = function Deque$get(index) {
var i = index;
if ((i !== (i | 0))) {
return void 0;
}
var len = this._length;
if (i < 0) {
i = i + len;
}
if (i < 0 || i >= len) {
return void 0;
}
return this[(this._front + i) & (this._capacity - 1)];
};
Deque.prototype.isEmpty = function Deque$isEmpty() {
return this._length === 0;
};
Deque.prototype.clear = function Deque$clear() {
var len = this._length;
var front = this._front;
var capacity = this._capacity;
for (var j = 0; j < len; ++j) {
this[(front + j) & (capacity - 1)] = void 0;
}
this._length = 0;
this._front = 0;
};
Deque.prototype.toString = function Deque$toString() {
return this.toArray().toString();
};
Deque.prototype.valueOf = Deque.prototype.toString;
Deque.prototype.removeFront = Deque.prototype.shift;
Deque.prototype.removeBack = Deque.prototype.pop;
Deque.prototype.insertFront = Deque.prototype.unshift;
Deque.prototype.insertBack = Deque.prototype.push;
Deque.prototype.enqueue = Deque.prototype.push;
Deque.prototype.dequeue = Deque.prototype.shift;
Deque.prototype.toJSON = Deque.prototype.toArray;
Object.defineProperty(Deque.prototype, "length", {
get: function() {
return this._length;
},
set: function() {
throw new RangeError("");
}
});
Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
if (this._capacity < size) {
this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
}
};
Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
if (front + length > oldCapacity) {
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
}
};
var isArray = Array.isArray;
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function pow2AtLeast(n) {
n = n >>> 0;
n = n - 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
return n + 1;
}
function getCapacity(capacity) {
if (typeof capacity !== "number") {
if (isArray(capacity)) {
capacity = capacity.length;
}
else {
return 16;
}
}
return pow2AtLeast(
Math.min(
Math.max(16, capacity), 1073741824)
);
}
module.exports = Deque;
},{}],133:[function(require,module,exports){
var prr = require('prr')
function init (type, message, cause) {
prr(this, {
type : type
, name : type
// can be passed just a 'cause'
, cause : typeof message != 'string' ? message : cause
, message : !!message && typeof message != 'string' ? message.message : message
}, 'ewr')
}
// generic prototype, not intended to be actually used - helpful for `instanceof`
function CustomError (message, cause) {
Error.call(this)
if (Error.captureStackTrace)
Error.captureStackTrace(this, arguments.callee)
init.call(this, 'CustomError', message, cause)
}
CustomError.prototype = new Error()
function createError (errno, type, proto) {
var err = function (message, cause) {
init.call(this, type, message, cause)
//TODO: the specificity here is stupid, errno should be available everywhere
if (type == 'FilesystemError') {
this.code = this.cause.code
this.path = this.cause.path
this.errno = this.cause.errno
this.message =
(errno.errno[this.cause.errno]
? errno.errno[this.cause.errno].description
: this.cause.message)
+ (this.cause.path ? ' [' + this.cause.path + ']' : '')
}
Error.call(this)
if (Error.captureStackTrace)
Error.captureStackTrace(this, arguments.callee)
}
err.prototype = !!proto ? new proto() : new CustomError()
return err
}
module.exports = function (errno) {
var ce = function (type, proto) {
return createError(errno, type, proto)
}
return {
CustomError : CustomError
, FilesystemError : ce('FilesystemError')
, createError : ce
}
}
},{"prr":135}],134:[function(require,module,exports){
var all = module.exports.all = [
{
errno: -2,
code: 'ENOENT',
description: 'no such file or directory'
},
{
errno: -1,
code: 'UNKNOWN',
description: 'unknown error'
},
{
errno: 0,
code: 'OK',
description: 'success'
},
{
errno: 1,
code: 'EOF',
description: 'end of file'
},
{
errno: 2,
code: 'EADDRINFO',
description: 'getaddrinfo error'
},
{
errno: 3,
code: 'EACCES',
description: 'permission denied'
},
{
errno: 4,
code: 'EAGAIN',
description: 'resource temporarily unavailable'
},
{
errno: 5,
code: 'EADDRINUSE',
description: 'address already in use'
},
{
errno: 6,
code: 'EADDRNOTAVAIL',
description: 'address not available'
},
{
errno: 7,
code: 'EAFNOSUPPORT',
description: 'address family not supported'
},
{
errno: 8,
code: 'EALREADY',
description: 'connection already in progress'
},
{
errno: 9,
code: 'EBADF',
description: 'bad file descriptor'
},
{
errno: 10,
code: 'EBUSY',
description: 'resource busy or locked'
},
{
errno: 11,
code: 'ECONNABORTED',
description: 'software caused connection abort'
},
{
errno: 12,
code: 'ECONNREFUSED',
description: 'connection refused'
},
{
errno: 13,
code: 'ECONNRESET',
description: 'connection reset by peer'
},
{
errno: 14,
code: 'EDESTADDRREQ',
description: 'destination address required'
},
{
errno: 15,
code: 'EFAULT',
description: 'bad address in system call argument'
},
{
errno: 16,
code: 'EHOSTUNREACH',
description: 'host is unreachable'
},
{
errno: 17,
code: 'EINTR',
description: 'interrupted system call'
},
{
errno: 18,
code: 'EINVAL',
description: 'invalid argument'
},
{
errno: 19,
code: 'EISCONN',
description: 'socket is already connected'
},
{
errno: 20,
code: 'EMFILE',
description: 'too many open files'
},
{
errno: 21,
code: 'EMSGSIZE',
description: 'message too long'
},
{
errno: 22,
code: 'ENETDOWN',
description: 'network is down'
},
{
errno: 23,
code: 'ENETUNREACH',
description: 'network is unreachable'
},
{
errno: 24,
code: 'ENFILE',
description: 'file table overflow'
},
{
errno: 25,
code: 'ENOBUFS',
description: 'no buffer space available'
},
{
errno: 26,
code: 'ENOMEM',
description: 'not enough memory'
},
{
errno: 27,
code: 'ENOTDIR',
description: 'not a directory'
},
{
errno: 28,
code: 'EISDIR',
description: 'illegal operation on a directory'
},
{
errno: 29,
code: 'ENONET',
description: 'machine is not on the network'
},
{
errno: 31,
code: 'ENOTCONN',
description: 'socket is not connected'
},
{
errno: 32,
code: 'ENOTSOCK',
description: 'socket operation on non-socket'
},
{
errno: 33,
code: 'ENOTSUP',
description: 'operation not supported on socket'
},
{
errno: 34,
code: 'ENOENT',
description: 'no such file or directory'
},
{
errno: 35,
code: 'ENOSYS',
description: 'function not implemented'
},
{
errno: 36,
code: 'EPIPE',
description: 'broken pipe'
},
{
errno: 37,
code: 'EPROTO',
description: 'protocol error'
},
{
errno: 38,
code: 'EPROTONOSUPPORT',
description: 'protocol not supported'
},
{
errno: 39,
code: 'EPROTOTYPE',
description: 'protocol wrong type for socket'
},
{
errno: 40,
code: 'ETIMEDOUT',
description: 'connection timed out'
},
{
errno: 41,
code: 'ECHARSET',
description: 'invalid Unicode character'
},
{
errno: 42,
code: 'EAIFAMNOSUPPORT',
description: 'address family for hostname not supported'
},
{
errno: 44,
code: 'EAISERVICE',
description: 'servname not supported for ai_socktype'
},
{
errno: 45,
code: 'EAISOCKTYPE',
description: 'ai_socktype not supported'
},
{
errno: 46,
code: 'ESHUTDOWN',
description: 'cannot send after transport endpoint shutdown'
},
{
errno: 47,
code: 'EEXIST',
description: 'file already exists'
},
{
errno: 48,
code: 'ESRCH',
description: 'no such process'
},
{
errno: 49,
code: 'ENAMETOOLONG',
description: 'name too long'
},
{
errno: 50,
code: 'EPERM',
description: 'operation not permitted'
},
{
errno: 51,
code: 'ELOOP',
description: 'too many symbolic links encountered'
},
{
errno: 52,
code: 'EXDEV',
description: 'cross-device link not permitted'
},
{
errno: 53,
code: 'ENOTEMPTY',
description: 'directory not empty'
},
{
errno: 54,
code: 'ENOSPC',
description: 'no space left on device'
},
{
errno: 55,
code: 'EIO',
description: 'i/o error'
},
{
errno: 56,
code: 'EROFS',
description: 'read-only file system'
},
{
errno: 57,
code: 'ENODEV',
description: 'no such device'
},
{
errno: 58,
code: 'ESPIPE',
description: 'invalid seek'
},
{
errno: 59,
code: 'ECANCELED',
description: 'operation canceled'
}
]
module.exports.errno = {}
module.exports.code = {}
all.forEach(function (error) {
module.exports.errno[error.errno] = error
module.exports.code[error.code] = error
})
module.exports.custom = require('./custom')(module.exports)
module.exports.create = module.exports.custom.createError
},{"./custom":133}],135:[function(require,module,exports){
/*!
* prr
* (c) 2013 Rod Vagg
* https://github.com/rvagg/prr
* License: MIT
*/
(function (name, context, definition) {
if (typeof module != 'undefined' && module.exports)
module.exports = definition()
else
context[name] = definition()
})('prr', this, function() {
var setProperty = typeof Object.defineProperty == 'function'
? function (obj, key, options) {
Object.defineProperty(obj, key, options)
return obj
}
: function (obj, key, options) { // < es5
obj[key] = options.value
return obj
}
, makeOptions = function (value, options) {
var oo = typeof options == 'object'
, os = !oo && typeof options == 'string'
, op = function (p) {
return oo
? !!options[p]
: os
? options.indexOf(p[0]) > -1
: false
}
return {
enumerable : op('enumerable')
, configurable : op('configurable')
, writable : op('writable')
, value : value
}
}
, prr = function (obj, key, value, options) {
var k
options = makeOptions(value, options)
if (typeof key == 'object') {
for (k in key) {
if (Object.hasOwnProperty.call(key, k)) {
options.value = key[k]
setProperty(obj, k, options)
}
}
return obj
}
return setProperty(obj, key, options)
}
return prr
})
},{}],136:[function(require,module,exports){
(function (root, factory) {
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define([], factory)
} else if (typeof exports === 'object') {
module.exports = factory()
} else {
root.PromisePool = factory()
// Legacy API
root.promisePool = root.PromisePool
}
})(this, function () {
'use strict'
var EventTarget = function () {
this._listeners = {}
}
EventTarget.prototype.addEventListener = function (type, listener) {
this._listeners[type] = this._listeners[type] || []
if (this._listeners[type].indexOf(listener) < 0) {
this._listeners[type].push(listener)
}
}
EventTarget.prototype.removeEventListener = function (type, listener) {
if (this._listeners[type]) {
var p = this._listeners[type].indexOf(listener)
if (p >= 0) {
this._listeners[type].splice(p, 1)
}
}
}
EventTarget.prototype.dispatchEvent = function (evt) {
if (this._listeners[evt.type] && this._listeners[evt.type].length) {
var listeners = this._listeners[evt.type].slice()
for (var i = 0, l = listeners.length; i < l; ++i) {
listeners[i].call(this, evt)
}
}
}
var isGenerator = function (func) {
return (typeof func.constructor === 'function' &&
func.constructor.name === 'GeneratorFunction')
}
var functionToIterator = function (func) {
return {
next: function () {
var promise = func()
return promise ? {value: promise} : {done: true}
}
}
}
var promiseToIterator = function (promise) {
var called = false
return {
next: function () {
if (called) {
return {done: true}
}
called = true
return {value: promise}
}
}
}
var toIterator = function (obj, Promise) {
var type = typeof obj
if (type === 'object') {
if (typeof obj.next === 'function') {
return obj
}
/* istanbul ignore else */
if (typeof obj.then === 'function') {
return promiseToIterator(obj)
}
}
if (type === 'function') {
return isGenerator(obj) ? obj() : functionToIterator(obj)
}
return promiseToIterator(Promise.resolve(obj))
}
var PromisePoolEvent = function (target, type, data) {
this.target = target
this.type = type
this.data = data
}
var PromisePool = function (source, concurrency, options) {
EventTarget.call(this)
if (typeof concurrency !== 'number' ||
Math.floor(concurrency) !== concurrency ||
concurrency < 1) {
throw new Error('Invalid concurrency')
}
this._concurrency = concurrency
this._options = options || {}
this._options.promise = this._options.promise || Promise
this._iterator = toIterator(source, this._options.promise)
this._done = false
this._size = 0
this._promise = null
this._callbacks = null
}
PromisePool.prototype = new EventTarget()
PromisePool.prototype.constructor = PromisePool
PromisePool.prototype.concurrency = function (value) {
if (typeof value !== 'undefined') {
this._concurrency = value
if (this.active()) {
this._proceed()
}
}
return this._concurrency
}
PromisePool.prototype.size = function () {
return this._size
}
PromisePool.prototype.active = function () {
return !!this._promise
}
PromisePool.prototype.promise = function () {
return this._promise
}
PromisePool.prototype.start = function () {
var that = this
var Promise = this._options.promise
this._promise = new Promise(function (resolve, reject) {
that._callbacks = {
reject: reject,
resolve: resolve
}
that._proceed()
})
return this._promise
}
PromisePool.prototype._fireEvent = function (type, data) {
this.dispatchEvent(new PromisePoolEvent(this, type, data))
}
PromisePool.prototype._settle = function (error) {
if (error) {
this._callbacks.reject(error)
} else {
this._callbacks.resolve()
}
this._promise = null
this._callbacks = null
}
PromisePool.prototype._onPooledPromiseFulfilled = function (promise, result) {
this._size--
if (this.active()) {
this._fireEvent('fulfilled', {
promise: promise,
result: result
})
this._proceed()
}
}
PromisePool.prototype._onPooledPromiseRejected = function (promise, error) {
this._size--
if (this.active()) {
this._fireEvent('rejected', {
promise: promise,
error: error
})
this._settle(error || new Error('Unknown error'))
}
}
PromisePool.prototype._trackPromise = function (promise) {
var that = this
promise
.then(function (result) {
that._onPooledPromiseFulfilled(promise, result)
}, function (error) {
that._onPooledPromiseRejected(promise, error)
})['catch'](function (err) {
that._settle(new Error('Promise processing failed: ' + err))
})
}
PromisePool.prototype._proceed = function () {
if (!this._done) {
var result = null
while (this._size < this._concurrency &&
!(result = this._iterator.next()).done) {
this._size++
this._trackPromise(result.value)
}
this._done = (result === null || !!result.done)
}
if (this._done && this._size === 0) {
this._settle()
}
}
PromisePool.PromisePoolEvent = PromisePoolEvent
// Legacy API
PromisePool.PromisePool = PromisePool
return PromisePool
})
},{}],137:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],138:[function(require,module,exports){
/**
* # hasLocalStorage()
*
* returns `true` or `false` depending on whether localStorage is supported or not.
* Beware that some browsers like Safari do not support localStorage in private mode.
*
* inspired by this cappuccino commit
* https://github.com/cappuccino/cappuccino/commit/063b05d9643c35b303568a28809e4eb3224f71ec
*
* @returns {Boolean}
*/
function hasLocalStorage() {
try {
// we've to put this in here. I've seen Firefox throwing `Security error: 1000`
// when cookies have been disabled
if (typeof localStorage === 'undefined') {
return false;
}
// Just because localStorage exists does not mean it works. In particular it might be disabled
// as it is when Safari's private browsing mode is active.
localStorage.setItem('Storage-Test', '1');
// that should not happen ...
if (localStorage.getItem('Storage-Test') !== '1') {
return false;
}
// okay, let's clean up if we got here.
localStorage.removeItem('Storage-Test');
} catch (_error) {
// in case of an error, like Safari's Private Mode, return false
return false;
}
// we're good.
return true;
}
if (typeof exports === 'object') {
module.exports = hasLocalStorage;
}
},{}],139:[function(require,module,exports){
(function (global){
var exports = module.exports = {};
var localStorageMemory = require('localstorage-memory');
exports.hasLocalStorage = require('has-localstorage');
/**
* returns localStorage-compatible API, either backed by window.localStorage
* or memory if it's not available or not persistent.
*
* It also adds an object API (`.getObject(key)`,
* `.setObject(key, properties)`) and a `isPresistent` property
*
* @returns {Object}
*/
exports.create = function () {
var api;
if (!exports.hasLocalStorage()) {
api = localStorageMemory;
api.isPersistent = false;
} else {
api = global.localStorage;
api = {
get length() { return global.localStorage.length; },
getItem: global.localStorage.getItem.bind(global.localStorage),
setItem: global.localStorage.setItem.bind(global.localStorage),
removeItem: global.localStorage.removeItem.bind(global.localStorage),
key: global.localStorage.key.bind(global.localStorage),
clear: global.localStorage.clear.bind(global.localStorage),
};
api.isPersistent = true;
}
api.getObject = exports.getObject.bind(null, api);
api.setObject = exports.setObject.bind(null, api);
return api;
};
/**
* sets key to passed Object.
*
* @returns undefined
*/
exports.setObject = function (store, key, object) {
if (typeof object !== 'object') {
return store.setItem(key, object);
}
return store.setItem(key, JSON.stringify(object));
};
/**
* returns Object for key, or null
*
* @returns {Object|null}
*/
exports.getObject = function (store, key) {
var item = store.getItem(key);
if (!item) {
return null;
}
try {
return JSON.parse(item);
} catch (e) {
return item;
}
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"has-localstorage":138,"localstorage-memory":173}],140:[function(require,module,exports){
var api = require('./api');
module.exports = api.create();
},{"./api":139}],141:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],142:[function(require,module,exports){
(function (global){
'use strict';
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode('');
observer.observe(element, {
characterData: true
});
scheduleDrain = function () {
element.data = (called = ++called % 2);
};
} else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
scheduleDrain = function () {
// Create a